Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2021-12-05 16:59:59 +01:00
commit 0330365d49
19 files changed
+1965 -149

No files matched your search

+10
View File
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 5.x Releases
- `5.16.x` Releases - [5.16.0](#5160)
- `5.15.x` Releases - [5.15.0](#5150)
- `5.14.x` Releases - [5.14.0](#5140)
- `5.13.x` Releases - [5.13.0](#5130)
@@ -82,6 +83,15 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 5.16.0
Released December 5, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.15.0...v5.16.0)
- **New**: [#1106](https://github.com/groue/GRDB.swift/pull/1106) by [@groue](https://github.com/groue): Sugar for fetching only a few columns of associated records
- **Documentation Update**: The [Joining And Prefetching Associated Records](Documentation/AssociationsBasics.md#joining-and-prefetching-associated-records) chapter was fully rewritten. The joining methods `including(required:)` and others are much more detailed, with an exploration of frequent use cases.
- **Documentation Update**: The [Joining And Prefetching Associated Records](Documentation/AssociationsBasics.md#joining-and-prefetching-associated-records) chapter introduces the new `annotated(withRequired:)` and `annotated(withOptional:)` joining methods.
- **Documentation Update**: The new [Choosing a Joining Method Given the Shape of the Decoded Type](Documentation/AssociationsBasics.md#choosing-a-joining-method-given-the-shape-of-the-decoded-type) chapter helps choosing a joining method, given the shape of the fetched data.
## 5.15.0
Released December 2, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.14.0...v5.15.0)
+492 -94
View File
@@ -842,125 +842,512 @@ let novels = try author
## Joining And Prefetching Associated Records
**You build requests that involve several records with the following "joining methods":**
You build requests that involve associations with one of the following "joining methods":
- `joining(optional: association)`
- `joining(required: association)`
- `including(optional: association)`
- `including(required: association)`
- `including(all: associationToMany)`
- Prefetch associated records:
- [`including(required:)`]
- [`including(optional:)`]
- [`including(all:)`]
- Prefetch only a few columns of an associated record:
- [`annotated(withRequired:)`]
- [`annotated(withOptional:)`]
- [`including(all:)`]
- Join associated records without prefetching:
- [`joining(required:)`]
- [`joining(optional:)`]
- [Choosing a Joining Method Given the Shape of the Decoded Type]
Before we describe them in detail, let's see a few requests they can build:
### `including(required:)`
For example, fetch books along with their author:
```swift
/// All authors with their respective books
let request = Author
.including(all: Author.books)
/// All authors with their awarded books
let request = Author
.including(all: Author.books.having(Book.awards.isEmpty == false))
/// All books with their respective author
let request = Book
.including(required: Book.author)
/// All books with their respective author, sorted by title
let request = Book
.including(required: Book.author)
.order(Column("title"))
/// All books written by a French author
let request = Book
.joining(required: Book.author.filter(Column("countryCode") == "FR"))
// SELECT book.*, author.*
// FROM book
// JOIN author ON author.id = book.authorId
let request = Book.including(required: Book.author)
```
The pattern is always the same: you start from a base request, that you extend with one of the joining methods.
This method accepts any association. It has the base record fetched along with one associated record, which is "included" in the fetched results. When the associated record does not exist, records are not present in the fetched results: the associated record is "required".
**To choose the joining method you need, you ask yourself two questions:**
**To fetch results from such a request**, you define a dedicated record type:
```swift
// Fetch all books along with their author
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var author: Author // The required associated record
}
let bookInfos = try Book
.including(required: Book.author)
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
**The CodingKey for the `BookInfo.author` property must match the association key of the `Book.author` association.** The association key is, by default, the name of the associated database table. This can be configured with the association `forKey(_:)` method:
```swift
struct Author: TableRecord {
static let databaseTableName = "writer"
}
struct Book: TableRecord {
// Replace the defaut "writer" association key with "author"
static let author = belongsTo(Author.self).forKey("author")
}
// Fetch all books along with their author
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var author: Author // Matches the "author" association key
}
let bookInfos = try Book
.including(required: Book.author)
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
**When you only need a few columns of the associated record**, you can define a partial type with one property per selected column of the associated record:
```swift
// Fetch all books along with the name and country of their author
struct BookInfo: Decodable, FetchableRecord {
struct PartialAuthor: Decodable {
var name: String
var country: String
}
var book: Book
var author: PartialAuthor
}
let bookInfos = try Book
.including(required: Book.author.select(Column("name"), Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
But if you'd rather avoid this extra partial type, prefer [`annotated(withRequired:)`]:
```swift
// Fetch all books along with the country of their author
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var country: String
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
### `including(optional:)`
For example, fetch books along with their eventual author:
```swift
// SELECT book.*, author.*
// FROM book
// LEFT JOIN author ON author.id = book.authorId
let request = Book.including(optional: Book.author)
```
This method accepts any association. It has the base record fetched along with one associated record, which is "included" in the fetched results. The associated record can be missing: it is "optional".
**To fetch results from such a request**, you define a dedicated record type:
```swift
// Fetch all books along with their eventual author
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var author: Author? // The optional associated record
}
let bookInfos = try Book
.including(optional: Book.author)
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
**The CodingKey for the `BookInfo.author` property must match the association key of the `Book.author` association.** See [`including(required:)`] for more information.
**When you only need a few columns of the associated record**, you can define a partial type with one property per selected column of the associated record:
```swift
// Fetch all books along with the name and country of their eventual author
struct BookInfo: Decodable, FetchableRecord {
struct PartialAuthor: Decodable {
var name: String
var country: String
}
var book: Book
var author: PartialAuthor?
}
let bookInfos = try Book
.including(optional: Book.author.select(Column("name"), Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
But if you'd rather avoid this extra partial type, prefer [`annotated(withOptional:)`]:
```swift
// Fetch all books along with the country of their eventual author
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var country: String?
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
### `including(all:)`
For example, fetch authors along with their books:
```swift
// SELECT author.* FROM author
// SELECT book.* FROM book WHERE authorId IN (...)
let request = Author.including(all: Author.books)
```
This method accepts any to-many association ([HasMany] or [HasManyThrough]). It has the base record fetched along with all its associated records, which are "included" in the fetched results.
**To fetch results from such a request**, you define a dedicated record type:
```swift
// Fetch all authors along with their books
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author // The base record
var books: [Book] // A collection of associated records
}
let authorInfos = try Author
.including(all: Author.books)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
The associated records can be stored into an Array as in the above example, but also a Set, and generally speaking any decodable Swift collection.
**The CodingKey for the `AuthorInfo.books` property must match the association key of the `Author.books` association.** The association key is, by default, the pluralized name of the associated database table. This can be configured with the association `forKey(_:)` method:
```swift
struct Book: TableRecord {
static let databaseTableName = "publication"
}
struct Author: TableRecord {
// Replace the defaut "publications" association key with "books"
static let books = hasMany(Book.self).forKey("books")
}
// Fetch all authors along with their books
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var books: [Book] // Matches the "books" association key
}
let authorInfos = try Author
.including(all: Author.books)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
**When you only need a few columns of the associated records**, you can define a partial type with one property per selected column of the associated record:
```swift
// Fetch all authors along with the titles and years of their books
struct AuthorInfo: Decodable, FetchableRecord {
struct PartialBook: Decodable {
var title: String
var year: Int
}
var author: Author
var books: [PartialBook]
}
let authorInfos = try Author
.including(all: Author.books.select(Column("title"), Column("year")))
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
When you need a single column of the associated records, avoid the extra partial type, and instead use the association `forKey(_:)` method in order to match the name of the decoded property:
```swift
// Fetch all authors along with the titles of their books
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookTitles: [String]
}
let authorInfos = try Author
.including(all: Author.books
.select(Column("title"))
.forKey("bookTitles"))
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
### `annotated(withRequired:)`
For example, fetch books along with the name and country of their author:
```swift
// SELECT book.*, author.name, author.country
// FROM book
// JOIN author ON author.id = book.authorId
let request = Book.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
```
This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, records are not present in the fetched results: the associated record is "required".
**To fetch results from such a request**, you define a dedicated record type:
```swift
// Fetch all books along with the name and country of their author
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var name: String // A column of the required associated record
var country: String // A column of the required associated record
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
If the name of a column of the associated record is also the name of a column of the base record, rename the associated column with the column `forKey(_:)` method, and accordingly rename the property of the decoded record type:
```swift
// Fetch all books along with the name of their author
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var authorName: String
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(Column("name").forKey("authorName")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
### `annotated(withOptional:)`
For example, fetch books along with the name and country of their eventual author:
```swift
// SELECT book.*, author.name, author.country
// FROM book
// LEFT JOIN author ON author.id = book.authorId
let request = Book.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
```
This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, the columns of the associated record are NULL: the associated record is "optional".
**To fetch results from such a request**, you define a dedicated record type:
```swift
// Fetch all books along with the name of their eventual author
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var name: String? // A column of the optional associated record
var country: String? // A column of the optional associated record
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
If the name of a column of the associated record is also the name of a column of the base record, rename the associated column with the column `forKey(_:)` method, and accordingly rename the property of the decoded record type:
```swift
// Fetch all books along with the name of their eventual author
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var authorName: String?
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(Column("name").forKey("authorName")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
### `joining(required:)`
For example, fetch books by French authors:
```swift
// SELECT book.*
// FROM book
// JOIN author ON author.id = book.authorId
// AND author.country = 'France'
let request = Book.joining(required: Book.author.filter(Column("country") == "France"))
```
This method accepts any association. It has the base record "joined" with one associated record, which is not included in the fetched results. When the associated record does not exist, the base record is not present in the fetched results: the associated record is "required".
To fetch results from such a request, you do not need to define a dedicated record type:
```swift
// Fetch all books by French authors
let books = try Book
.joining(required: Book.author.filter(Column("country") == "France"))
.fetchAll(db)
```
### `joining(optional:)`
```swift
// SELECT book.*
// FROM book
// LEFT JOIN author ON author.id = book.authorId
let request = Book.joining(optional: Book.author)
```
This method accepts any association. It has the base record "joined" with one associated record, which is not included in the fetched results. The associated record can be missing: it is "optional".
This method has no observable effect unless the associated record is used in a way or another. We'll see examples later in this documentation.
### Choosing a Joining Method Given the Shape of the Decoded Type
In the description of the [joining methods] above, we have seen that you need to define dedicated record types in order to prefetch associated records. Each joining method needs a dedicated record type to have a specific shape.
In this chapter, we take the reversed perspective. We list various shapes of decoded record types. When you find the type you want, you'll know the joining method you need.
> :point_up: **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level apis described in [Decoding a Joined Request with FetchableRecord].
- [`including(required:)`]
1. Should the associated records be fetched along with the base records?
If yes, use `including(...)`. Otherwise, use `joining(...)`.
For example, to load books with their respective author, you use `including(required:)`:
```swift
// All books with their respective author
let request = Book
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var author: Author // The associated record
}
let bookInfos = try Book
.including(required: Book.author)
// This request can feed the following record:
struct BookInfo: FetchableRecord, Decodable {
var book: Book
var author: Author // the required associated author
}
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
And to load authors with their respective books, you use `including(all:)`:
```swift
// All authors with their respective books
let request = Author
.including(all: Author.books)
// This request can feed the following record:
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var books: [Book] // all associated books
struct BookInfo: Decodable, FetchableRecord {
struct PartialAuthor: Decodable {
var name: String
var country: String
}
var book: Book // The base record
var author: PartialAuthor // The partial associated record
}
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
On the other side, to load all books written by a French author, you sure need to filter authors, but you don't need them to be present in the fetched results. You prefer `joining`:
```swift
// All books written by a French author
let request = Book
.joining(required: Book.author.filter(Column("countryCode") == "FR"))
// This request feeds the Book record:
let books: [Book] = try request.fetchAll(db)
let bookInfos = try Book
.including(required: Book.author.select(Column("name"), Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
2. For to-one associations, should the request allow missing associated records?
If yes, choose the `optional` variant. Otherwise, choose `required`.
For example, to load all books with their respective authors, even if the book has no recorded author, you'd use `including(optional:)`:
- [`annotated(withRequired:)`]
```swift
// All books with their respective (eventual) authors
let request = Book
.including(optional: Book.author)
// This request can feed the following record:
struct BookInfo: FetchableRecord, Decodable {
var book: Book
var author: Author? // the optional associated author
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var authorName: String // A column of the associated record
var country: String // A column of the associated record
}
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
let bookInfos = try Book
.annotated(withRequired: Book.author.select(
Column("name").forKey("authorName"),
Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
- [`including(optional:)`]
```swift
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var author: Author? // The eventual associated record
}
let bookInfos = try Book
.including(optional: Book.author)
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
You can remember to use `optional` when the fetched associated records should feed optional Swift values, of type `Author?`. Conversely, when the fetched results feed non-optional values of type `Author`, prefer `required`.
```swift
struct BookInfo: Decodable, FetchableRecord {
struct PartialAuthor: Decodable {
var name: String
var country: String
}
var book: Book // The base record
var author: PartialAuthor? // The eventual partial associated record
}
Another way to describe the difference is that `required` filters the fetched results in order to discard missing associated records, when `optional` does not filter anything, and lets missing values pass through.
Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins:
let bookInfos = try Book
.including(optional: Book.author.select(Column("name"), Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
- [`annotated(withOptional:)`]
```swift
// SELECT book.* FROM book LEFT JOIN author ON author.id = book.authorID
Book.joining(optional: Book.author)
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var authorName: String? // A column of the eventual associated record
var country: String? // A column of the eventual associated record
}
// SELECT book.* FROM book JOIN author ON author.id = book.authorID
Book.joining(required: Book.author)
let bookInfos = try Book
.annotated(withOptional: Book.author.select(
Column("name").forKey("authorName"),
Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
- [`including(all:)`]
// SELECT book.*, author.* FROM book LEFT JOIN author ON author.id = book.authorID
Book.including(optional: Book.author)
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author // The base record
var books: [Book] // A collection of associated records
}
// SELECT book.*, author.* FROM book JOIN author ON author.id = book.authorID
Book.including(required: Book.author)
let authorInfos = try Author
.including(all: Author.books)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
```swift
struct AuthorInfo: Decodable, FetchableRecord {
struct PartialBook: Decodable {
var title: String
var year: Int
}
var author: Author // The base record
var books: [PartialBook] // A collection of partial associated records
}
let authorInfos = try Author
.including(all: Author.books.select(Column("title"), Column("year")))
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author // The base record
var bookTitles: [String] // A collection of one column of the associated records
}
let authorInfos = try Author
.including(all: Author.books
.select(Column("title"))
.forKey("bookTitles"))
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
@@ -1243,7 +1630,7 @@ let teamInfos = try Team
## Columns Selected by an Association
By default, associated records include all their columns:
By default, associated records, like all records, include all their columns:
```swift
// SELECT book.*, author.*
@@ -1254,7 +1641,9 @@ let request = Book.including(required: Book.author)
**The selection can be changed for each individual request, or for all requests including a given type.**
To specify the selection of an associated record in a specific request, use the `select` method:
To specify the default selection for a given record type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request).
To specify the selection in a specific request, use the `select` method:
```swift
// SELECT book.*, author.id, author.name
@@ -1264,7 +1653,7 @@ let restrictedAuthor = Book.author.select(Column("id"), Column("name"))
let request = Book.including(required: restrictedAuthor)
```
To specify the default selection for all inclusions of a given type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request).
In order to fetch from such requests of partial records, see the documentation of the [joining methods].
## Further Refinements to Associations
@@ -2568,6 +2957,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Requesting Associated Records]: #requesting-associated-records
[requests for associated records]: #requesting-associated-records
[Joining And Prefetching Associated Records]: #joining-and-prefetching-associated-records
[joining methods]: #joining-and-prefetching-associated-records
[Filtering Associations]: #filtering-associations
[Sorting Associations]: #sorting-associations
[Columns Selected by an Association]: #columns-selected-by-an-association
@@ -2603,3 +2993,11 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[common table expressions]: CommonTableExpressions.md
[Common Table Expressions]: CommonTableExpressions.md
[Associations to Common Table Expressions]: CommonTableExpressions.md#associations-to-common-table-expressions
[`including(required:)`]: #includingrequired
[`including(optional:)`]: #includingoptional
[`including(all:)`]: #includingall
[`annotated(withRequired:)`]: #annotatedwithrequired
[`annotated(withOptional:)`]: #annotatedwithoptional
[`joining(required:)`]: #joiningrequired
[`joining(optional:)`]: #joiningoptional
[Choosing a Joining Method Given the Shape of the Decoded Type]: #choosing-a-joining-method-given-the-shape-of-the-decoded-type
+2 -2
View File
@@ -304,7 +304,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html):
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -587,7 +587,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html):
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
+1 -1
View File
@@ -77,7 +77,7 @@ try dbQueue.read { db in
}
```
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.15/Structs/DatabaseMigrator.html) for more migrator methods.
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.16/Structs/DatabaseMigrator.html) for more migrator methods.
## The `eraseDatabaseOnSchemaChange` Option
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '5.15.0'
s.version = '5.16.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
@@ -7,9 +7,9 @@ import Foundation
public protocol TypedRequest {
/// The type that can decode database rows.
///
/// In the request below, it is Book:
/// In the request below, it is Player:
///
/// let request = Book.all()
/// let request = Player.all()
associatedtype RowDecoder
}
@@ -703,6 +703,94 @@ extension JoinableRequest {
}
}
extension JoinableRequest where Self: SelectionRequest {
/// Creates a request which appends *columns of an associated record* to
/// the current selection.
///
/// // SELECT player.*, team.color
/// // FROM player LEFT JOIN team ...
/// let teamColor = Player.team.select(Column("color"))
/// let request = Player.all().annotated(withOptional: teamColor)
///
/// This method performs the same SQL request as `including(optional:)`.
/// The difference is in the shape of Decodable records that decode such
/// a request: the associated columns can be decoded at the same level as
/// the main record:
///
/// struct PlayerWithTeamColor: FetchableRecord, Decodable {
/// var player: Player
/// var color: String?
/// }
/// let players = try dbQueue.read { db in
/// try request
/// .asRequest(of: PlayerWithTeamColor.self)
/// .fetchAll(db)
/// }
///
/// Note: this is a convenience method. You can build the same request with
/// `TableAlias`, `annotated(with:)`, and `joining(optional:)`:
///
/// let teamAlias = TableAlias()
/// let request = Player.all()
/// .annotated(with: teamAlias[Column("color")])
/// .joining(optional: Player.team.aliased(teamAlias))
public func annotated<A: Association>(withOptional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
// TODO: find a way to prefix the selection with the association key
let alias = TableAlias()
let selection = association._sqlAssociation.destination.relation.selectionPromise
return self
.joining(optional: association.aliased(alias))
.annotated(with: { db in
try selection.resolve(db).map { selection in
selection.qualified(with: alias)
}
})
}
/// Creates a request which appends *columns of an associated record* to
/// the current selection.
///
/// // SELECT player.*, team.color
/// // FROM player JOIN team ...
/// let teamColor = Player.team.select(Column("color"))
/// let request = Player.all().annotated(withRequired: teamColor)
///
/// This method performs the same SQL request as `including(required:)`.
/// The difference is in the shape of Decodable records that decode such
/// a request: the associated columns can be decoded at the same level as
/// the main record:
///
/// struct PlayerWithTeamColor: FetchableRecord, Decodable {
/// var player: Player
/// var color: String
/// }
/// let players = try dbQueue.read { db in
/// try request
/// .asRequest(of: PlayerWithTeamColor.self)
/// .fetchAll(db)
/// }
///
/// Note: this is a convenience method. You can build the same request with
/// `TableAlias`, `annotated(with:)`, and `joining(required:)`:
///
/// let teamAlias = TableAlias()
/// let request = Player.all()
/// .annotated(with: teamAlias[Column("color")])
/// .joining(required: Player.team.aliased(teamAlias))
public func annotated<A: Association>(withRequired association: A) -> Self where A.OriginRowDecoder == RowDecoder {
// TODO: find a way to prefix the selection with the association key
let selection = association._sqlAssociation.destination.relation.selectionPromise
let alias = TableAlias()
return self
.joining(required: association.aliased(alias))
.annotated(with: { db in
try selection.resolve(db).map { selection in
selection.qualified(with: alias)
}
})
}
}
// MARK: - DerivableRequest
/// The base protocol for all requests that can be refined.
@@ -797,20 +885,20 @@ extension DerivableRequest {
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: Player.books.count)
/// // SELECT team.*, COUNT(DISTINCT player.id) AS playerCount
/// // FROM team LEFT JOIN player ...
/// var request = Team.all()
/// request = request.annotated(with: Team.players.count)
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> Self {
annotated(with: aggregates)
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: [Player.books.count])
/// // SELECT team.*, COUNT(DISTINCT player.id) AS playerCount
/// // FROM team LEFT JOIN player ...
/// var request = team.all()
/// request = request.annotated(with: [Team.players.count])
public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> Self {
aggregates.reduce(self) { request, aggregate in
request.annotated(with: aggregate)
@@ -820,11 +908,11 @@ extension DerivableRequest {
/// Creates a request which appends the provided aggregate *predicate* to
/// the eventual set of already applied predicates.
///
/// // SELECT player.*
/// // FROM player LEFT JOIN book ...
/// // HAVING COUNT(DISTINCT book.id) = 0
/// var request = Player.all()
/// request = request.having(Player.books.isEmpty)
/// // SELECT team.*
/// // FROM team LEFT JOIN player ...
/// // HAVING COUNT(DISTINCT player.id) = 0
/// var request = Team.all()
/// request = request.having(Team.players.isEmpty)
public func having(_ predicate: AssociationAggregate<RowDecoder>) -> Self {
var request = self
let expression = predicate.prepare(&request)
+82
View File
@@ -1186,6 +1186,88 @@ extension Table {
{
all().joining(required: association)
}
/// Creates a request which appends *columns of an associated record* to
/// the columns of the table.
///
/// let playerTable = Table("player")
/// let teamTable = Table("team")
/// let playerTeam = playerTable.belongsTo(teamTable)
///
/// // SELECT player.*, team.color
/// // FROM player LEFT JOIN team ...
/// let teamColor = playerTeam.select(Column("color")
/// let request = playerTable.annotated(withOptional: teamColor))
///
/// This method performs the same SQL request as `including(optional:)`.
/// The difference is in the shape of Decodable records that decode such
/// a request: the associated columns can be decoded at the same level as
/// the main record:
///
/// struct PlayerWithTeamColor: FetchableRecord, Decodable {
/// var player: Player
/// var color: String?
/// }
/// let players = try dbQueue.read { db in
/// try request
/// .asRequest(of: PlayerWithTeamColor.self)
/// .fetchAll(db)
/// }
///
/// Note: this is a convenience method. You can build the same request with
/// `TableAlias`, `annotated(with:)`, and `joining(optional:)`:
///
/// let teamAlias = TableAlias()
/// let request = playerTable
/// .annotated(with: teamAlias[Column("color")])
/// .joining(optional: playerTeam.aliased(teamAlias))
public func annotated<A: Association>(withOptional association: A)
-> QueryInterfaceRequest<RowDecoder>
where A.OriginRowDecoder == RowDecoder
{
all().annotated(withOptional: association)
}
/// Creates a request which appends *columns of an associated record* to
/// the columns of the table.
///
/// let playerTable = Table("player")
/// let teamTable = Table("team")
/// let playerTeam = playerTable.belongsTo(teamTable)
///
/// // SELECT player.*, team.color
/// // FROM player JOIN team ...
/// let teamColor = playerTeam.select(Column("color")
/// let request = playerTable.annotated(withRequired: teamColor))
///
/// This method performs the same SQL request as `including(required:)`.
/// The difference is in the shape of Decodable records that decode such
/// a request: the associated columns can be decoded at the same level as
/// the main record:
///
/// struct PlayerWithTeamColor: FetchableRecord, Decodable {
/// var player: Player
/// var color: String
/// }
/// let players = try dbQueue.read { db in
/// try request
/// .asRequest(of: PlayerWithTeamColor.self)
/// .fetchAll(db)
/// }
///
/// Note: this is a convenience method. You can build the same request with
/// `TableAlias`, `annotated(with:)`, and `joining(required:)`:
///
/// let teamAlias = TableAlias()
/// let request = playerTable
/// .annotated(with: teamAlias[Column("color")])
/// .joining(required: playerTeam.aliased(teamAlias))
public func annotated<A: Association>(withRequired association: A)
-> QueryInterfaceRequest<RowDecoder>
where A.OriginRowDecoder == RowDecoder
{
all().annotated(withRequired: association)
}
}
// MARK: - Association Aggregates
@@ -620,6 +620,80 @@ extension TableRecord {
{
all().joining(required: association)
}
/// Creates a request which appends *columns of an associated record* to
/// the selection.
///
/// // SELECT player.*, team.color
/// // FROM player LEFT JOIN team ...
/// let teamColor = Player.team.select(Column("color"))
/// let request = Player.annotated(withOptional: teamColor)
///
/// This method performs the same SQL request as `including(optional:)`.
/// The difference is in the shape of Decodable records that decode such
/// a request: the associated columns can be decoded at the same level as
/// the main record:
///
/// struct PlayerWithTeamColor: FetchableRecord, Decodable {
/// var player: Player
/// var color: String?
/// }
/// let players = try dbQueue.read { db in
/// try request
/// .asRequest(of: PlayerWithTeamColor.self)
/// .fetchAll(db)
/// }
///
/// Note: this is a convenience method. You can build the same request with
/// `TableAlias`, `annotated(with:)`, and `joining(optional:)`:
///
/// let teamAlias = TableAlias()
/// let request = Player
/// .annotated(with: teamAlias[Column("color")])
/// .joining(optional: Player.team.aliased(teamAlias))
public static func annotated<A: Association>(withOptional association: A)
-> QueryInterfaceRequest<Self>
where A.OriginRowDecoder == Self
{
all().annotated(withOptional: association)
}
/// Creates a request which appends *columns of an associated record* to
/// the selection.
///
/// // SELECT player.*, team.color
/// // FROM player JOIN team ...
/// let teamColor = Player.team.select(Column("color"))
/// let request = Player.annotated(withRequired: teamColor)
///
/// This method performs the same SQL request as `including(required:)`.
/// The difference is in the shape of Decodable records that decode such
/// a request: the associated columns can be decoded at the same level as
/// the main record:
///
/// struct PlayerWithTeamColor: FetchableRecord, Decodable {
/// var player: Player
/// var color: String
/// }
/// let players = try dbQueue.read { db in
/// try request
/// .asRequest(of: PlayerWithTeamColor.self)
/// .fetchAll(db)
/// }
///
/// Note: this is a convenience method. You can build the same request with
/// `TableAlias`, `annotated(with:)`, and `joining(required:)`:
///
/// let teamAlias = TableAlias()
/// let request = Player
/// .annotated(with: teamAlias[Column("color")])
/// .joining(required: Player.team.aliased(teamAlias))
public static func annotated<A: Association>(withRequired association: A)
-> QueryInterfaceRequest<Self>
where A.OriginRowDecoder == Self
{
all().annotated(withRequired: association)
}
}
// MARK: - Aggregates
+3 -3
View File
@@ -488,10 +488,10 @@ ifdef JAZZY
--author 'Gwendal Roué' \
--author_url https://github.com/groue \
--github_url https://github.com/groue/GRDB.swift \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.15.0 \
--module-version 5.15.0 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.16.0 \
--module-version 5.16.0 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/5.15/ \
--root-url http://groue.github.io/GRDB.swift/docs/5.16/ \
--output Documentation/Reference \
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
else
+24 -30
View File
@@ -11,13 +11,13 @@
---
**Latest release**: December 2, 2021 • [version 5.15.0](https://github.com/groue/GRDB.swift/tree/v5.15.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
**Latest release**: December 5, 2021 • [version 5.16.0](https://github.com/groue/GRDB.swift/tree/v5.16.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
**Requirements**: iOS 11.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ &bull; SQLite 3.8.5+ &bull; Swift 5.3+ / Xcode 12+
| Swift version | GRDB version |
| -------------- | ----------------------------------------------------------- |
| **Swift 5.3+** | **v5.15.0** |
| **Swift 5.3+** | **v5.16.0** |
| Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) |
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
@@ -317,7 +317,7 @@ Documentation
#### Reference
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.15/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.16/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
#### Getting Started
@@ -511,7 +511,7 @@ let dbQueue = try DatabaseQueue(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.15/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.16/Structs/Configuration.html) for more details.
## Database Pools
@@ -591,7 +591,7 @@ let dbPool = try DatabasePool(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.15/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.16/Structs/Configuration.html) for more details.
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
@@ -651,7 +651,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details.
@@ -909,7 +909,7 @@ try dbQueue.read { db in
let dictionary = try Dictionary(uniqueKeysWithValues: cursor)
```
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.15/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.16/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
```swift
// Prints all Github links
@@ -988,7 +988,7 @@ let rows = try Row.fetchAll(db,
arguments: ["name": "Arthur"])
```
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
@@ -1273,7 +1273,7 @@ GRDB ships with built-in support for the following value types:
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html):
```swift
let url: URL = ...
@@ -1720,7 +1720,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
}
```
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.15/Structs/Configuration.html) configuration flag:
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.16/Structs/Configuration.html) configuration flag:
```swift
// fatal error: A transaction has been left opened at the end of a database access
@@ -1832,7 +1832,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
```swift
insertStatement.arguments = ["name": "Arthur", "score": 1000]
@@ -1915,7 +1915,7 @@ See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates)
> :point_up: **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so.
For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.15/Classes/Statement.html).
For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.16/Classes/Statement.html).
### Prepared Statements Cache
@@ -2658,7 +2658,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set<Place>
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
```
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html) for more information about the query arguments.
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html) for more information about the query arguments.
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
@@ -3098,7 +3098,7 @@ protocol EncodableRecord {
}
```
See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies.
See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.16/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.16/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies.
### Date and UUID Coding Strategies
@@ -3120,7 +3120,7 @@ protocol EncodableRecord {
}
```
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.16/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.16/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.16/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase).
@@ -4642,7 +4642,7 @@ Player // SELECT * FROM player
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -5410,7 +5410,7 @@ try Player.customRequest().fetchAll(db) // [Player]
- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.15/Structs/AnyFetchRequest.html): a type-erased request.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.16/Structs/AnyFetchRequest.html): a type-erased request.
## Joined Queries Support
@@ -6700,7 +6700,7 @@ DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track ch
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.15/Structs/DatabaseRegion.html).
For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.16/Structs/DatabaseRegion.html).
#### The DatabaseRegionConvertible Protocol
@@ -7824,11 +7824,9 @@ struct BookInfo: Decodable, FetchableRecord {
// SELECT book.*, author.name AS authorName
// FROM book
// LEFT JOIN author ON author.id = book.authorID
let authorAlias = TableAlias()
let authorName = authorAlias[Author.Columns.name].forKey(CodingKeys.authorName)
let authorName = Author.Columns.name.forKey(CodingKeys.authorName)
return Book
.annotated(with: authorName)
.joining(optional: Book.author.aliased(authorAlias))
.annotated(withOptional: Book.author.select(authorName))
.asRequest(of: BookInfo.self)
}
}
@@ -7838,13 +7836,9 @@ let bookInfos: [BookInfo] = try dbQueue.read { db in
}
```
By using a TableAlias, you can refer to an author column from a request of books.
By defining the request as a static method of BookInfo, you have access to the private `CodingKeys.authorName`, and a compiler-checked SQL column name.
By using the `annotated(with:)` method, you append the author name to the top-level selection that can be decoded by the ad-hoc record.
By using the `joining()` method, you make sure no author column is selected, but the one declared in `annotated(with:)`.
By using the `annotated(withOptional:)` method, you append the author name to the top-level selection that can be decoded by the ad-hoc record.
By using `asRequest(of:)`, you enhance the type-safety of your request.
@@ -7985,7 +7979,7 @@ When this is the case, there are two possible explanations:
try db.execute(sql: "UPDATE player SET name = ?", arguments: [name])
```
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.15/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.16/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
@@ -8126,7 +8120,7 @@ This chapter has [moved](Documentation/Concurrency.md#database-snapshots).
#### DatabaseWriter and DatabaseReader Protocols
This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.15/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.15/Protocols/DatabaseWriter.html).
This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.16/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.16/Protocols/DatabaseWriter.html).
#### Asynchronous APIs
@@ -8174,7 +8168,7 @@ This chapter has [moved](Documentation/Concurrency.md#safe-and-unsafe-database-a
[Sharing a Database]: Documentation/SharingADatabase.md
[FAQ]: #faq
[Database Observation]: #database-changes-observation
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.15/Structs/SQLRequest.html
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.16/Structs/SQLRequest.html
[SQL literal]: Documentation/SQLInterpolation.md#sql-literal
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
[Query Interface Organization]: Documentation/QueryInterfaceOrganization.md
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>5.15.0</string>
<string>5.16.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -27,6 +27,11 @@ private struct PlayerWithOptionalTeam: Decodable, FetchableRecord {
static let team = Player.team.forKey(CodingKeys.team)
}
private struct PlayerWithTeamName: Decodable, FetchableRecord {
var player: Player
var teamName: String?
}
extension QueryInterfaceRequest where RowDecoder == Player {
func filter(teamName: String) -> QueryInterfaceRequest<Player> {
joining(required: PlayerWithOptionalTeam.team.filter(Column("name") == teamName))
@@ -74,6 +79,19 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase {
XCTAssertEqual(records[0].team.name, "Reds")
}
func testAnnotatedWithRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player
.annotated(withRequired: Player.team.select(Column("name").forKey("teamName")))
.asRequest(of: PlayerWithTeamName.self)
let records = try dbQueue.inDatabase { try request.fetchAll($0) }
XCTAssertEqual(records.count, 1)
XCTAssertEqual(records[0].player.id, 1)
XCTAssertEqual(records[0].player.teamId, 1)
XCTAssertEqual(records[0].player.name, "Arthur")
XCTAssertEqual(records[0].teamName, "Reds")
}
func testIncludingOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player
@@ -92,6 +110,22 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase {
XCTAssertNil(records[1].team)
}
func testAnnotatedWithOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player
.annotated(withOptional: Player.team.select(Column("name").forKey("teamName")))
.asRequest(of: PlayerWithTeamName.self)
let records = try dbQueue.inDatabase { try request.fetchAll($0) }
XCTAssertEqual(records.count, 2)
XCTAssertEqual(records[0].player.id, 1)
XCTAssertEqual(records[0].player.teamId, 1)
XCTAssertEqual(records[0].player.name, "Arthur")
XCTAssertEqual(records[0].teamName, "Reds")
XCTAssertEqual(records[1].player.id, 2)
XCTAssertEqual(records[1].player.name, "Barbara")
XCTAssertNil(records[1].teamName)
}
func testJoiningRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.joining(required: Player.team)
@@ -36,6 +36,16 @@ private struct PlayerWithOptionalTeam: FetchableRecord {
}
}
private struct PlayerWithTeamName: FetchableRecord {
var player: Player
var teamName: String?
init(row: Row) {
player = Player(row: row)
teamName = row["teamName"]
}
}
/// Test support for FetchableRecord records
class AssociationBelongsToFetchableRecordTests: GRDBTestCase {
@@ -71,6 +81,19 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase {
XCTAssertEqual(records[0].team.name, "Reds")
}
func testAnnotatedWithRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player
.annotated(withRequired: Player.team.select(Column("name").forKey("teamName")))
.asRequest(of: PlayerWithTeamName.self)
let records = try dbQueue.inDatabase { try request.fetchAll($0) }
XCTAssertEqual(records.count, 1)
XCTAssertEqual(records[0].player.id, 1)
XCTAssertEqual(records[0].player.teamId, 1)
XCTAssertEqual(records[0].player.name, "Arthur")
XCTAssertEqual(records[0].teamName, "Reds")
}
func testIncludingOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player
@@ -89,6 +112,22 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase {
XCTAssertNil(records[1].team)
}
func testAnnotatedWithOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player
.annotated(withOptional: Player.team.select(Column("name").forKey("teamName")))
.asRequest(of: PlayerWithTeamName.self)
let records = try dbQueue.inDatabase { try request.fetchAll($0) }
XCTAssertEqual(records.count, 2)
XCTAssertEqual(records[0].player.id, 1)
XCTAssertEqual(records[0].player.teamId, 1)
XCTAssertEqual(records[0].player.name, "Arthur")
XCTAssertEqual(records[0].teamName, "Reds")
XCTAssertEqual(records[1].player.id, 2)
XCTAssertEqual(records[1].player.name, "Barbara")
XCTAssertNil(records[1].teamName)
}
func testJoiningRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.joining(required: Player.team)
@@ -99,7 +138,7 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase {
XCTAssertEqual(players[0].name, "Arthur")
}
func testJoiningsOptional() throws {
func testJoiningOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.joining(optional: Player.team)
let players = try dbQueue.inDatabase { try request.fetchAll($0) }
@@ -66,6 +66,22 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[0].scopes["team"]!, ["id":1, "name":"Reds"])
}
func testDefaultScopeAnnotatedWithRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withRequired: Player.defaultTeam)
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1, "name":"Reds"])
}
func testDefaultScopeAnnotatedWithRequiredCustomSelection() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withRequired: Player.defaultTeam.select(Column("name").forKey("teamName")))
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"])
}
func testDefaultScopeIncludingOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.including(optional: Player.defaultTeam)
@@ -79,6 +95,24 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[1].scopes["team"]!, ["id":nil, "name":nil])
}
func testDefaultScopeAnnotatedWithOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withOptional: Player.defaultTeam)
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1, "name":"Reds"])
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "id":nil, "name":nil])
}
func testDefaultScopeAnnotatedWithOptionalCustomSelection() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withOptional: Player.defaultTeam.select(Column("name").forKey("teamName")))
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"])
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "teamName":nil])
}
func testDefaultScopeJoiningRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.joining(required: Player.defaultTeam)
@@ -118,7 +152,23 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(Set(rows[0].scopes.names), ["customTeam"])
XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"])
}
func testCustomScopeAnnotatedWithRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withRequired: Player.customTeam)
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1, "name":"Reds"])
}
func testCustomScopeAnnotatedWithRequiredCustomSelection() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withRequired: Player.customTeam.select(Column("name").forKey("teamName")))
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"])
}
func testCustomScopeIncludingOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.including(optional: Player.customTeam)
@@ -132,6 +182,24 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[1].scopes["customTeam"]!, ["id":nil, "name":nil])
}
func testCustomScopeAnnotatedWithOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withOptional: Player.customTeam)
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1, "name":"Reds"])
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "id":nil, "name":nil])
}
func testCustomScopeAnnotatedWithOptionalCustomSelection() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withOptional: Player.customTeam.select(Column("name").forKey("teamName")))
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"])
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "teamName":nil])
}
func testCustomPluralScopeIncludingRequired() throws {
// Make sure explicit plural keys are preserved
let dbQueue = try makeDatabaseQueue()
@@ -61,6 +61,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."rowid" = "children"."parentId") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON "parents"."rowid" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."rowid" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("rowid"))), """
SELECT "children".*, "parents"."rowid" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."rowid" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "rowid" = 1
""")
@@ -108,6 +124,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """
SELECT "children".*, "parents"."id" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
""")
@@ -182,6 +214,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """
SELECT "children".*, "parents"."id" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
""")
@@ -229,6 +277,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """
SELECT "children".*, "parents"."id" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
""")
@@ -301,6 +365,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """
SELECT "children".*, "parents"."id" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
""")
@@ -348,6 +428,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """
SELECT "children".*, "parents"."id" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
""")
@@ -395,6 +491,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """
SELECT "children".*, "parents"."id" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
""")
@@ -472,6 +584,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """
SELECT "children".*, "parents"."id" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
""")
@@ -519,6 +647,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """
SELECT "children".*, "parents"."id" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
""")
@@ -566,6 +710,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """
SELECT "children".*, "parents"."id" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 2
""")
@@ -613,6 +773,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """
SELECT "children".*, "parents"."id" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 2
""")
@@ -691,6 +867,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """
SELECT "children".*, "parents"."a", "parents"."b" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
""")
@@ -784,6 +976,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """
SELECT "children".*, "parents"."a", "parents"."b" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
""")
@@ -845,6 +1053,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """
SELECT "children".*, "parents"."a", "parents"."b" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
""")
@@ -937,6 +1161,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """
SELECT "children".*, "parents"."a", "parents"."b" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
""")
@@ -998,6 +1238,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """
SELECT "children".*, "parents"."a", "parents"."b" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
""")
@@ -1059,6 +1315,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """
SELECT "children".*, "parents"."a", "parents"."b" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
""")
@@ -1160,6 +1432,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """
SELECT "children".*, "parents"."a", "parents"."b" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
""")
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
""")
@@ -1221,6 +1509,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """
SELECT "children".*, "parents"."a", "parents"."b" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
""")
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
""")
@@ -1282,6 +1586,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """
SELECT "children".*, "parents"."a", "parents"."b" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
""")
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 3) AND ("b" = 4)
""")
@@ -1343,6 +1663,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B") AND ("parents"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "children".*, "parents".* \
FROM "children" \
JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """
SELECT "children".*, "parents"."a", "parents"."b" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
""")
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 3) AND ("b" = 4)
""")
@@ -1470,6 +1806,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "PARENTS" ON ("PARENTS"."id" = "CHILDREN"."parentId") AND ("PARENTS"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "CHILDREN".*, "PARENTS".* \
FROM "CHILDREN" \
JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "CHILDREN".*, "PARENTS".* \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """
SELECT "CHILDREN".*, "PARENTS"."id" \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "PARENTS" WHERE "id" = 1
""")
@@ -1517,6 +1869,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "PARENTS" ON ("PARENTS"."id" = "CHILDREN"."parentId") AND ("PARENTS"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "CHILDREN".*, "PARENTS".* \
FROM "CHILDREN" \
JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "CHILDREN".*, "PARENTS".* \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """
SELECT "CHILDREN".*, "PARENTS"."id" \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "PARENTS" WHERE "id" = 1
""")
@@ -1564,6 +1932,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
LEFT JOIN "PARENTS" ON ("PARENTS"."ID" = "CHILDREN"."PARENTID") AND ("PARENTS"."name" = 'foo')
""")
try assertEqualSQL(db, Child.annotated(withRequired: association), """
SELECT "CHILDREN".*, "PARENTS".* \
FROM "CHILDREN" \
JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association), """
SELECT "CHILDREN".*, "PARENTS".* \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """
SELECT "CHILDREN".*, "PARENTS"."id" \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "PARENTS" WHERE "ID" = 1
""")
@@ -53,6 +53,28 @@ private struct AWithRequiredBAndOptionalC: FetchableRecord {
}
}
private struct AWithCName: FetchableRecord {
var a: A
var cName: String?
init(row: Row) {
a = A(row: row)
cName = row["cName"]
}
}
private struct AWithRequiredBNameAndOptionalCName: FetchableRecord {
var a: A
var bName: String
var cName: String?
init(row: Row) {
a = A(row: row)
bName = row["bName"]
cName = row["cName"]
}
}
/// Test support for FetchableRecord records
class AssociationHasOneThroughFetchableRecordTests: GRDBTestCase {
@@ -96,6 +118,19 @@ class AssociationHasOneThroughFetchableRecordTests: GRDBTestCase {
XCTAssertEqual(records[0].c.name, "c1")
}
func testAnnotatedWithRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = A.annotated(withRequired: A.c.select(Column("name").forKey("cName"))).order(sql: "a.id")
let records = try dbQueue.inDatabase { try AWithCName.fetchAll($0, request) }
XCTAssertEqual(records.count, 1)
XCTAssertEqual(records[0].a.id, 1)
XCTAssertEqual(records[0].a.bId, 1)
XCTAssertEqual(records[0].a.name, "a1")
XCTAssertEqual(records[0].cName, "c1")
}
func testIncludingOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = A.including(optional: A.c).order(sql: "a.id")
@@ -120,6 +155,29 @@ class AssociationHasOneThroughFetchableRecordTests: GRDBTestCase {
XCTAssertNil(records[2].c)
}
func testAnnotatedWithOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = A.annotated(withOptional: A.c.select(Column("name").forKey("cName"))).order(sql: "a.id")
let records = try dbQueue.inDatabase { try AWithCName.fetchAll($0, request) }
XCTAssertEqual(records.count, 3)
XCTAssertEqual(records[0].a.id, 1)
XCTAssertEqual(records[0].a.bId, 1)
XCTAssertEqual(records[0].a.name, "a1")
XCTAssertEqual(records[0].cName, "c1")
XCTAssertEqual(records[1].a.id, 2)
XCTAssertEqual(records[1].a.bId, 2)
XCTAssertEqual(records[1].a.name, "a2")
XCTAssertNil(records[1].cName)
XCTAssertEqual(records[2].a.id, 3)
XCTAssertNil(records[2].a.bId)
XCTAssertEqual(records[2].a.name, "a3")
XCTAssertNil(records[2].cName)
}
func testJoiningRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = A.joining(required: A.c).order(sql: "a.id")
@@ -177,4 +235,27 @@ class AssociationHasOneThroughFetchableRecordTests: GRDBTestCase {
XCTAssertEqual(records[1].b.name, "b2")
XCTAssertNil(records[1].c)
}
func testAnnotatedWithOptionalAnnotatedWithRequiredPivot() throws {
let dbQueue = try makeDatabaseQueue()
let request = A
.annotated(withOptional: A.c.select(Column("name").forKey("cName")))
.annotated(withRequired: A.b.select(Column("name").forKey("bName")))
.order(sql: "a.id")
let records = try dbQueue.inDatabase { try AWithRequiredBNameAndOptionalCName.fetchAll($0, request) }
XCTAssertEqual(records.count, 2)
XCTAssertEqual(records[0].a.id, 1)
XCTAssertEqual(records[0].a.bId, 1)
XCTAssertEqual(records[0].a.name, "a1")
XCTAssertEqual(records[0].bName, "b1")
XCTAssertEqual(records[0].cName, "c1")
XCTAssertEqual(records[1].a.id, 2)
XCTAssertEqual(records[1].a.bId, 2)
XCTAssertEqual(records[1].a.name, "a2")
XCTAssertEqual(records[1].bName, "b2")
XCTAssertNil(records[1].cName)
}
}
@@ -74,6 +74,22 @@ class AssociationHasOneThroughRowscopeTests: GRDBTestCase {
XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, ["id":1, "name":"c1"])
}
func testDefaultScopeAnnotatedWithRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = A.annotated(withRequired: A.defaultC).order(sql: "a.id")
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "id":1, "name":"c1"])
}
func testDefaultScopeAnnotatedWithRequiredCustomSelection() throws {
let dbQueue = try makeDatabaseQueue()
let request = A.annotated(withRequired: A.defaultC.select(Column("name").forKey("cName"))).order(sql: "a.id")
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "cName":"c1"])
}
func testDefaultScopeIncludingOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = A.including(optional: A.defaultC).order(sql: "a.id")
@@ -100,6 +116,30 @@ class AssociationHasOneThroughRowscopeTests: GRDBTestCase {
XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!.unscoped, ["id":nil, "name":nil])
}
func testDefaultScopeAnnotatedWithOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = A.annotated(withOptional: A.defaultC).order(sql: "a.id")
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 3)
XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "id":1, "name":"c1"])
XCTAssertEqual(rows[1], ["id":2, "bId":2, "name":"a2", "id":nil, "name":nil])
XCTAssertEqual(rows[2], ["id":3, "bId":nil, "name":"a3", "id":nil, "name":nil])
}
func testDefaultScopeAnnotatedWithOptionalCustomSelection() throws {
let dbQueue = try makeDatabaseQueue()
let request = A.annotated(withOptional: A.defaultC.select(Column("name").forKey("cName"))).order(sql: "a.id")
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 3)
XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "cName":"c1"])
XCTAssertEqual(rows[1], ["id":2, "bId":2, "name":"a2", "cName":nil])
XCTAssertEqual(rows[2], ["id":3, "bId":nil, "name":"a3", "cName":nil])
}
func testDefaultScopeJoiningRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = A.joining(required: A.defaultC).order(sql: "a.id")
@@ -184,4 +224,60 @@ class AssociationHasOneThroughRowscopeTests: GRDBTestCase {
XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"])
XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!.unscoped, ["id":nil, "name":nil])
}
func testDefaultScopeAnnotatedWithOptionalAnnotatedWithRequiredPivot() throws {
let dbQueue = try makeDatabaseQueue()
do {
let request = A
.annotated(withOptional: A.defaultC)
.annotated(withRequired: A.defaultB)
.order(sql: "a.id")
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "id":1, "name":"c1", "id":1, "cId":1, "name":"b1"])
XCTAssertEqual(rows[1], ["id":2, "bId":2, "name":"a2", "id":nil, "name":nil, "id":2, "cId":nil, "name":"b2"])
}
do {
let request = A
.annotated(withRequired: A.defaultB)
.annotated(withOptional: A.defaultC)
.order(sql: "a.id")
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "id":1, "cId":1, "name":"b1", "id":1, "name":"c1"])
XCTAssertEqual(rows[1], ["id":2, "bId":2, "name":"a2", "id":2, "cId":nil, "name":"b2", "id":nil, "name":nil])
}
}
func testDefaultScopeAnnotatedWithOptionalAnnotatedWithRequiredPivotCustomSelection() throws {
let dbQueue = try makeDatabaseQueue()
do {
let request = A
.annotated(withOptional: A.defaultC.select(Column("name").forKey("cName")))
.annotated(withRequired: A.defaultB.select(Column("name").forKey("bName")))
.order(sql: "a.id")
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "cName":"c1", "bName":"b1"])
XCTAssertEqual(rows[1], ["id":2, "bId":2, "name":"a2", "cName":nil, "bName":"b2"])
}
do {
let request = A
.annotated(withRequired: A.defaultB.select(Column("name").forKey("bName")))
.annotated(withOptional: A.defaultC.select(Column("name").forKey("cName")))
.order(sql: "a.id")
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "bName":"b1", "cName":"c1"])
XCTAssertEqual(rows[1], ["id":2, "bId":2, "name":"a2", "bName":"b2", "cName":nil])
}
}
}
@@ -206,6 +206,25 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.annotated(withOptional: ac), """
SELECT "a".*, "c".* \
FROM "a" \
LEFT JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.annotated(withRequired: ac), """
SELECT "a".*, "c".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.annotated(withRequired: ac.select(Column.rowID)), """
SELECT "a".*, "c"."rowid" \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition)
""")
}
do {
try assertEqualSQL(db, A.including(optional: ac).including(optional: ab), """
@@ -232,6 +251,25 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.annotated(withOptional: ab).including(optional: ac), """
SELECT "a".*, "b".*, "c".* \
FROM "a" \
LEFT JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.including(optional: ac).annotated(withRequired: ab), """
SELECT "a".*, "b".*, "c".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.including(optional: ac).annotated(withRequired: ab.select(Column.rowID)), """
SELECT "a".*, "b"."rowid", "c".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition)
""")
}
do {
try assertEqualSQL(db, A.including(required: ac).including(optional: ab), """
@@ -258,6 +296,25 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.annotated(withOptional: ab).including(required: ac), """
SELECT "a".*, "b".*, "c".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.including(required: ac).annotated(withRequired: ab), """
SELECT "a".*, "b".*, "c".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.including(required: ac).annotated(withRequired: ab.select(Column.rowID)), """
SELECT "a".*, "b"."rowid", "c".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition)
""")
}
do {
try assertEqualSQL(db, A.joining(optional: ac).including(optional: ab), """
@@ -284,6 +341,25 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.annotated(withOptional: ab).joining(optional: ac), """
SELECT "a".*, "b".* \
FROM "a" \
LEFT JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.joining(optional: ac).annotated(withRequired: ab), """
SELECT "a".*, "b".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.joining(optional: ac).annotated(withRequired: ab.select(Column.rowID)), """
SELECT "a".*, "b"."rowid" \
FROM "a" \
JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition)
""")
}
do {
try assertEqualSQL(db, A.joining(required: ac).including(optional: ab), """
@@ -310,6 +386,25 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.annotated(withOptional: ab).joining(required: ac), """
SELECT "a".*, "b".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.joining(required: ac).annotated(withRequired: ab), """
SELECT "a".*, "b".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition)
""")
try assertEqualSQL(db, A.joining(required: ac).annotated(withRequired: ab.select(Column.rowID)), """
SELECT "a".*, "b"."rowid" \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition)
""")
}
}
@@ -841,6 +936,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.annotated(withOptional: dThroughC),
A.annotated(withOptional: dThroughB)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".* \
FROM "a" \
LEFT JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition) \
LEFT JOIN "d" ON \(dCondition)
""")
}
for request in [
A.annotated(withRequired: dThroughC),
A.annotated(withRequired: dThroughB)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.annotated(withRequired: dThroughC.select(Column.rowID)),
A.annotated(withRequired: dThroughB.select(Column.rowID))]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d"."rowid" \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
}
do {
@@ -893,6 +1025,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.including(optional: b).annotated(withOptional: dThroughC),
A.annotated(withOptional: dThroughB).including(optional: b)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".*, "b".* \
FROM "a" \
LEFT JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition) \
LEFT JOIN "d" ON \(dCondition)
""")
}
for request in [
A.including(optional: b).annotated(withRequired: dThroughC),
A.annotated(withRequired: dThroughB).including(optional: b)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".*, "b".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.including(optional: b).annotated(withRequired: dThroughC.select(Column.rowID)),
A.annotated(withRequired: dThroughB.select(Column.rowID)).including(optional: b)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d"."rowid", "b".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
}
do {
@@ -944,6 +1113,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.including(required: b).annotated(withOptional: dThroughC),
A.annotated(withOptional: dThroughB).including(required: b)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".*, "b".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition) \
LEFT JOIN "d" ON \(dCondition)
""")
}
for request in [
A.including(required: b).annotated(withRequired: dThroughC),
A.annotated(withRequired: dThroughB).including(required: b)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".*, "b".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.including(required: b).annotated(withRequired: dThroughC.select(Column.rowID)),
A.annotated(withRequired: dThroughB.select(Column.rowID)).including(required: b)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d"."rowid", "b".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
}
do {
@@ -995,6 +1201,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.joining(optional: b).annotated(withOptional: dThroughC),
A.annotated(withOptional: dThroughB).joining(optional: b)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".* \
FROM "a" \
LEFT JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition) \
LEFT JOIN "d" ON \(dCondition)
""")
}
for request in [
A.joining(optional: b).annotated(withRequired: dThroughC),
A.annotated(withRequired: dThroughB).joining(optional: b)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.joining(optional: b).annotated(withRequired: dThroughC.select(Column.rowID)),
A.annotated(withRequired: dThroughB.select(Column.rowID)).joining(optional: b)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d"."rowid" \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
}
do {
@@ -1046,6 +1289,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.joining(required: b).annotated(withOptional: dThroughC),
A.annotated(withOptional: dThroughB).joining(required: b)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition) \
LEFT JOIN "d" ON \(dCondition)
""")
}
for request in [
A.joining(required: b).annotated(withRequired: dThroughC),
A.annotated(withRequired: dThroughB).joining(required: b)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.joining(required: b).annotated(withRequired: dThroughC.select(Column.rowID)),
A.annotated(withRequired: dThroughB.select(Column.rowID)).joining(required: b)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d"."rowid" \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
}
}
@@ -1099,6 +1379,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.including(optional: c).annotated(withOptional: dThroughC),
A.annotated(withOptional: dThroughB).including(optional: c)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".*, "c".* \
FROM "a" \
LEFT JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition) \
LEFT JOIN "d" ON \(dCondition)
""")
}
for request in [
A.including(optional: c).annotated(withRequired: dThroughC),
A.annotated(withRequired: dThroughB).including(optional: c)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".*, "c".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.including(optional: c).annotated(withRequired: dThroughC.select(Column.rowID)),
A.annotated(withRequired: dThroughB.select(Column.rowID)).including(optional: c)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d"."rowid", "c".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
}
do {
@@ -1150,6 +1467,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.including(required: c).annotated(withOptional: dThroughC),
A.annotated(withOptional: dThroughB).including(required: c)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".*, "c".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
LEFT JOIN "d" ON \(dCondition)
""")
}
for request in [
A.including(required: c).annotated(withRequired: dThroughC),
A.annotated(withRequired: dThroughB).including(required: c)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".*, "c".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.including(required: c).annotated(withRequired: dThroughC.select(Column.rowID)),
A.annotated(withRequired: dThroughB.select(Column.rowID)).including(required: c)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d"."rowid", "c".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
}
do {
@@ -1201,6 +1555,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.joining(optional: c).annotated(withOptional: dThroughC),
A.annotated(withOptional: dThroughB).joining(optional: c)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".* \
FROM "a" \
LEFT JOIN "b" ON \(bCondition) \
LEFT JOIN "c" ON \(cCondition) \
LEFT JOIN "d" ON \(dCondition)
""")
}
for request in [
A.joining(optional: c).annotated(withRequired: dThroughC),
A.annotated(withRequired: dThroughB).joining(optional: c)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.joining(optional: c).annotated(withRequired: dThroughC.select(Column.rowID)),
A.annotated(withRequired: dThroughB.select(Column.rowID)).joining(optional: c)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d"."rowid" \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
}
do {
@@ -1252,6 +1643,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.joining(required: c).annotated(withOptional: dThroughC),
A.annotated(withOptional: dThroughB).joining(required: c)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
LEFT JOIN "d" ON \(dCondition)
""")
}
for request in [
A.joining(required: c).annotated(withRequired: dThroughC),
A.annotated(withRequired: dThroughB).joining(required: c)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d".* \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
for request in [
A.joining(required: c).annotated(withRequired: dThroughC.select(Column.rowID)),
A.annotated(withRequired: dThroughB.select(Column.rowID)).joining(required: c)]
{
try assertEqualSQL(db, request, """
SELECT "a".*, "d"."rowid" \
FROM "a" \
JOIN "b" ON \(bCondition) \
JOIN "c" ON \(cCondition) \
JOIN "d" ON \(dCondition)
""")
}
}
}
}
@@ -130,6 +130,46 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
}
}
// ContiguousArray
do {
struct Record: FetchableRecord, Decodable, Equatable {
var a: A
var bs: ContiguousArray<B>
}
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [
B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]),
]),
Record(
a: A(row: ["cola1": 2, "cola2": "a2"]),
bs: [
B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]),
]),
Record(
a: A(row: ["cola1": 3, "cola2": "a3"]),
bs: []),
])
}
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [
B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]),
]))
}
}
// Set
do {
struct Record: FetchableRecord, Decodable, Equatable {