diff --git a/.swift-version b/.swift-version index 389f7740e..7d5c902e7 100644 --- a/.swift-version +++ b/.swift-version @@ -1 +1 @@ -4.0 \ No newline at end of file +4.1 diff --git a/.travis.yml b/.travis.yml index 416b9532c..164f49bb5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,198 +15,140 @@ jobs: ########################################### ## Test GRDB - # Test GRDBOSX (Xcode 9.2) + # Test GRDBOSX (Xcode 9.3) - stage: Test GRDB gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBOSX (Xcode 9.2, macOS) + - TID=GRDBOSX (Xcode 9.3, macOS) script: make test_framework_GRDBOSX - # Test GRDBWatchOS (Xcode 9.2) + # Test GRDBWatchOS (Xcode 9.3) - stage: Test GRDB gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBWatchOS (Xcode 9.2, watchOS) + - TID=GRDBWatchOS (Xcode 9.3, watchOS) script: make test_framework_GRDBWatchOS - # Test GRDBiOS (Xcode 9.2, iOS ) + # Test GRDBiOS (Xcode 9.3, iOS ) - stage: Test GRDB gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBiOS (Xcode 9.2, iOS ) + - TID=GRDBiOS (Xcode 9.3, iOS ) script: make test_framework_GRDBiOS_maxTarget - # Test GRDBiOS (Xcode 9.2, iOS )) + # Test GRDBiOS (Xcode 9.3, iOS )) - stage: Test GRDB gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBiOS (Xcode 9.2, iOS ) + - TID=GRDBiOS (Xcode 9.3, iOS ) script: make test_framework_GRDBiOS_minTarget - # Test GRDB [SPM] (Xcode 9.2, macOS) + # Test GRDB [SPM] (Xcode 9.3, macOS) - stage: Test GRDB gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDB [SPM] (Xcode 9.2, macOS) + - TID=GRDB [SPM] (Xcode 9.3, macOS) script: make test_SPM - # Test GRDBOSX (Xcode 9.0) - - stage: Test GRDB - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9 - env: - - TID=GRDBOSX (Xcode 9.0, macOS) - script: make test_framework_GRDBOSX - - # Test GRDBiOS (Xcode 9.0, iOS ) - - stage: Test GRDB - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9 - env: - - TID=GRDBiOS (Xcode 9.0, iOS ) - script: make test_framework_GRDBiOS_maxTarget - ########################################### ## Test GRDB (Custom SQLite) - # Test GRDBCustomSQLiteOSX (Xcode 9.2) + # Test GRDBCustomSQLiteOSX (Xcode 9.3) - stage: Test GRDB + Custom SQLite gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBCustomSQLiteOSX (Xcode 9.2, macOS) + - TID=GRDBCustomSQLiteOSX (Xcode 9.3, macOS) script: make test_framework_GRDBCustomSQLiteOSX - # Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS ) + # Test GRDBCustomSQLiteiOS (Xcode 9.3, iOS ) - stage: Test GRDB + Custom SQLite gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS ) + - TID=GRDBCustomSQLiteiOS (Xcode 9.3, iOS ) script: make test_framework_GRDBCustomSQLiteiOS_maxTarget - # Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS )) + # Test GRDBCustomSQLiteiOS (Xcode 9.3, iOS )) - stage: Test GRDB + Custom SQLite gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS ) + - TID=GRDBCustomSQLiteiOS (Xcode 9.3, iOS ) script: make test_framework_GRDBCustomSQLiteiOS_minTarget - # Test GRDBCustomSQLiteOSX (Xcode 9.0) - - stage: Test GRDB + Custom SQLite - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9 - env: - - TID=GRDBCustomSQLiteOSX (Xcode 9.0, macOS) - script: make test_framework_GRDBCustomSQLiteOSX - - # Test GRDBCustomSQLiteiOS (Xcode 9.0, iOS ) - - stage: Test GRDB + Custom SQLite - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9 - env: - - TID=GRDBCustomSQLiteiOS (Xcode 9.0, iOS ) - script: make test_framework_GRDBCustomSQLiteiOS_maxTarget - ########################################### ## Test GRDB (SQLCipher) - # Test GRDBCipherOSX (Xcode 9.2) + # Test GRDBCipherOSX (Xcode 9.3) - stage: Test GRDB + SQLCipher gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBCipherOSX (Xcode 9.2, macOS) + - TID=GRDBCipherOSX (Xcode 9.3, macOS) script: make test_framework_GRDBCipherOSX - # Test GRDBCipheriOS (Xcode 9.2, iOS ) + # Test GRDBCipheriOS (Xcode 9.3, iOS ) - stage: Test GRDB + SQLCipher gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBCipheriOS (Xcode 9.2, iOS ) + - TID=GRDBCipheriOS (Xcode 9.3, iOS ) script: make test_framework_GRDBCipheriOS_maxTarget - # Test GRDBCipheriOS (Xcode 9.2, iOS )) + # Test GRDBCipheriOS (Xcode 9.3, iOS )) - stage: Test GRDB + SQLCipher gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBCipheriOS (Xcode 9.2, iOS ) + - TID=GRDBCipheriOS (Xcode 9.3, iOS ) script: make test_framework_GRDBCipheriOS_minTarget - # Test GRDBCipherOSX (Xcode 9.0) - - stage: Test GRDB + SQLCipher - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9 - env: - - TID=GRDBCipherOSX (Xcode 9.0, macOS) - script: make test_framework_GRDBCipherOSX - - # Test GRDBCipheriOS (Xcode 9.0, iOS ) - - stage: Test GRDB + SQLCipher - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9 - env: - - TID=GRDBCipheriOS (Xcode 9.0, iOS ) - script: make test_framework_GRDBCipheriOS_maxTarget - - ########################################### ## Test Installation Methods - # Manual Install (Xcode 9.2) + # Manual Install (Xcode 9.3) - stage: Test Installation gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=Manual Install (Xcode 9.2) + - TID=Manual Install (Xcode 9.3) script: make test_install_manual - # Manual Install (GRDBCipher, Xcode 9.2) + # Manual Install (GRDBCipher, Xcode 9.3) - stage: Test Installation gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=Manual Install (GRDBCipher, Xcode 9.2) + - TID=Manual Install (GRDBCipher, Xcode 9.3) script: make test_install_GRDBCipher - # Cocoapods Lint (Xcode 9.2) + # Cocoapods Lint (Xcode 9.3) - stage: Test Installation - osx_image: xcode9.2 + osx_image: xcode9.3 install: - gem install cocoapods # Since Travis is not always on latest version env: - - TID=Cocoapods (Xcode 9.2) + - TID=Cocoapods (Xcode 9.3) script: make test_CocoaPodsLint - # Cocoapods Lint (Xcode 9.0) + # SPM Install (Xcode 9.3) - stage: Test Installation - osx_image: xcode9 - install: - - gem install cocoapods # Since Travis is not always on latest version + osx_image: xcode9.3 env: - - TID=Cocoapods (Xcode 9.0) - script: make test_CocoaPodsLint - - # SPM Install (Xcode 9.2) - - stage: Test Installation - osx_image: xcode9.2 - env: - - TID=SPM (Xcode 9.2) + - TID=SPM (Xcode 9.3) script: make test_install_SPM ## Carthage Build ## Commented out until `make test_CarthageBuild` performs *reliably*. ## See https://github.com/groue/GRDB.swift/pull/262 # - stage: Test Installation - # osx_image: xcode9.2 + # osx_image: xcode9.3 # before_install: # - brew update # - brew outdated carthage || brew upgrade carthage diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md new file mode 100644 index 000000000..a8440f888 --- /dev/null +++ b/Documentation/AssociationsBasics.md @@ -0,0 +1,1375 @@ +GRDB Associations +================= + +- [Associations Benefits] +- [The Types of Associations] + - [BelongsTo] + - [HasOne] + - [HasMany] + - [Choosing Between BelongsTo and HasOne] + - [Self Joins] +- [Associations and the Database Schema] + - [Convention for Database Table Names] + - [Convention for the BelongsTo Association] + - [Convention for the HasOne Association] + - [Convention for the HasMany Association] + - [Foreign Keys] +- [Building Requests from Associations] + - [Requesting Associated Records] + - [Joining Methods] + - [Combining Associations] + - [Filtering Associations] + - [Sorting Associations] + - [Columns Selected by an Association] + - [Table Aliases] +- [Fetching Values from Associations] + - [The Structure of a Joined Request] + - [Decoding a Joined Request with a Decodable Record] + - [Decoding a Joined Request with FetchableRecord] +- [Known Issues] +- [Future Directions] + + +## Associations Benefits + +**An association is a connection between two [Record] types.** + +Associations streamline common operations in your code, make them safer, and more efficient. For example, consider a library application that has two record types, author and book: + +```swift +struct Author: TableRecord, FetchableRecord { + var id: Int64 + var name: String +} + +struct Book: TableRecord, FetchableRecord { + var id: Int64 + var authorId: Int64? + var title: String +} +``` + +Now, suppose we wanted to load all books from an existing author. We'd need to do something like this: + +```swift +let author: Author = ... +let books = try Book + .filter(Column("authorId") == author.id) + .fetchAll(db) +``` + +Or, loading all pairs of books along with their authors: + +```swift +struct BookInfo { + var book: Book + var author: Author? +} + +let books = try Book.fetchAll(db) +let bookInfos = books.map { book -> BookInfo in + let author = try Author.fetchOne(key: book.authorId) + return BookInfo(book: book, author: author) +} +``` + +With GRDB associations, we can streamline these operations (and others), by declaring the connections between books and authors. Here is how we define associations, and properties that access them: + +```swift +extension Author { + static let books = hasMany(Book.self) + var books: QueryInterfaceRequest { + return request(for: Author.books) + } +} + +extension Book { + static let author = belongsTo(Author.self) + var author: QueryInterfaceRequest { + return request(for: Book.author) + } +} +``` + +Loading all books from an existing author is now easier: + +```swift +let books = try author.books.fetchAll(db) +``` + +As for loading all pairs of books and authors, it is not only easier, but also *far much efficient*: + +```swift +struct BookInfo: FetchableRecord, Codable { + let book: Book + let author: Author? +} + +let request = Book.including(optional: Book.author) +let bookInfos = BookInfo.fetchAll(db, request) +``` + +Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because Your SQL skills are welcome: see the [Joined Queries Support](../README.md#joined-queries-support) chapter. + + +The Types of Associations +========================= + +GRDB handles three types of associations: + +- **BelongsTo** +- **HasOne** +- **HasMany** + +An association declares a link from a record type to another, as in "one book **belongs to** its author". It instructs GRDB to use the foreign keys declared in the database as support for Swift methods. + +Each one of the three types of associations is appropriate for a particular database situation. + +- [BelongsTo] +- [HasOne] +- [HasMany] +- [Choosing Between BelongsTo and HasOne] +- [Self Joins] + + +## BelongsTo + +The **BelongsTo** association sets up a one-to-one connection from a record type to another record type, such as each instance of the declaring record "belongs to" an instance of the other record. + +For example, if your application includes authors and books, and each book is assigned its author, you'd declare the association this way: + +```swift +struct Book: TableRecord { + static let author = belongsTo(Author.self) + ... +} + +struct Author: TableRecord { + ... +} +``` + +The **BelongsTo** association between a book and its author needs that the database table for books has a column that points to the table for authors: + +![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/BelongsToSchema.svg) + +See [Convention for the BelongsTo Association] for some sample code that defines the database schema for such an association. + + +## HasOne + +The **HasOne** association also sets up a one-to-one connection from a record type to another record type, but with different semantics, and underlying database schema. It is usually used when an entity has been denormalized into two database tables. + +For example, if your application has one database table for countries, and another for their demographic profiles, you'd declare the association this way: + +```swift +struct Country: TableRecord { + static let demographics = hasOne(Demographics.self) + ... +} + +struct Demographics: TableRecord { + ... +} +``` + +The **HasOne** association between a country and its demographics needs that the database table for demographics has a column that points to the table for countries: + +![HasOneSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasOneSchema.svg) + +See [Convention for the HasOne Association] for some sample code that defines the database schema for such an association. + + +## HasMany + +The **HasMany** association indicates a one-to-many connection between two record types, such as each instance of the declaring record "has many" instances of the other record. You'll often find this association on the other side of a **BelongsTo** association. + +For example, if your application includes authors and books, and each author is assigned zero or more books, you'd declare the association this way: + +```swift +struct Author: TableRecord { + static let books = hasMany(Book.self) +} + +struct Book: TableRecord { + ... +} +``` + +The **HasMany** association between an author and its books needs that the database table for books has a column that points to the table for authors: + +![HasManySchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasManySchema.svg) + +See [Convention for the HasMany Association] for some sample code that defines the database schema for such an association. + + +## Choosing Between BelongsTo and HasOne + +When you want to set up a one-to-one relationship between two record types, you'll need to add a **BelongsTo** association to one, and a **HasOne** association to the other. How do you know which is which? + +The distinction is in where you place the database foreign key. The record that points to the other one has the **BelongsTo** association. The other record has the **HasOne** association: + +A country **has one** demographic profile, a demographic profile **belongs to** a country: + +![HasOneSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasOneSchema.svg) + +```swift +struct Country: TableRecord, FetchableRecord { + static let demographics = hasOne(Demographics.self) + ... +} + +struct Demographics: TableRecord, FetchableRecord { + static let country = belongsTo(Demographics.self) + ... +} +``` + +## Self Joins + +When designing your data model, you will sometimes find a record that should have a relation to itself. For example, you may want to store all employees in a single database table, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations: + +```swift +struct Employee { + static let subordinates = hasMany(Employee.self) + static let manager = belongsTo(Employee.self) +} +``` + +![RecursiveSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/RecursiveSchema.svg) + +The matching [migration] would look like: + +```swift +migrator.registerMigration("Employees") { db in + try db.create(table: "employee") { t in + t.autoIncrementedPrimaryKey("id") + t.column("managerId", .integer) + .indexed() + .references("employee", onDelete: .restrict) + t.column("name", .text) + } +} +``` + + +Associations and the Database Schema +==================================== + +**Associations are grounded in the database schema, the way database tables are defined.** + +For example, a **[BelongsTo]** association between a book and its author needs that the database table for books has a column that points to the table for authors. + +GRDB also comes with several *conventions* for defining your database schema. + +Those conventions help associations be convenient and, generally, "just work". When you can't, or don't want to follow conventions, you will have to override the expected defaults in your Swift code. + +- [Convention for Database Table Names] +- [Convention for the BelongsTo Association] +- [Convention for the HasOne Association] +- [Convention for the HasMany Association] +- [Foreign Keys] + + +## Convention for Database Table Names + +**Database table names should be singular and camel-cased.** + +This is the same convention as Swift identifiers for variables and properties. For example: `book`, `author`, `postalAddress`. + +This convention helps fetching values from associations. It is used, for example, in the sample code below, where we load all pairs of books along with their authors: + +```swift +// The Book record +struct Book: FetchableRecord, TableRecord { + static let databaseTableName = "book" + static let author = belongsTo(Author.self) + ... +} + +// The Author record +struct Author: FetchableRecord, TableRecord { + static let databaseTableName = "author" + ... +} + +// A pair made of a book and its author +struct BookInfo: FetchableRecord, Codable { + let book: Book + let author: Author? +} + +let request = Book.including(optional: Book.author) +let bookInfos = BookInfo.fetchAll(db, request) +``` + +This sample code only works if the database table for authors is called "author". This name "author" is the key that helps BookInfo initialize its `author` property. + +If the database schema does not follow this convention, and has, for example, database tables named with plural names (`authors` and `books`), you can still use associations. But you need to help row consumption by providing the required key: + +```swift +struct Book: FetchableRecord, TableRecord { + static let author = belongsTo(Author.self).forKey("author") // <- +} +``` + +See [The Structure of a Joined Request] for more information. + + +## Convention for the BelongsTo Association + +**[BelongsTo] associations should be supported by an SQLite foreign key.** + +Foreign keys are the recommended way to declare relationships between database tables. Not only will SQLite guarantee the integrity of your data, but GRDB will be able to use those foreign keys to automatically configure your associations. + +![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/BelongsToSchema.svg) + +The matching [migration] could look like: + +```swift +migrator.registerMigration("Books and Authors") { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") // (1) + t.column("name", .text) + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorId", .integer) // (2) + .notNull() // (3) + .indexed() // (4) + .references("author", onDelete: .cascade) // (5) + t.column("title", .text) + } +} +``` + +1. The `author` table has a primary key. +2. The `book.authorId` column is used to link a book to the author it belongs to. +3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author. +4. Create an index on the `book.authorId` column in order to ease the selection of an author's books. +5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information. + +The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported. + +Following this convention lets you write, for example: + +```swift +struct Book: FetchableRecord, TableRecord { + static let databaseTableName = "book" + static let author = belongsTo(Author.self) +} + +struct Author: FetchableRecord, TableRecord { + static let databaseTableName = "author" +} +``` + +If the database schema does not follow this convention, and does not define foreign keys between tables, you can still use **BelongsTo** associations. But your help is needed to define the missing foreign key: + +```swift +struct Book: FetchableRecord, TableRecord { + static let author = belongsTo(Author.self, using: ForeignKey(...)) +} +``` + +See [Foreign Keys] for more information. + + +## Convention for the HasOne Association + +**[HasOne] associations should be supported by an SQLite foreign key.** + +Foreign keys are the recommended way to declare relationships between database tables. Not only will SQLite guarantee the integrity of your data, but GRDB will be able to use those foreign keys to automatically configure your associations. + +![HasOneSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasOneSchema.svg) + +The matching [migration] could look like: + +```swift +migrator.registerMigration("Countries") { db in + try db.create(table: "country") { t in + t.column("code", .text).primaryKey() // (1) + t.column("name", .text) + } + try db.create(table: "demographics") { t in + t.autoIncrementedPrimaryKey("id") + t.column("countryCode", .text) // (2) + .notNull() // (3) + .unique() // (4) + .references("country", onDelete: .cascade) // (5) + t.column("population", .integer) + t.column("density", .double) + } +} +``` + +1. The `country` table has a primary key. +2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to. +3. Make the `demographics.countryCode` column not null if you want SQLite to guarantee that all profiles are linked to a country. +4. Create a unique index on the `demographics.countryCode` column in order to guarantee the unicity of any country's profile. +5. Create a foreign key from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information. + +The example above uses a string primary key for the "country" table. But generally speaking, all primary keys are supported. + +Following this convention lets you write, for example: + +```swift +struct Country: FetchableRecord, TableRecord { + static let databaseTableName = "country" + static let demographics = hasOne(Demographics.self) +} + +struct Demographics: FetchableRecord, TableRecord { + static let databaseTableName = "demographics" +} +``` + +If the database schema does not follow this convention, and does not define foreign keys between tables, you can still use HasOne associations. But your help is needed to define the missing foreign key: + +```swift +struct Book: FetchableRecord, TableRecord { + static let demographics = hasOne(Demographics.self, using: ForeignKey(...)) +} +``` + +See [Foreign Keys] for more information. + + +## Convention for the HasMany Association + +**[HasMany] associations should be supported by an SQLite foreign key.** + +Foreign keys are the recommended way to declare relationships between database tables. Not only will SQLite guarantee the integrity of your data, but GRDB will be able to use those foreign keys to automatically configure your associations. + +![HasManySchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasManySchema.svg) + +The matching [migration] could look like: + +```swift +migrator.registerMigration("Books and Authors") { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") // (1) + t.column("name", .text) + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorId", .integer) // (2) + .notNull() // (3) + .indexed() // (4) + .references("author", onDelete: .cascade) // (5) + t.column("title", .text) + } +} +``` + +1. The `author` table has a primary key. +2. The `book.authorId` column is used to link a book to the author it belongs to. +3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author. +4. Create an index on the `book.authorId` column in order to ease the selection of an author's books. +5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information. + +The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported. + +Following this convention lets you write, for example: + +```swift +struct Book: FetchableRecord, TableRecord { + static let databaseTableName = "book" +} + +struct Author: FetchableRecord, TableRecord { + static let databaseTableName = "author" + static let books = hasMany(Book.self) +} +``` + +If the database schema does not follow this convention, and does not define foreign keys between tables, you can still use **HasMany** associations. But your help is needed to define the missing foreign key: + +```swift +struct Author: FetchableRecord, TableRecord { + static let books = hasMany(Book.self, using: ForeignKey(...)) +} +``` + +See [Foreign Keys] for more information. + + +## Foreign Keys + +**Associations can automatically infer the foreign keys that define how two database tables are linked together.** + +In the example below, the `book.authorId` column is automatically used to link a book to its author: + +![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/BelongsToSchema.svg) + +```swift +struct Book: TableRecord { + static let author = belongsTo(Author.self) +} + +struct Author: TableRecord { + static let books = hasMany(Book.self) +} +``` + +But this requires the database schema to define a foreign key between the book and author database tables (see [Convention for the BelongsTo Association]). + +Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another. + +![AmbiguousForeignKeys](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/AmbiguousForeignKeys.svg) + +When this happens, associations can't be automatically inferred from the database schema. GRDB will complain with a fatal error such as "Ambiguous foreign key from book to author", or "Could not infer foreign key from book to author". + +Your help is needed. You have to instruct GRDB which foreign key to use: + +```swift +struct Book: TableRecord { + // Define foreign keys + static let authorForeignKey = ForeignKey(["authorId"])) + static let translatorForeignKey = ForeignKey(["translatorId"])) + + // Use foreign keys to define associations: + static let author = belongsTo(Person.self, using: authorForeignKey) + static let translator = belongsTo(Person.self, using: translatorForeignKey) +} +``` + +Foreign keys are always defined from the table that contains the columns at the origin of the foreign key. Person's symmetric **HasMany** associations reuse Book's foreign keys: + +```swift +struct Person: TableRecord { + static let writtenBooks = hasMany(Book.self, using: Book.authorForeignKey) + static let translatedBooks = hasMany(Book.self, using: Book.translatorForeignKey) +} +``` + +Foreign keys can also be defined from `Column`: + +```swift +struct Book: TableRecord { + static let authorId = Column("authorId") + static let translatorId = Column("translatorId") + + static let authorForeignKey = ForeignKey([authorId])) + static let translatorForeignKey = ForeignKey([translatorId])) +} +``` + +When the destination table of a foreign key does not define any primary key, you need to provide the full definition of a foreign key: + +```swift +struct Book: TableRecord { + static let authorForeignKey = ForeignKey(["authorId"], to: ["id"])) + static let author = belongsTo(Person.self, using: authorForeignKey) +} +``` + + +Building Requests from Associations +=================================== + +**Once you have defined associations, you can define fetch request that involve several record types.** + +> :point_up: **Note**: Those requests are executed by SQLite as *SQL joined queries*. In all examples below, we'll show the SQL queries executed by our association-based requests. You can ignore them if you are not familiar with SQL. + +Fetch requests do not visit the database until you fetch values from them. This will be covered in [Fetching Values from Associations]. But before you can fetch anything, you have to describe what you want to fetch. This is the topic of this chapter. + +- [Requesting Associated Records] +- [Joining Methods] +- [Combining Associations] +- [Filtering Associations] +- [Sorting Associations] +- [Columns Selected by an Association] +- [Table Aliases] + + +## Requesting Associated Records + +**You can use associations to build requests for associated records.** + +For example, given a `Book.author` **[BelongsTo]** association, you can build a request for the author of a book. In the example below, we return this request from the `Book.author` property: + +```swift +struct Book: PersistableRecord { + static let author = belongsTo(Author.self) + + /// The request for a book's author + var author: QueryInterfaceRequest { + return request(for: Book.author) + } +} +``` + +This request can fetch a book's author: + +```swift +let book: Book = ... +let author = try book.author.fetchOne(db) // Author? +``` + +**[HasOne]** and **[HasMany]** associations can also build requests for associated records. For example: + +```swift +struct Author: PersistableRecord { + static let books = hasMany(Book.self) + + /// The request for an author's books + var books: QueryInterfaceRequest { + return request(for: Author.books) + } +} + +let author: Author = ... +let books = try author.books.fetchAll(db) // [Book] +``` + +Those requests can also turn out useful when you want to track their changes with database observation tools like [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): + +```swift +// Track changes in the author's books: +let author: Author = ... +author.books.rx + .fetchAll(in: dbQueue) + .subscribe(onNext: { (books: [Book]) in + print("Author's book have changed") + }) +``` + + +## Joining Methods + +**You build requests that involve several records with the four "joining methods":** + +- `including(optional: association)` +- `including(required: association)` +- `joining(optional: association)` +- `joining(required: association)` + +Before we describe them in detail, let's see a few requests they can build: + +```swift +/// All books with their respective authors +let request = Book + .including(required: Book.author) + +/// All books with their respective authors, sorted by title +let request = Book + .order(Column("title")) + .including(required: Book.author) + +/// All books written by a French author +let request = Book + .joining(required: Book.author.filter(Column("countryCode") == "FR")) +``` + +The pattern is always the same: you start from a base request, that you extend with one of the joining methods. + +**To choose the joining method you need, you ask yourself two questions:** + +1. Should the associated records be fetched along with the base records? + + If yes, use `including(...)`. Otherwise, use `joining(...)`. + + For example, to load all books with their respective authors, you want authors to be fetched, and you use `including`: + + ```swift + /// All books with their respective authors + let request = Book + .including(required: Book.author) + ``` + + 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")) + ``` + +2. 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:)`: + + ```swift + /// All books with their respective (eventual) authors + /// (One Thousand and One Nights should be there) + let request = Book + .including(optional: Book.author) + ``` + + 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`. + + 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. + + For example, consider this request: + + ```swift + let request = Book + .joining(optional: Book.author.filter(Column("countryCode") == "FR")) + ``` + + It fetches books that have a French author, but also those who don't :sweat_smile:. It's just another way to tell `Book.all()`. But we'll see below that such join can turn out useful. + + Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins. + + +## Combining Associations + +**Associations can be combined in order to build more complex requests.** + +You can join several associations in parallel: + +```swift +// SELECT book.*, person1.*, person2.* +// FROM book +// JOIN person person1 ON person1.id = book.authorId +// LEFT JOIN person person2 ON person2.id = book.translatorId +let request = Book + .including(required: Book.author) + .including(optional: Book.translator) +``` + +The request above fetches all books, along with their author and eventual translator. + +You can chain associations in order to jump from a record to another: + +```swift +// SELECT book.*, person.*, country.* +// FROM book +// JOIN person ON person.id = book.authorId +// LEFT JOIN country ON country.code = person.countryCode +let request = Book + .including(required: Book.author + .including(optional: Person.country)) +``` + +The request above fetches all books, along with their author, and their author's country. + +When you chain associations, you can avoid fetching intermediate values by replacing the `including` method with `joining`: + +```swift +// SELECT book.*, country.* +// FROM book +// LEFT JOIN person ON person.id = book.authorId +// LEFT JOIN country ON country.code = person.countryCode +let request = Book + .joining(optional: Book.author + .including(optional: Person.country)) +``` + +The request above fetches all books, along with their author's country. + +> :warning: **Warning**: you can not currently chain a required association behind an optional association: +> +> ```swift +> // Not implemented +> let request = Book +> .joining(optional: Book.author +> .including(required: Person.country)) +> ``` +> +> This code compiles, but you'll get a runtime fatal error "Not implemented: chaining a required association behind an optional association". Future versions of GRDB may allow such requests. + + +## Filtering Associations + +**You can filter associated records.** + +The `filter(_:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#requests), can filter associated records as well: + +```swift +// SELECT book.* +// FROM book +// JOIN person ON person.id = book.authorId +// AND person.countryCode = 'FR' +let frenchAuthor = Book.author.filter(Column("countryCode") == "FR") +let request = Book.joining(required: frenchAuthor) +``` + +The request above fetches all books written by a French author. + +**There are more filtering options:** + +- Filtering on conditions that involve several tables. +- Filtering in the WHERE clause instead of the ON clause (can be useful when you are skilled enough in SQL to make the difference). + +Those extra filtering options require **[Table Aliases]**, introduced below. + + +## Sorting Associations + +**You can sort fetched results according to associated records.** + +The `order()` method, that you already know for [sorting simple requests](https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#requests), can sort associated records as well: + +```swift +// SELECT book.*, person.* +// FROM book +// JOIN person ON person.id = book.authorId +// ORDER BY person.name +let sortedAuthor = Book.author.order(Column("name")) +let request = Book.including(required: sortedAuthor) +``` + +When you sort both the base record on the associated record, the request is sorted on the base record first, and on the associated record next: + +```swift +// SELECT book.*, person.* +// FROM book +// JOIN person ON person.id = book.authorId +// ORDER BY book.publishDate DESC, person.name +let sortedAuthor = Book.author.order(Column("name")) +let request = Book + .including(required: sortedAuthor) + .order(Column("publishDate").desc) +``` + +**There are more sorting options:** + +- Sorting on expressions that involve several tables. +- Changing the order of the sorting terms (such as sorting on author name first, and then publish date). + +Those extra sorting options require **[Table Aliases]**, introduced below. + + +## Columns Selected by an Association + +By default, associated records include all their columns: + +```swift +// SELECT book.*, author.* +// FROM book +// JOIN author ON author.id = book.authorId +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: + +```swift +// SELECT book.*, author.id, author.name +// FROM book +// JOIN author ON author.id = book.authorId +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, define the `databaseSelection` property: + +```swift +struct RestrictedAuthor: TableRecord { + static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")] +} + +struct ExtendedAuthor: TableRecord { + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] +} + +extension Book { + static let restrictedAuthor = belongsTo(RestrictedAuthor.self) + static let extendedAuthor = belongsTo(ExtendedAuthor.self) +} + +// SELECT book.*, author.id, author.name +// FROM book +// JOIN author ON author.id = book.authorId +let request = Book.including(required: Book.restrictedAuthor) + +// SELECT book.*, author.*, author.rowid +// FROM book +// JOIN author ON author.id = book.authorId +let request = Book.including(required: Book.extendedAuthor) +``` + +Modifying `databaseSelection` not only affects joined requests, but all requests built from the modified record. This is how records make sure they are always fed with the columns they need, no more, no less: + +```swift +// SELECT id, name FROM author +let request = RestrictedAuthor.all() +``` + +> :point_up: **Note**: make sure the `databaseSelection` property is explicitely declared as `[SQLSelectable]`. If it is not, the Swift compiler may infer a type which may silently miss the protocol requirement, resulting in sticky SELECT * requests. See [Columns Selected by a Request](https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#columns-selected-by-a-request) for further information. + + +## Table Aliases + +In all examples we have seen so far, all associated records are joined, included, filtered, and sorted independently. We could not filter them on conditions that involve several records, for example. + +Let's say we look for posthumous books, published after their author has died. We need to compare a book publication date with an author eventual death date. + +Let's first see a wrong way to do it: + +```swift +// A wrong request: +// SELECT book.* +// FROM book +// JOIN person ON person.id = book.authorId +// WHERE book.publishDate >= book.deathDate +let request = Book + .joining(required: Book.author) + .filter(Column("publishDate") >= Column("deathDate")) +``` + +When executed, we'll get a DatabaseError of code 1, "no such column: book.deathDate". + +That is because the "deathDate" column has been used for filtering books, when it is defined on the person database table. + +To fix this error, we need a **table alias**: + +```swift +let authorAlias = TableAlias() +``` + +We modify the `Book.author` association so that it uses this table alias, and we use the table alias to qualify author columns where needed: + +```swift +// SELECT book.* +// FROM book +// JOIN person ON person.id = book.authorId +// WHERE book.publishDate >= person.deathDate +let request = Book + .joining(required: Book.author.aliased(authorAlias)) + .filter(Column("publishDate") >= authorAlias[Column("deathDate")]) +``` + +**Table aliases** can also improve control over the ordering of request results. In the example below, we override the [default ordering](#sorting-associations) of associated records by sorting on author names first: + +```swift +// SELECT book.* +// FROM book +// JOIN person ON person.id = book.authorId +// ORDER BY person.name, book.publishDate +let request = Book + .joining(required: Book.author.aliased(authorAlias)) + .order(authorAlias[Column("name")], Column("publishDate")) +``` + +**Table aliases** can be given a name. This name is guaranteed to be used as the table alias in the SQL query. This guarantee lets you write SQL snippets when you need it: + +```swift +// SELECT myBook.* +// FROM book myBook +// JOIN person myAuthor ON myAuthor.id = myBook.authorId +// AND myAuthor.countryCode = 'FR' +// WHERE myBook.publishDate >= myAuthor.deathDate +let bookAlias = TableAlias(name: "myBook") +let authorAlias = TableAlias(name: "myAuthor") +let request = Book.aliased(bookAlias) + .joining(required: Book.author.aliased(authorAlias) + .filter(sql: "myAuthor.countryCode = ?", arguments: ["FR"])) + .filter(sql: "myBook.publishDate >= myAuthor.deathDate") +``` + + +Fetching Values from Associations +================================= + +We have seen in [Building Requests from Associations] how to define requests that involve several records by the mean of [Joining Methods]. + +If your application needs to display a list of books with information about their author, country, and cover image, you may build the following joined request: + +```swift +// SELECT book.*, author.*, country.*, coverImage.* +// FROM book +// JOIN author ON author.id = book.authorId +// LEFT JOIN country ON country.code = author.countryCode +// LEFT JOIN coverImage ON coverImage.bookId = book.id +let request = Book + .including(required: Book.author + .including(optional: Author.country)) + .including(optional: Bool.coverImage) +``` + +**Now is the time to tell how joined requests should be consumed.** + +As always in GRDB, requests can be consumed as raw database rows, or as well-structured and convenient records. + +The request above can be consumed into the following record: + +```swift +struct BookInfo: FetchableRecord, Decodable { + var book: Book + var author: Author + var country: Country? + var coverImage: CoverImage? +} + +let bookInfos = try BookInfo.fetchAll(db, request) // [BookInfo] +``` + +If we consume raw rows, we start to see what's happening under the hood: + +```swift +let row = try Row.fetchOne(db, request)! // Row +print(row.debugDescription) +// ▿ [id:1, authorId:2, title:"Moby-Dick"] +// unadapted: [id:1, authorId:2, title:"Moby-Dick", id:2, name:"Herman Melville", countryCode:"US", code:"US", name:"United States of America", id:42, imageId:1, path:"moby-dick.jpg"] +// - author: [id:2, name:"Herman Melville", countryCode:"US"] +// - country: [code:"US", name:"United States of America"] +// - coverImage: [id:42, imageId:1, path:"moby-dick.jpg"] +``` + +- [The Structure of a Joined Request] +- [Decoding a Joined Request with a Decodable Record] +- [Decoding a Joined Request with FetchableRecord] + + +## The Structure of a Joined Request + +**Joined request define a tree of associated records identified by "association keys".** + +Below, author and cover image are both associated to book, and country is associated to author: + +```swift +let request = Book + .including(required: Book.author + .including(optional: Author.country)) + .including(optional: Bool.coverImage) +``` + +This request builds the following **tree of association keys**: + +![TreeOfAssociationKeys](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/TreeOfAssociationKeys.svg) + +**Association keys** are strings. They are the names of the database tables of associated records (unless you specify otherwise, as we'll see below). + +Those keys are associated with slices in the fetched rows: + +![TreeOfAssociationKeysMapping](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg) + +We'll see below how this tree of association keys and row slices can feed a Decodable record type. We'll then add some details by using FetchableRecord without Decodable support. + + +## Decoding a Joined Request with a Decodable Record + +When **association keys** match the property names of a Decodable record, you get free decoding of joined requests into this record: + +```swift +struct BookInfo: FetchableRecord, Decodable { + var book: Book + var author: Author + var country: Country? + var coverImage: CoverImage? +} + +let bookInfos = try BookInfo.fetchAll(db, request) // [BookInfo] +``` + +We see that a hierarchical tree has been flattened in the `BookInfo` record. + +This flattening is made possible because the BookInfo initializer generated by the Decodable protocol matches **coding keys** with **association keys** by performing a breadth-first search in the tree of association keys. + +This deserves a little explanation: + +You known that the Decodable protocol feeds a value's properties by looking for **coding keys**. For example, the standard built-in JSONDecoder matches those coding keys with dictionary keys in a JSON object. The GRDB record decoder also matches coding keys, but with association keys: + +![TreeOfAssociationKeysMapping](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg) + +Practically speaking, the BookInfo initializer first looks for the "book" coding key. This key is not found anywhere in the tree of association keys, so the book property is initialized from the row slice associated with the root of the tree, which contains book columns. + +The BookInfo initializer then looks for the "author", "country", and "coverImage" coding keys. All those are found in the tree of association keys, and each property is initialized from its matching row slice. + +The key lookup digs into the tree of association keys, and stops as soon as a key as been found, digging into deep tree levels only if the key was not found in higher levels (that's called a "breadth-first search"). This is how we can decode a hierarchical tree into a flat record. + +But sometimes your decoded records will have better reflect the hierarchical structure of the request: + + +### Decoding a Hierarchical Decodable Record + +Some requests are better decoded with a Decodable record that reflects the hierarchical structure of the request. + +```swift +let request = Book + .including(optional: Bool.coverImage) + .including(required: Book.author + .including(optional: Person.country)) + .including(optional: Book.translator + .including(optional: Person.country)) +``` + +This requests for all books, with their cover images, and their authors and translators. Those people are themselves decorated with their respective nationalities. + +We plan to decode this request into is the following record: + +```swift +struct BookInfo: FetchableRecord, Decodable { + struct AuthorInfo: Decodable { + var author: Author + var country: Country? + } + var book: Book + var authorInfo: AuthorInfo + var translatorInfo: AuthorInfo? + var coverImage: CoverImage? +} +``` + +This request needs a little preparation: we need **association keys** that match the **coding keys** for the authorInfo and translatorInfo properties. + +And who is the most able to know those coding keys? BookInfo itself, thanks to its `CodingKeys` enum that was automatically generated by the Swift compiler. We thus define the `BookInfo.all()` method that builds our request: + +```swift +extension BookInfo { + static func all() -> QueryInterfaceRequest { + return Book + .including(optional: Bool.coverImage) + .including(required: Book.author + .forKey(CodingKeys.authorInfo) // (1) + .including(optional: Person.country)) + .including(optional: Book.translator + .forKey(CodingKeys.translatorInfo) // (1) + .including(optional: Person.country)) + .asRequest(of: BookInfo.self) // (2) + } +} + +let bookInfos = try BookInfo.all().fetchAll(db, request) // [BookInfo] +``` + +1. The `forKey(_:)` method changes the association key, so that the associated records can feed their target properties. +2. The `asRequest(of:)` method turns the request into a request of BookInfo. See [Custom Requests] for more information. + + +### Debugging Joined Request Decoding + +When you have difficulties building a Decodable record that successfully decodes a joined request, we advise to temporarily decode raw database rows, and inspect them. + +```swift +let request = Book + .including(required: Book.author + .including(optional: Author.country)) + .including(optional: Bool.coverImage) + +let rows = try Row.fetchAll(db, request) +print(rows[0]) +// Prints: +// ▿ [id:1, authorId:2, title:"Moby-Dick"] +// unadapted: [id:1, authorId:2, title:"Moby-Dick", id:2, name:"Herman Melville", countryCode:"US", code:"US", name:"United States of America", id:NULL, imageId:NULL, path:NULL] +// - person: [id:2, name:"Herman Melville", countryCode:"US"] +// - country: [code:"US", name:"United States of America"] +// - coverImage: [id:NULL, imageId:NULL, path:NULL] +``` + +There are two important things to look into the row debugging description: + +- the **association keys**: "person", "country", and "coverImage" in our example +- associated rows that contain only null values (coverImage). + +The associated rows that contain only null values are easy to deal with: null rows loaded from optional associated records should be decoded into Swift optionals: + +```swift +struct BookInfo: FetchableRecord, Decodable { + var book: Book + var author: Author // .including(required: Book.author) + var country: Country? // .including(optional: Author.country) + var coverImage: CoverImage? // .including(optional: Bool.coverImage) +} +``` + +**Association keys** may not match the property names of your Decodable record. In this case, use the `forKey(_:)` method. + +This can be done at the request level: + +```swift +struct BookInfo: FetchableRecord, Decodable { + var book: Book + var author: Author // Expect "author" association key + var country: Country? + var coverImage: CoverImage? +} + +let request = Book + .including(required: Book.author + .forKey("author") // Change association key + .including(optional: Author.country)) + .including(optional: Bool.coverImage) +``` + +Association keys can also be defined right into the definition of the association: + +```swift +struct Book { + static let author = belongsTo(Person.self).forKey("author") +} + +let request = Book + .including(required: Book.author // "author" association key + .including(optional: Author.country)) + .including(optional: Bool.coverImage) +``` + +The best choice is up to you and the structure of your application. See also [Decoding a Hierarchical Decodable Record] for further discussion about decoding keys. + + +## Decoding a Joined Request with FetchableRecord + +When [Dedocable](#decoding-a-joined-request-with-a-decodable-record) records provides convenient decoding of joined rows, you may want a little more control over row decoding. + +The `init(row:)` initializer of the FetchableRecord protocol is what you look after: + +```swift +struct BookInfo: FetchableRecord { + var book: Book + var author: Author + var country: Country? + var coverImage: CoverImage? + + init(row: Row) { + book = Book(row: row) + author = row["author"] + country = row["country"] + coverImage = row["coverImage"] + } +} + +let bookInfos = try BookInfo.fetchAll(db, request) // [BookInfo] +``` + +You are already familiar with row subscripts to decode [database values](https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#column-values): + +```swift +let name: String = row["name"] +``` + +When you extract a record instead of a value from a row, GRDB perfoms a breadth-first search in the tree of **association keys** defined by the joined request. If the key is not found, or only associated with columns that all contain NULL values, an optional record is decoded as nil: + +```swift +let author: Author = row["author"] +let country: Country? = row["country"] +``` + +You can also perform custom navigation in the tree by using *row scopes*. See [Row Adapters] for more information. + + +## Known Issues + +**You can't chain a required association on an optional association:** + +```swift +// NOT IMPLEMENTED +let request = Book + .joining(optional: Book.author + .including(required: Person.country)) +``` + +This code compiles, but you'll get a runtime fatal error "Not implemented: chaining a required association behind an optional association". Future versions of GRDB may allow such requests. + +**You can't join two associations with the same [association key](#the-structure-of-a-joined-request) at the same level:** + +```swift +// NOT IMPLEMENTED +let request = Book + .including(Book.author) // key "author" + .including(Book.author) // key "author" +``` + +This code compiles, but you'll get a runtime fatal error "The association key `author` is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.". Future versions of GRDB may allow such requests. + +To join the same table twice, and make sure GRDB does not modify the fetched results in some future release, make sure no two associations have the same name on a given level: + +```swift +// OK +let request = Book + .including(Book.author.forKey("firstAuthor")) + .including(Book.author.forKey("secondAuthor")) +``` + + +## Future Directions + +The APIs that have been described above do not cover the whole topic of joined requests. Among the biggest omissions, there is: + +- One can not yet join two tables without a foreign key. One can not build the plain `SELECT * FROM a JOIN b`, for example. + +- One can not yet express requests such as "all authors with all their books". + +- A common use case of associations is aggregations, such as fetching all authors with the number of books they have written: + + ```swift + let request = Author.annotate(with: Author.books.count) + ``` + +- There's no HasOneThrough and HasManyThrough association, which would allow to skip intermediate bridge records when building requests. + +Those features are not present yet because they hide several very tough challenges. Come [discuss](http://twitter.com/groue) for more information, or if you wish to help turning those features into reality. + + +--- + +This documentation owns a lot to the [Active Record Associations](http://guides.rubyonrails.org/association_basics.html) guide, which is an immensely well-written introduction to database relations. Many thanks to the Rails team and contributors. + +--- + +### LICENSE + +**GRDB** + +Copyright (C) 2018 Gwendal Roué + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +**Ruby on Rails documentation** + +Copyright (c) 2005-2018 David Heinemeier Hansson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +[Associations Benefits]: #associations-benefits +[BelongsTo]: #belongsto +[HasOne]: #hasone +[HasMany]: #hasmany +[Choosing Between BelongsTo and HasOne]: #choosing-between-belongsto-and-hasone +[Self Joins]: #self-joins +[The Types of Associations]: #the-types-of-associations +[Codable]: https://developer.apple.com/documentation/swift/codable +[FetchableRecord]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#fetchablerecord-protocols +[migration]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#migrations +[Record]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#records +[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions +[Associations and the Database Schema]: #associations-and-the-database-schema +[Convention for Database Table Names]: #convention-for-database-table-names +[Convention for the BelongsTo Association]: #convention-for-the-belongsto-association +[Convention for the HasOne Association]: #convention-for-the-hasone-association +[Convention for the HasMany Association]: #convention-for-the-hasmany-association +[Foreign Keys]: #foreign-keys +[Building Requests from Associations]: #building-requests-from-associations +[Fetching Values from Associations]: #fetching-values-from-associations +[Combining Associations]: #combining-associations +[Requesting Associated Records]: #requesting-associated-records +[Joining Methods]: #joining-methods +[Filtering Associations]: #filtering-associations +[Sorting Associations]: #sorting-associations +[Columns Selected by an Association]: #columns-selected-by-an-association +[Table Aliases]: #table-aliases +[The Structure of a Joined Request]: #the-structure-of-a-joined-request +[Decoding a Joined Request with a Decodable Record]: #decoding-a-joined-request-with-a-decodable-record +[Decoding a Hierarchical Decodable Record]: #decoding-a-hierarchical-decodable-record +[Decoding a Joined Request with FetchableRecord]: #decoding-a-joined-request-with-fetchablerecord +[Custom Requests]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#custom-requests +[Known Issues]: #known-issues +[Future Directions]: #future-directions +[Row Adapters]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#row-adapters \ No newline at end of file diff --git a/Documentation/Images/Associations2/AmbiguousForeignKeys.svg b/Documentation/Images/Associations2/AmbiguousForeignKeys.svg new file mode 100644 index 000000000..67ac61af5 --- /dev/null +++ b/Documentation/Images/Associations2/AmbiguousForeignKeys.svg @@ -0,0 +1,154 @@ + + + + AmbiguousForeignKeys + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + authorId + + + integer + + + + + + + + translatorId + + + integer + + + + + + + + title + + + text + + + + + + book + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + name + + + text + + + + + + + + + + + + + person + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/Associations.sketch b/Documentation/Images/Associations2/Associations.sketch new file mode 100644 index 000000000..561df5fc6 Binary files /dev/null and b/Documentation/Images/Associations2/Associations.sketch differ diff --git a/Documentation/Images/Associations2/BelongsToSchema.svg b/Documentation/Images/Associations2/BelongsToSchema.svg new file mode 100644 index 000000000..720e2bd11 --- /dev/null +++ b/Documentation/Images/Associations2/BelongsToSchema.svg @@ -0,0 +1,133 @@ + + + + BelongsToSchema + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + authorId + + + integer + + + + + + + + title + + + text + + + + + + book + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + name + + + text + + + + + + + + + + + + + author + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/HasManySchema.svg b/Documentation/Images/Associations2/HasManySchema.svg new file mode 100644 index 000000000..189ed0188 --- /dev/null +++ b/Documentation/Images/Associations2/HasManySchema.svg @@ -0,0 +1,135 @@ + + + + HasManySchema + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + authorId + + + integer + + + + + + + + title + + + text + + + + + + book + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + name + + + text + + + + + + + + + + + + + author + + + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/HasManyThroughSchema.svg b/Documentation/Images/Associations2/HasManyThroughSchema.svg new file mode 100644 index 000000000..a3219c05f --- /dev/null +++ b/Documentation/Images/Associations2/HasManyThroughSchema.svg @@ -0,0 +1,185 @@ + + + + HasManyThroughSchema + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + countryCode + + + text + + + + + + + + citizenId + + + integer + + + + + + + + issueDate + + + date + + + + + + passport + + + + + + + + + + + + + + + + code + + + text + + + + + + + + name + + + text + + + + + + country + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + name + + + text + + + + + + citizen + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/HasOneSchema.svg b/Documentation/Images/Associations2/HasOneSchema.svg new file mode 100644 index 000000000..b774fc54f --- /dev/null +++ b/Documentation/Images/Associations2/HasOneSchema.svg @@ -0,0 +1,153 @@ + + + + HasOneSchema + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + countryCode + + + text + + + + + + + + population + + + integer + + + + + + + + density + + + double + + + + + + demographics + + + + + + + + + + + + + + + + code + + + text + + + + + + + + name + + + text + + + + + + + + + + + + + + + + + + + + country + + + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/HasOneThroughSchema.svg b/Documentation/Images/Associations2/HasOneThroughSchema.svg new file mode 100644 index 000000000..cca317fce --- /dev/null +++ b/Documentation/Images/Associations2/HasOneThroughSchema.svg @@ -0,0 +1,198 @@ + + + + HasOneThroughSchema + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + name + + + text + + + + + + library + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + libraryId + + + integer + + + + + + + + title + + + text + + + + + + book + + + + + + + + + + + + + + + + libraryId + + + integer + + + + + + + + street + + + text + + + + + + + + city + + + text + + + + + + address + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/Makefile b/Documentation/Images/Associations2/Makefile new file mode 100644 index 000000000..7c42c98f5 --- /dev/null +++ b/Documentation/Images/Associations2/Makefile @@ -0,0 +1,3 @@ +fixfonts: + sed -i '' -- 's/SFUIText-Regular, SF UI Text/-apple-system,sans-serif/g' *.svg + sed -i '' -- 's/SFUIText-Semibold, SF UI Text/-apple-system,sans-serif/g' *.svg diff --git a/Documentation/Images/Associations2/RecursiveSchema.svg b/Documentation/Images/Associations2/RecursiveSchema.svg new file mode 100644 index 000000000..9970827e3 --- /dev/null +++ b/Documentation/Images/Associations2/RecursiveSchema.svg @@ -0,0 +1,91 @@ + + + + RecursiveSchema + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + managerId + + + integer + + + + + + + + name + + + text + + + + + + + + + + + + + employee + + + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/TreeOfAssociationKeys.svg b/Documentation/Images/Associations2/TreeOfAssociationKeys.svg new file mode 100644 index 000000000..d3d3032f7 --- /dev/null +++ b/Documentation/Images/Associations2/TreeOfAssociationKeys.svg @@ -0,0 +1,110 @@ + + + + TreeOfAssociationKeys + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + root + + + + + + + + + + + + + + "author" + + + + + + + + + + + + + + "coverImage" + + + + + + + + + + + + + + "country" + + + + + diff --git a/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg b/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg new file mode 100644 index 000000000..4a1d65d5b --- /dev/null +++ b/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg @@ -0,0 +1,130 @@ + + + + TreeOfAssociationKeysMapping + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + root + + + + + + + + + + + + + + "author" + + + + + + + + + + + + + + "coverImage" + + + + + + + + + + + + + + "country" + + + + + SELECT + book.* + , + author.* + , + country.* + , + coverImage.* + + FROM … + + + + + + diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 571eaeeb5..4a264ad8d 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -148,6 +148,64 @@ 564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; + 5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EAD920944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EADB20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EADC20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EADD20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EADE20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EADF20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EAE020944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACB20944B4D00F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EAE120944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACB20944B4D00F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EAE220944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACC20944B4D00F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EAE320944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACC20944B4D00F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACD20944B4D00F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EAE520944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACD20944B4D00F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EAE620944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACE20944B4D00F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EAE720944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACE20944B4D00F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */; }; + 5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */; }; + 5653EAEC20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD120944B4E00F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EAED20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD120944B4E00F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD220944B4E00F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD220944B4E00F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EAF220944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD420944B4E00F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EAF320944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD420944B4E00F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EAF420944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EAF520944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */; }; + 5653EB0420944C7C00F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */; }; + 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */; }; + 5653EB0620944C7C00F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */; }; + 5653EB0720944C7C00F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */; }; + 5653EB0820944C7C00F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */; }; + 5653EB0920944C7C00F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFA20944C7B00F46237 /* Association.swift */; }; + 5653EB0A20944C7C00F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFA20944C7B00F46237 /* Association.swift */; }; + 5653EB0B20944C7C00F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFA20944C7B00F46237 /* Association.swift */; }; + 5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; + 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; + 5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; + 5653EB0F20944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; + 5653EB1020944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; + 5653EB1120944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; + 5653EB1520944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; + 5653EB1620944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; + 5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; + 5653EB1820944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; + 5653EB1920944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; + 5653EB1A20944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; + 5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; }; + 5653EB2220944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; }; + 5653EB2320944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; }; + 5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; }; + 5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; }; + 5653EC142098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; }; 565490B41D5A4820005622CB /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3773F819C8CBB3004FCF85 /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; 565490B51D5A4827005622CB /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; 565490B61D5AE236005622CB /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; }; @@ -423,9 +481,6 @@ 56B021CD1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; - 56B1C3CD201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; - 56B1C3CE201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; - 56B1C3CF201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; 56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; }; 56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; }; 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; }; @@ -809,6 +864,30 @@ 564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; + 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainRowScopesTests.swift; sourceTree = ""; }; + 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; + 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRowScopeSearchTests.swift; sourceTree = ""; }; + 5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLTests.swift; sourceTree = ""; }; + 5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLDerivationTests.swift; sourceTree = ""; }; + 5653EACB20944B4D00F46237 /* AssociationTableAliasTestsSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationTableAliasTestsSQLTests.swift; sourceTree = ""; }; + 5653EACC20944B4D00F46237 /* AssociationHasOneSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLTests.swift; sourceTree = ""; }; + 5653EACD20944B4D00F46237 /* AssociationParallelRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelRowScopesTests.swift; sourceTree = ""; }; + 5653EACE20944B4D00F46237 /* AssociationBelongsToFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToFetchableRecordTests.swift; sourceTree = ""; }; + 5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; + 5653EAD120944B4E00F46237 /* AssociationBelongsToSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLDerivationTests.swift; sourceTree = ""; }; + 5653EAD220944B4E00F46237 /* AssociationParallelDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelDecodableRecordTests.swift; sourceTree = ""; }; + 5653EAD420944B4E00F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; + 5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; + 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; + 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; + 5653EAFA20944C7B00F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; + 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; + 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; + 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationQuery.swift; sourceTree = ""; }; + 5653EAFF20944C7C00F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; + 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; + 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; + 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; 565490A01D5A4798005622CB /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXCrashTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; @@ -948,7 +1027,6 @@ 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; - 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; @@ -1268,6 +1346,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EABF20944B1300F46237 /* Association */, 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, @@ -1284,17 +1363,20 @@ 56300B6D1C53F592005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EAF720944BC900F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, + 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */, 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */, 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */, + 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */, 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, @@ -1319,6 +1401,42 @@ name = DatabaseQueue; sourceTree = ""; }; + 5653EABF20944B1300F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EAD420944B4E00F46237 /* AssociationBelongsToDecodableRecordTests.swift */, + 5653EACE20944B4D00F46237 /* AssociationBelongsToFetchableRecordTests.swift */, + 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */, + 5653EAD120944B4E00F46237 /* AssociationBelongsToSQLDerivationTests.swift */, + 5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */, + 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */, + 5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */, + 5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */, + 5653EACC20944B4D00F46237 /* AssociationHasOneSQLTests.swift */, + 5653EAD220944B4E00F46237 /* AssociationParallelDecodableRecordTests.swift */, + 5653EACD20944B4D00F46237 /* AssociationParallelRowScopesTests.swift */, + 5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */, + 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */, + 5653EACB20944B4D00F46237 /* AssociationTableAliasTestsSQLTests.swift */, + ); + name = Association; + sourceTree = ""; + }; + 5653EAF720944BC900F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EAFA20944C7B00F46237 /* Association.swift */, + 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */, + 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */, + 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */, + 5653EAFF20944C7C00F46237 /* ForeignKey.swift */, + 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */, + 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */, + 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */, + ); + path = Association; + sourceTree = ""; + }; 5659F4861EA8D94E004A4992 /* Utils */ = { isa = PBXGroup; children = ( @@ -1626,7 +1744,6 @@ 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, 569A98EC2039B6F3008D7DBF /* Fixits-3.0.swift */, - 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */, ); path = Legacy; sourceTree = ""; @@ -2191,6 +2308,7 @@ 5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, + 5653EB0B20944C7C00F46237 /* Association.swift in Sources */, 56F5ABDA1D814330001F60CB /* NSData.swift in Sources */, 56D121601ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */, @@ -2198,6 +2316,7 @@ 5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */, 56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, + 5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 565490B91D5AE236005622CB /* DatabasePool.swift in Sources */, 5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */, @@ -2207,12 +2326,14 @@ 565490D91D5AE252005622CB /* Migration.swift in Sources */, 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 5653EB1120944C7C00F46237 /* AssociationRequest.swift in Sources */, C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */, 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */, 56F3E7691E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 5698AC7E1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, + 5653EB1A20944C7C00F46237 /* ForeignKey.swift in Sources */, 5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */, 566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, @@ -2227,6 +2348,7 @@ 565490C31D5AE236005622CB /* RowAdapter.swift in Sources */, 5698AD3B1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, 5659F49E1EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */, 565490CA1D5AE252005622CB /* DatabaseDateComponents.swift in Sources */, 565490D01D5AE252005622CB /* NSString.swift in Sources */, @@ -2235,6 +2357,7 @@ 5674A6E81F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 56873BF21F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D431DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, + 5653EB2320944C7C00F46237 /* HasOneAssociation.swift in Sources */, 565490C01D5AE236005622CB /* DatabaseWriter.swift in Sources */, 565490C41D5AE236005622CB /* SchedulingWatchdog.swift in Sources */, 566B91311FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, @@ -2243,6 +2366,7 @@ 56BF6D351DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 566B91291FA4CF810012D5B0 /* Database+Schema.swift in Sources */, 5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, + 5653EC142098738B00F46237 /* SQLGenerationContext.swift in Sources */, 56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */, 5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, @@ -2267,13 +2391,15 @@ 56F5ABDD1D814330001F60CB /* UUID.swift in Sources */, 565490CB1D5AE252005622CB /* (null) in Sources */, 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, + 5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 56BF6D3C1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, - 56B1C3CF201C8D0E001938DA /* Swift4.1.swift in Sources */, 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */, + 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 565490BC1D5AE236005622CB /* DatabaseSchemaCache.swift in Sources */, 565490BA1D5AE236005622CB /* DatabaseQueue.swift in Sources */, 565490CD1D5AE252005622CB /* Date.swift in Sources */, + 5653EB0820944C7C00F46237 /* ForeignKeyRequest.swift in Sources */, 565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -2307,16 +2433,19 @@ 5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, 566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 5653EB0A20944C7C00F46237 /* Association.swift in Sources */, 56A2387E1B9C75030082EB20 /* Database.swift in Sources */, 56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5605F15A1C672E4000235C62 /* CGFloat.swift in Sources */, 56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */, + 5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5605F1641C672E4000235C62 /* Date.swift in Sources */, 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 5659F49B1EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB2220944C7C00F46237 /* HasOneAssociation.swift in Sources */, 569A98EE2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 56CEB51C1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 5698AC3A1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, @@ -2325,6 +2454,7 @@ 563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */, 5698AD1B1DAAD17D0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7661E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, + 5653EB0420944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 56B964B41DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, 566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, @@ -2335,11 +2465,14 @@ 56A8C2331D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D321DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, + 5653EB1020944C7C00F46237 /* AssociationRequest.swift in Sources */, 566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, + 5653EB1620944C7C00F46237 /* AssociationQuery.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, + 5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 5659F48B1EA8D94E004A4992 /* Utils.swift in Sources */, @@ -2349,7 +2482,6 @@ 5674A7081F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 56A2388C1B9C75030082EB20 /* Statement.swift in Sources */, 5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */, - 56B1C3CE201C8D0E001938DA /* Swift4.1.swift in Sources */, 5605F1941C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, 5690C3431D23E82A00E59934 /* Data.swift in Sources */, @@ -2363,6 +2495,7 @@ 5605F15E1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 56BF6D391DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */, + 5653EB1920944C7C00F46237 /* ForeignKey.swift in Sources */, 5659F4A31EA8D997004A4992 /* Result.swift in Sources */, 56B964BC1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 5605F1661C672E4000235C62 /* NSNull.swift in Sources */, @@ -2371,6 +2504,7 @@ 5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, 56D1215D1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, + 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */, @@ -2380,6 +2514,7 @@ 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, + 5653EB0720944C7C00F46237 /* ForeignKeyRequest.swift in Sources */, 5657AABC1D107001006283EF /* NSData.swift in Sources */, 31A778841C6A4E0600F507F6 /* FetchedRecordsController.swift in Sources */, 56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */, @@ -2434,6 +2569,7 @@ 56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 562393341DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 5698AC841DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, + 5653EAE320944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */, 566AD8CA1D531BEC002EC1A8 /* TableDefinitionTests.swift in Sources */, 56A238541B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift in Sources */, 56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */, @@ -2448,12 +2584,14 @@ 5657AB421D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56CC922D201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */, 56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, + 5653EADD20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56176C6B1EACCCC9000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 56300B621C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */, 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 5657AB6A1D108BA9006283EF /* FoundationURLTests.swift in Sources */, + 5653EADF20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */, 56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */, @@ -2472,6 +2610,7 @@ 560A37AC1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift in Sources */, 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */, 5690C33B1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, + 5653EAF320944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 565D5D721BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */, 5623936D1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, @@ -2491,19 +2630,25 @@ 565B0FF01BBC7D980098DE03 /* FetchableRecordTests.swift in Sources */, 5698AC9A1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 562393521DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, + 5653EAE520944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */, 56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, + 5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, 5698ACD21DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */, + 5653EAE120944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, + 5653EAE720944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5695312A1C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift in Sources */, + 5653EADB20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5698ACA21DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, 56A2385C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 56A238401B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */, + 5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */, 5690C32A1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, 5657AB3A1D108BA9006283EF /* FoundationDataTests.swift in Sources */, @@ -2519,17 +2664,21 @@ 568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, 5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */, + 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, 562393641DEE06D300A6B01F /* CursorTests.swift in Sources */, 5657AB5A1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 56300B6C1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 5674A7231F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56F0B9921B6001C600A2F135 /* FoundationNSDateTests.swift in Sources */, 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */, + 5653EAED20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */, 5634B10A1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 560C97C81BFD0B8400BF8471 /* DatabaseFunctionTests.swift in Sources */, + 5653EAD920944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 56A2383A1B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift in Sources */, 56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */, + 5653EAF520944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */, 56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */, 5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */, @@ -2581,6 +2730,7 @@ 56D4967C1D8130DB008276D7 /* CGFloatTests.swift in Sources */, 56D496631D81304E008276D7 /* FoundationURLTests.swift in Sources */, 56D496B71D81344B008276D7 /* RecordUniqueIndexTests.swift in Sources */, + 5653EAE220944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */, 56D496671D813086008276D7 /* Record+QueryInterfaceRequestTests.swift in Sources */, 56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, 56D496AE1D813345008276D7 /* DatabasePoolCollationTests.swift in Sources */, @@ -2595,12 +2745,14 @@ 56D4965E1D81304E008276D7 /* FoundationNSStringTests.swift in Sources */, 5698AC891DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */, + 5653EADC20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56D5075E1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */, 567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 56D4968D1D81316E008276D7 /* DatabaseFunctionTests.swift in Sources */, + 5653EADE20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 56D496661D813086008276D7 /* QueryInterfaceRequestTests.swift in Sources */, 56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */, @@ -2619,6 +2771,7 @@ 5698AC031D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 56D496611D81304E008276D7 /* Row+FoundationTests.swift in Sources */, 56D496C41D813767008276D7 /* DatabaseQueueTests.swift in Sources */, + 5653EAF220944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56D496851D813147008276D7 /* StatementArgumentsTests.swift in Sources */, 56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */, 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */, @@ -2638,19 +2791,25 @@ 56176C5D1EACCCC7000F3F2B /* FTS5TokenizerTests.swift in Sources */, 56D496B21D8133CE008276D7 /* DatabaseQueueInMemoryTests.swift in Sources */, 562393601DEE06D300A6B01F /* CursorTests.swift in Sources */, + 5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */, 56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */, 56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */, 5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, + 5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, 56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */, + 5653EAE020944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, + 5653EAE620944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */, + 5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */, 56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */, 56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */, 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, + 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */, 56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */, 56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, @@ -2666,17 +2825,21 @@ 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */, + 5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, 5698AC801DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 56D496821D813131008276D7 /* TransactionObserverTests.swift in Sources */, 56D496941D81317B008276D7 /* SchedulingWatchdogTests.swift in Sources */, 5674A7201F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */, 56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, + 5653EAEC20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 5698ACB61DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 56D4965C1D81304E008276D7 /* FoundationNSNullTests.swift in Sources */, + 5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56D4967F1D813131008276D7 /* StatementColumnConvertibleTests.swift in Sources */, + 5653EAF420944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */, 56D496971D81317B008276D7 /* DatabaseReaderTests.swift in Sources */, 56D496911D81316E008276D7 /* RowFromStatementTests.swift in Sources */, 56071A411DB54ED000CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, @@ -2728,11 +2891,13 @@ 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 56E06F061E859064008AE2A4 /* Fixits-0.102.0.swift in Sources */, + 5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */, 5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7631E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, + 5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5605F1691C672E4000235C62 /* NSString.swift in Sources */, 560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, 56A8C2301D1914540096E9D4 /* UUID.swift in Sources */, @@ -2742,6 +2907,7 @@ 56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */, 56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BA1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, + 5653EB0920944C7C00F46237 /* Association.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, @@ -2755,7 +2921,6 @@ 5605F1931C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, 566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56A2388B1B9C75030082EB20 /* Statement.swift in Sources */, - 56B1C3CD201C8D0E001938DA /* Swift4.1.swift in Sources */, 5690C3401D23E82A00E59934 /* Data.swift in Sources */, 5659F4881EA8D94E004A4992 /* Utils.swift in Sources */, 56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, @@ -2763,12 +2928,16 @@ 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, 5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 56BF6D361DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, + 5653EB0F20944C7C00F46237 /* AssociationRequest.swift in Sources */, 56193E8E1CD8A3E200F95862 /* FetchedRecordsController.swift in Sources */, 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, + 5653EB1520944C7C00F46237 /* AssociationQuery.swift in Sources */, 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, 56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 5653EB1820944C7C00F46237 /* ForeignKey.swift in Sources */, 5674A6FB1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, + 5653EB0620944C7C00F46237 /* ForeignKeyRequest.swift in Sources */, 5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */, @@ -2778,10 +2947,13 @@ 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */, 56A238871B9C75030082EB20 /* Row.swift in Sources */, + 5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */, 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */, + 5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */, 560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 566475A21D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 5657AAB91D107001006283EF /* NSData.swift in Sources */, 560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */, diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 8de34aebe..0062157d4 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -132,7 +132,6 @@ extension Cursor { return nil } - #if swift(>=4.1) /// Returns a cursor over the concatenated non-nil results of mapping /// transform over this cursor. public func compactMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { @@ -143,13 +142,6 @@ extension Cursor { public func flatMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { return compactMap(transform) } - #else - /// Returns a cursor over the concatenated non-nil results of mapping - /// transform over this cursor. - public func flatMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { - return map(transform).filter { $0 != nil }.map { $0! } - } - #endif /// Returns a cursor that skips any initial elements that satisfy /// `predicate`. diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 7ac80ece1..fb0e98d66 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -232,24 +232,24 @@ extension Database { } /// Returns the actual name of the database table - func canonicalName(table: String) throws -> String { - if let canonicalName = schemaCache.canonicalName(table: table) { - return canonicalName + func canonicalTableName(_ tableName: String) throws -> String { + if let canonicalTableName = schemaCache.canonicalTableName(tableName) { + return canonicalTableName } - guard let canonicalName = try String.fetchOne(self, """ + guard let canonicalTableName = try String.fetchOne(self, """ SELECT name FROM ( SELECT name, type FROM sqlite_master UNION SELECT name, type FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ? - """, arguments: [table.lowercased()]) + """, arguments: [tableName.lowercased()]) else { - throw DatabaseError(message: "no such table: \(table)") + throw DatabaseError(message: "no such table: \(tableName)") } - schemaCache.set(canonicalName: canonicalName, forTable: table) - return canonicalName + schemaCache.set(canonicalTableName: canonicalTableName, forTable: tableName) + return canonicalTableName } } @@ -327,11 +327,11 @@ extension Database { /// This type closely matches the information returned by the /// `table_info` pragma. /// -/// > CREATE TABLE players ( +/// > CREATE TABLE player ( /// id INTEGER PRIMARY KEY, /// firstName TEXT, /// lastName TEXT) -/// > PRAGMA table_info("players") +/// > PRAGMA table_info("player") /// cid name type notnull dflt_value pk /// ---- ----- ------- -------- ---------- --- /// 0 id INTEGER 0 NULL 1 @@ -362,14 +362,14 @@ public struct ColumnInfo : FetchableRecord { /// For example: /// /// try db.execute(""" - /// CREATE TABLE players( + /// CREATE TABLE player( /// id INTEGER PRIMARY KEY, /// name TEXT DEFAULT 'Anonymous', /// score INT DEFAULT 0, /// creationDate DATE DEFAULT CURRENT_TIMESTAMP /// ) /// """) - /// let columnInfos = try db.columns(in: "players") + /// let columnInfos = try db.columns(in: "player") /// columnInfos[0].defaultValueSQL // nil /// columnInfos[1].defaultValueSQL // "'Anoynymous'" /// columnInfos[2].defaultValueSQL // "0" @@ -424,38 +424,38 @@ public struct IndexInfo { /// /// When the table's primary key is the rowid: /// -/// // CREATE TABLE items (name TEXT) -/// let pk = try db.primaryKey("items") +/// // CREATE TABLE item (name TEXT) +/// let pk = try db.primaryKey("item") /// pk.columns // ["rowid"] /// pk.rowIDColumn // nil /// pk.isRowID // true /// -/// // CREATE TABLE citizens ( +/// // CREATE TABLE citizen ( /// // id INTEGER PRIMARY KEY, /// // name TEXT /// // ) -/// let pk = try db.primaryKey("citizens")! +/// let pk = try db.primaryKey("citizen")! /// pk.columns // ["id"] /// pk.rowIDColumn // "id" /// pk.isRowID // true /// /// When the table's primary key is not the rowid: /// -/// // CREATE TABLE countries ( +/// // CREATE TABLE country ( /// // isoCode TEXT NOT NULL PRIMARY KEY /// // name TEXT /// // ) -/// let pk = db.primaryKey("countries")! +/// let pk = db.primaryKey("country")! /// pk.columns // ["isoCode"] /// pk.rowIDColumn // nil /// pk.isRowID // false /// -/// // CREATE TABLE citizenships ( -/// // citizenID INTEGER NOT NULL REFERENCES citizens(id) -/// // countryIsoCode TEXT NOT NULL REFERENCES countries(isoCode) +/// // CREATE TABLE citizenship ( +/// // citizenID INTEGER NOT NULL REFERENCES citizen(id) +/// // countryIsoCode TEXT NOT NULL REFERENCES country(isoCode) /// // PRIMARY KEY (citizenID, countryIsoCode) /// // ) -/// let pk = db.primaryKey("citizenships")! +/// let pk = db.primaryKey("citizenship")! /// pk.columns // ["citizenID", "countryIsoCode"] /// pk.rowIDColumn // nil /// pk.isRowID // false diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 4053f9535..7918fae44 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -1,12 +1,12 @@ import Foundation extension Database { - + // MARK: - Statements - + /// Returns a new prepared statement that can be reused. /// - /// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?") + /// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?") /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! /// @@ -19,7 +19,7 @@ extension Database { /// Returns a new prepared statement that can be reused. /// - /// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?", prepFlags: 0) + /// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0) /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! /// @@ -34,7 +34,7 @@ extension Database { /// Returns a prepared statement that can be reused. /// - /// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?") + /// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?") /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! /// @@ -55,7 +55,7 @@ extension Database { /// Returns a new prepared statement that can be reused. /// - /// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)") + /// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)") /// try statement.execute(arguments: ["Arthur"]) /// try statement.execute(arguments: ["Barbara"]) /// @@ -68,7 +68,7 @@ extension Database { /// Returns a new prepared statement that can be reused. /// - /// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)", prepFlags: 0) + /// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)", prepFlags: 0) /// try statement.execute(arguments: ["Arthur"]) /// try statement.execute(arguments: ["Barbara"]) /// @@ -83,7 +83,7 @@ extension Database { /// Returns a prepared statement that can be reused. /// - /// let statement = try db.cachedUpdateStatement("INSERT INTO players (name) VALUES (?)") + /// let statement = try db.cachedUpdateStatement("INSERT INTO player (name) VALUES (?)") /// try statement.execute(arguments: ["Arthur"]) /// try statement.execute(arguments: ["Barbara"]) /// @@ -105,13 +105,13 @@ extension Database { /// Executes one or several SQL statements, separated by semi-colons. /// /// try db.execute( - /// "INSERT INTO players (name) VALUES (:name)", + /// "INSERT INTO player (name) VALUES (:name)", /// arguments: ["name": "Arthur"]) /// /// try db.execute(""" - /// INSERT INTO players (name) VALUES (?); - /// INSERT INTO players (name) VALUES (?); - /// INSERT INTO players (name) VALUES (?); + /// INSERT INTO player (name) VALUES (?); + /// INSERT INTO player (name) VALUES (?); + /// INSERT INTO player (name) VALUES (?); /// """, arguments; ['Arthur', 'Barbara', 'Craig']) /// /// This method may throw a DatabaseError. diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 9d38e5cd9..cdde29f8b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -867,14 +867,6 @@ extension Database { self.rawValue = rawValue } - #if !swift(>=4.1) - /// The hash value - /// :nodoc: - public var hashValue: Int { - return rawValue.hashValue - } - #endif - /// The `BINARY` built-in SQL collation public static let binary = CollationName("BINARY") @@ -887,7 +879,7 @@ extension Database { /// An SQL column type. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// } @@ -906,14 +898,6 @@ extension Database { self.rawValue = rawValue } - #if !swift(>=4.1) - /// The hash value - /// :nodoc: - public var hashValue: Int { - return rawValue.hashValue - } - #endif - /// The `TEXT` SQL column type public static let text = ColumnType("TEXT") diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index 41c6520af..432293690 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -16,7 +16,7 @@ public final class DatabaseCollation { /// return (string1 as NSString).localizedStandardCompare(string2) /// } /// db.add(collation: collation) - /// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard") + /// try db.execute("CREATE TABLE file (name TEXT COLLATE localized_standard") /// /// - parameters: /// - name: The function name. diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index afa6cb5d9..778e3e8ef 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -139,16 +139,6 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8))) } -#if !swift(>=4.1) -// Equatable -extension ResultCode { - /// :nodoc: - public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool { - return lhs.rawValue == rhs.rawValue - } -} -#endif - // CustomStringConvertible extension ResultCode { /// :nodoc: diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 257740ff1..5cf33ea11 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -10,16 +10,6 @@ public final class DatabaseFunction: Hashable { private struct Identity: Hashable { let name: String let nArg: Int32 // -1 for variadic functions - - #if !swift(>=4.1) - var hashValue: Int { - return name.hashValue ^ nArg.hashValue - } - - static func == (lhs: Identity, rhs: Identity) -> Bool { - return lhs.name == rhs.name && lhs.nArg == rhs.nArg - } - #endif } public var name: String { return identity.name } @@ -373,10 +363,10 @@ public protocol DatabaseAggregate { /// aggregate function. /// /// -- One value - /// SELECT maxLength(name) FROM players + /// SELECT maxLength(name) FROM player /// /// -- Two values - /// SELECT maxFullNameLength(firstName, lastName) FROM players + /// SELECT maxFullNameLength(firstName, lastName) FROM player /// /// This method is never called after the finalize() method has been called. mutating func step(_ dbValues: [DatabaseValue]) throws diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 5d650d89a..29dee73e4 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -224,14 +224,14 @@ extension DatabasePool : DatabaseReader { /// /// try dbPool.read { db in /// // Those two values are guaranteed to be equal, even if the - /// // `wines` table is modified between the two requests: - /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! - /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// // `wine` table is modified between the two requests: + /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! + /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// try dbPool.read { db in /// // Now this value may be different: - /// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// This method is *not* reentrant. @@ -266,8 +266,8 @@ extension DatabasePool : DatabaseReader { /// try dbPool.unsafeRead { db in /// // Those two values may be different because some other thread /// // may have inserted or deleted a wine between the two requests: - /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! - /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! + /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// Cursor iteration is safe, though: @@ -303,8 +303,8 @@ extension DatabasePool : DatabaseReader { /// try dbPool.unsafeReentrantRead { db in /// // Those two values may be different because some other thread /// // may have inserted or deleted a wine between the two requests: - /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! - /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! + /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// Cursor iteration is safe, though: @@ -346,12 +346,12 @@ extension DatabasePool : DatabaseReader { /// database updates are *not visible* inside the block. /// /// try dbPool.write { db in - /// try db.execute("DELETE FROM players") + /// try db.execute("DELETE FROM player") /// try dbPool.readFromCurrentState { db in /// // Guaranteed to be zero - /// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")! + /// try Int.fetchOne(db, "SELECT COUNT(*) FROM player")! /// } - /// try db.execute("INSERT INTO players ...") + /// try db.execute("INSERT INTO player ...") /// } /// /// This method blocks the current thread until the isolation guarantee has @@ -611,7 +611,7 @@ extension DatabasePool : DatabaseReader { /// } /// dbPool.add(collation: collation) /// try dbPool.write { db in - /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") + /// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD") /// } public func add(collation: DatabaseCollation) { collations.update(with: collation) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index fac705911..600ed95c5 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -10,7 +10,7 @@ public final class DatabaseQueue: DatabaseWriter { #if os(iOS) private weak var application: UIApplication? #endif - + // MARK: - Configuration /// The database configuration @@ -291,7 +291,7 @@ extension DatabaseQueue { /// Synchronously executes a block in a protected dispatch queue, and /// returns its result. /// - /// // INSERT INTO players ... + /// // INSERT INTO player ... /// let players = try dbQueue.inDatabase { db in /// try Player(...).insert(db) /// } @@ -307,7 +307,7 @@ extension DatabaseQueue { /// Synchronously executes a block in a protected dispatch queue, and /// returns its result. /// - /// // INSERT INTO players ... + /// // INSERT INTO player ... /// try dbQueue.unsafeReentrantWrite { db in /// try Player(...).insert(db) /// } @@ -350,7 +350,7 @@ extension DatabaseQueue { /// } /// dbQueue.add(collation: collation) /// try dbQueue.write { db in - /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") + /// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD") /// } public func add(collation: DatabaseCollation) { writer.sync { $0.add(collation: collation) } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 5a33d8f20..b3222c6f0 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -31,14 +31,14 @@ public protocol DatabaseReader : class { /// /// try reader.read { db in /// // Those two values are guaranteed to be equal, even if the - /// // `wines` table is modified between the two requests: - /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! - /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// // `wine` table is modified between the two requests: + /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! + /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// try reader.read { db in /// // Now this value may be different: - /// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds @@ -61,8 +61,8 @@ public protocol DatabaseReader : class { /// try reader.unsafeRead { db in /// // Those two values may be different because some other thread /// // may have inserted or deleted a wine between the two requests: - /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! - /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! + /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// Cursor iterations are isolated, though: @@ -92,8 +92,8 @@ public protocol DatabaseReader : class { /// try reader.unsafeReentrantRead { db in /// // Those two values may be different because some other thread /// // may have inserted or deleted a wine between the two requests: - /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! - /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! + /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// Cursor iterations are isolated, though: @@ -144,7 +144,7 @@ public protocol DatabaseReader : class { /// return (string1 as NSString).localizedStandardCompare(string2) /// } /// reader.add(collation: collation) - /// try reader.execute("SELECT * FROM files ORDER BY name COLLATE localized_standard") + /// try reader.execute("SELECT * FROM file ORDER BY name COLLATE localized_standard") func add(collation: DatabaseCollation) /// Remove a collation. diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 678144fbf..b1e7383ec 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -18,27 +18,27 @@ /// /// - `SelectStatement.fetchedRegion`: /// -/// let statement = db.makeSelectStatement("SELECT name, score FROM players") +/// let statement = db.makeSelectStatement("SELECT name, score FROM player") /// print(statement.fetchedRegion) -/// // prints "players(name,score)" +/// // prints "player(name,score)" /// /// - `Request.fetchedRegion(_:)` /// /// let request = Player.filter(key: 1) /// try print(request.fetchedRegion(db)) -/// // prints "players(*)[1]" +/// // prints "player(*)[1]" /// /// Database regions returned by requests can be more precise than regions /// returned by select statements. Especially, regions returned by statements /// don't know about rowids: /// /// // A plain statement -/// let statement = db.makeSelectStatement("SELECT * FROM players WHERE id = 1") -/// statement.fetchedRegion // "players(*)" +/// let statement = db.makeSelectStatement("SELECT * FROM player WHERE id = 1") +/// statement.fetchedRegion // "player(*)" /// /// // A query interface request that executes the same statement: /// let request = Player.filter(key: 1) -/// try request.fetchedRegion(db) // "players(*)[1]" +/// try request.fetchedRegion(db) // "player(*)[1]" public struct DatabaseRegion: CustomStringConvertible, Equatable { private let tableRegions: [String: TableRegion]? private init(tableRegions: [String: TableRegion]?) { @@ -255,14 +255,6 @@ private struct TableRegion: Equatable { return false } - #if !swift(>=4.1) - static func == (lhs: TableRegion, rhs: TableRegion) -> Bool { - if lhs.columns != rhs.columns { return false } - if lhs.rowIds != rhs.rowIds { return false } - return true - } - #endif - func intersection(_ other: TableRegion) -> TableRegion { let columnsIntersection: Set? switch (self.columns, other.columns) { diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index 46d57e51c..237db0b97 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -2,8 +2,8 @@ protocol DatabaseSchemaCache { mutating func clear() - func canonicalName(table: String) -> String? - mutating func set(canonicalName: String, forTable table: String) + func canonicalTableName(_ table: String) -> String? + mutating func set(canonicalTableName: String, forTable table: String) func primaryKey(_ table: String) -> PrimaryKeyInfo? mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) @@ -20,26 +20,26 @@ protocol DatabaseSchemaCache { /// A thread-unsafe database schema cache struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { - private var canonicalNames: [String: String] = [:] + private var canonicalTableNames: [String: String] = [:] private var primaryKeys: [String: PrimaryKeyInfo] = [:] private var columns: [String: [ColumnInfo]] = [:] private var indexes: [String: [IndexInfo]] = [:] private var foreignKeys: [String: [ForeignKeyInfo]] = [:] mutating func clear() { - canonicalNames = [:] + canonicalTableNames = [:] primaryKeys = [:] columns = [:] indexes = [:] foreignKeys = [:] } - func canonicalName(table: String) -> String? { - return canonicalNames[table] + func canonicalTableName(_ table: String) -> String? { + return canonicalTableNames[table] } - mutating func set(canonicalName: String, forTable table: String) { - canonicalNames[table] = table + mutating func set(canonicalTableName: String, forTable table: String) { + canonicalTableNames[table] = table } func primaryKey(_ table: String) -> PrimaryKeyInfo? { @@ -79,8 +79,8 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { struct EmptyDatabaseSchemaCache: DatabaseSchemaCache { func clear() { } - func canonicalName(table: String) -> String? { return nil } - func set(canonicalName: String, forTable table: String) { } + func canonicalTableName(_ table: String) -> String? { return nil } + func set(canonicalTableName: String, forTable table: String) { } func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil } func set(primaryKey: PrimaryKeyInfo, forTable table: String) { } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 0a949573f..35bed7e2c 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -110,7 +110,7 @@ extension DatabaseSnapshot { /// } /// snapshot.add(collation: collation) /// let files = try snapshot.read { db in - /// try File.fetchAll(db, "SELECT * FROM files ORDER BY name COLLATE localized_standard") + /// try File.fetchAll(db, "SELECT * FROM file ORDER BY name COLLATE localized_standard") /// } public func add(collation: DatabaseCollation) { serializedDatabase.sync { $0.add(collation: collation) } diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 7f4603cf4..3b804a745 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -308,14 +308,13 @@ extension DatabaseValue { extension DatabaseValue { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { + public func expressionSQL(_ context: inout SQLGenerationContext) -> String { // fast path for NULL if isNull { return "NULL" } - if arguments != nil { - arguments!.values.append(self) + if context.appendArguments([self]) { return "?" } else { // Correctness above all: use SQLite to quote the value. @@ -352,7 +351,13 @@ extension DatabaseValue { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return self + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return self } } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index eb951b785..e5e35095b 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -42,7 +42,7 @@ extension DatabaseValueConvertible { /// For example: /// /// try dbQueue.read { db in -/// let urls: DatabaseValueCursor = try URL.fetchCursor(db, "SELECT url FROM links") +/// let urls: DatabaseValueCursor = try URL.fetchCursor(db, "SELECT url FROM link") /// while let url = urls.next() { // URL /// print(url) /// } @@ -82,7 +82,7 @@ public final class DatabaseValueCursor : Cursor /// For example: /// /// try dbQueue.read { db in -/// let urls: NullableDatabaseValueCursor = try Optional.fetchCursor(db, "SELECT url FROM links") +/// let urls: NullableDatabaseValueCursor = try Optional.fetchCursor(db, "SELECT url FROM link") /// while let url = urls.next() { // URL? /// print(url) /// } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index a9d308d30..d60a88c93 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -73,12 +73,12 @@ public protocol DatabaseWriter : DatabaseReader { /// For example: /// /// try writer.write { db in - /// try db.execute("DELETE FROM players") + /// try db.execute("DELETE FROM player") /// try writer.readFromCurrentState { db in /// // Guaranteed to be zero - /// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")! + /// try Int.fetchOne(db, "SELECT COUNT(*) FROM player")! /// } - /// try db.execute("INSERT INTO players ...") + /// try db.execute("INSERT INTO player ...") /// } func readFromCurrentState(_ block: @escaping (Database) -> Void) throws } diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index d17185743..cd03312c3 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -73,23 +73,6 @@ public protocol FetchRequest: SelectStatementRequest { } extension FetchRequest { - /// Returns a request bound to type T. - /// - /// The returned request can fetch if the type T is fetchable (Row, - /// value, record). - /// - /// // Int? - /// let maxScore = Player - /// .select(max(scoreColumn)) - /// .asRequest(of: Int.self) // <-- - /// .fetchOne(db) - /// - /// - parameter type: The fetched type T - /// - returns: A typed request bound to type T. - public func asRequest(of type: T.Type) -> AnyFetchRequest { - return AnyFetchRequest(self) - } - /// Returns an adapted request. public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { return AdaptedFetchRequest(self, adapter) @@ -202,8 +185,8 @@ public struct SQLRequest : FetchRequest { /// Creates a request from an SQL string, optional arguments, and /// optional row adapter. /// - /// let request = SQLRequest("SELECT * FROM players") - /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) + /// let request = SQLRequest("SELECT * FROM player") + /// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1]) /// /// - parameters: /// - sql: An SQL query. @@ -232,8 +215,8 @@ public struct SQLRequest : FetchRequest { /// Creates an SQL request from an SQL string, optional arguments, and /// optional row adapter. /// - /// let request = SQLRequest("SELECT * FROM players") - /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) + /// let request = SQLRequest("SELECT * FROM player") + /// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1]) /// /// - parameters: /// - sql: An SQL query. diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 242637cd5..5c385ec99 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -583,7 +583,7 @@ extension Row { /// A cursor of database rows. For example: /// /// try dbQueue.read { db in -/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM players") +/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM player") /// } public final class RowCursor : Cursor { public let statement: SelectStatement @@ -690,7 +690,7 @@ extension Row { /// Returns a cursor over rows fetched from an SQL query. /// - /// let rows = try Row.fetchCursor(db, "SELECT id, name FROM players") // RowCursor + /// let rows = try Row.fetchCursor(db, "SELECT id, name FROM player") // RowCursor /// while let row = try rows.next() { // Row /// let id: Int64 = row[0] /// let name: String = row[1] diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 482def1cd..092b3e623 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -289,7 +289,7 @@ extension AuthorizedStatement { /// You create SelectStatement with the Database.makeSelectStatement() method: /// /// try dbQueue.read { db in -/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?") +/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?") /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! /// } @@ -375,7 +375,7 @@ extension SelectStatement: AuthorizedStatement { } /// For example: /// /// try dbQueue.read { db in -/// let statement = db.makeSelectStatement("SELECT * FROM players") +/// let statement = db.makeSelectStatement("SELECT * FROM player") /// let cursor: StatementCursor = statement.cursor() /// } public final class StatementCursor: Cursor { @@ -414,7 +414,7 @@ public final class StatementCursor: Cursor { /// You create UpdateStatement with the Database.makeUpdateStatement() method: /// /// try dbQueue.inTransaction { db in -/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)") +/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)") /// try statement.execute(arguments: ["Arthur"]) /// try statement.execute(arguments: ["Barbara"]) /// return .commit @@ -588,8 +588,8 @@ extension UpdateStatement: AuthorizedStatement { } /// print(row) /// // Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"] public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral { - var values: [DatabaseValue] = [] - var namedValues: [String: DatabaseValue] = [:] + private(set) var values: [DatabaseValue] = [] + private(set) var namedValues: [String: DatabaseValue] = [:] public var isEmpty: Bool { return values.isEmpty && namedValues.isEmpty @@ -905,18 +905,6 @@ extension StatementArguments { } } -#if !swift(>=4.1) -// Equatable -extension StatementArguments { - /// :nodoc: - public static func == (lhs: StatementArguments, rhs: StatementArguments) -> Bool { - if lhs.values != rhs.values { return false } - if lhs.namedValues != rhs.namedValues { return false } - return true - } -} -#endif - /// A thread-unsafe statement cache struct StatementCache { unowned let db: Database diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 2a1dc14e7..fa7ef5446 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -75,7 +75,7 @@ extension StatementColumnConvertible { /// For example: /// /// try dbQueue.read { db in -/// let names: ColumnCursor = try String.fetchCursor(db, "SELECT name FROM players") +/// let names: ColumnCursor = try String.fetchCursor(db, "SELECT name FROM player") /// while let name = names.next() { // String /// print(name) /// } @@ -121,7 +121,7 @@ public final class ColumnCursor = try Optional.fetchCursor(db, "SELECT email FROM players") +/// let emails: NullableColumnCursor = try Optional.fetchCursor(db, "SELECT email FROM player") /// while let email = emails.next() { // String? /// print(email ?? "") /// } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index f27921111..0b50b9f80 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -29,13 +29,12 @@ extension Database { /// Registers a closure to be executed after the next or current /// transaction completion. /// - /// dbQueue.inTransaction { db in + /// try dbQueue.write { db in /// db.afterNextTransactionCommit { _ in - /// print("commit did succeed") + /// print("success") /// } /// ... - /// return .commit // prints "commit did succeed" - /// } + /// } // prints "success" /// /// If the transaction is rollbacked, the closure is not executed. /// @@ -100,11 +99,11 @@ extension Database { /// /// Then a statement is executed: /// -/// try db.execute("INSERT INTO documents ...") +/// try db.execute("INSERT INTO document ...") /// /// The observation process starts when the statement is *compiled*: /// sqlite3_set_authorizer tells that the statement performs insertion into the -/// `documents` table. Generally speaking, statements may have many effects, by +/// `document` table. Generally speaking, statements may have many effects, by /// the mean of foreign key actions and SQL triggers. SQLite takes care of /// exposing all those effects to sqlite3_set_authorizer. /// @@ -129,7 +128,7 @@ extension Database { /// /// Then another statement is executed: /// -/// try db.execute("INSERT INTO documents ...") +/// try db.execute("INSERT INTO document ...") /// /// This time, when the statement is *executed* and SQLite tells that a row has /// been inserted, the broker buffers the change event instead of immediately @@ -738,14 +737,14 @@ extension TransactionObserver { /// For example: /// /// class PlayerObserver: TransactionObserver { - /// var playersTableWasModified = false + /// var playerTableWasModified = false /// /// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - /// return eventKind.tableName == "players" + /// return eventKind.tableName == "player" /// } /// /// func databaseDidChange(with event: DatabaseEvent) { - /// playersTableWasModified = true + /// playerTableWasModified = true /// /// // It is pointless to keep on tracking further changes: /// stopObservingDatabaseChangesUntilNextTransaction() diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index 6e2e06ff8..5098d5967 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -1,15 +1,15 @@ /// FTS3 lets you define "fts3" virtual tables. /// -/// // CREATE VIRTUAL TABLE documents USING fts3(content) -/// try db.create(virtualTable: "documents", using: FTS3()) { t in +/// // CREATE VIRTUAL TABLE document USING fts3(content) +/// try db.create(virtualTable: "document", using: FTS3()) { t in /// t.column("content") /// } public struct FTS3 : VirtualTableModule { /// Creates a FTS3 module suitable for the Database /// `create(virtualTable:using:)` method. /// - /// // CREATE VIRTUAL TABLE documents USING fts3(content) - /// try db.create(virtualTable: "documents", using: FTS3()) { t in + /// // CREATE VIRTUAL TABLE document USING fts3(content) + /// try db.create(virtualTable: "document", using: FTS3()) { t in /// t.column("content") /// } public init() { @@ -54,7 +54,7 @@ public struct FTS3 : VirtualTableModule { /// You don't create instances of this class. Instead, you use the Database /// `create(virtualTable:using:)` method: /// -/// try db.create(virtualTable: "documents", using: FTS3()) { t in // t is FTS3TableDefinition +/// try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition /// t.column("content") /// } public final class FTS3TableDefinition { @@ -62,7 +62,7 @@ public final class FTS3TableDefinition { /// The virtual table tokenizer /// - /// try db.create(virtualTable: "documents", using: FTS3()) { t in + /// try db.create(virtualTable: "document", using: FTS3()) { t in /// t.tokenizer = .porter /// } /// See https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables @@ -70,7 +70,7 @@ public final class FTS3TableDefinition { /// Appends a table column. /// - /// try db.create(virtualTable: "documents", using: FTS3()) { t in + /// try db.create(virtualTable: "document", using: FTS3()) { t in /// t.column("content") /// } /// diff --git a/GRDB/FTS/FTS3TokenizerDescriptor.swift b/GRDB/FTS/FTS3TokenizerDescriptor.swift index d4387dd07..24ce4fff9 100644 --- a/GRDB/FTS/FTS3TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS3TokenizerDescriptor.swift @@ -1,6 +1,6 @@ /// An FTS3 tokenizer, suitable for FTS3 and FTS4 table definitions: /// -/// db.create(virtualTable: "books", using: FTS4()) { t in +/// db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .simple // FTS3TokenizerDescriptor /// } /// @@ -16,7 +16,7 @@ public struct FTS3TokenizerDescriptor { /// The "simple" tokenizer. /// - /// db.create(virtualTable: "books", using: FTS4()) { t in + /// db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .simple /// } /// @@ -25,7 +25,7 @@ public struct FTS3TokenizerDescriptor { /// The "porter" tokenizer. /// - /// db.create(virtualTable: "books", using: FTS4()) { t in + /// db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .porter /// } /// @@ -35,7 +35,7 @@ public struct FTS3TokenizerDescriptor { #if GRDBCUSTOMSQLITE || GRDBCIPHER /// The "unicode61" tokenizer. /// - /// db.create(virtualTable: "books", using: FTS4()) { t in + /// db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .unicode61() /// } /// @@ -54,7 +54,7 @@ public struct FTS3TokenizerDescriptor { #else /// The "unicode61" tokenizer. /// - /// db.create(virtualTable: "books", using: FTS4()) { t in + /// db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .unicode61() /// } /// diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index 7fea3dc75..fded83706 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -1,7 +1,7 @@ /// FTS4 lets you define "fts4" virtual tables. /// -/// // CREATE VIRTUAL TABLE documents USING fts4(content) -/// try db.create(virtualTable: "documents", using: FTS4()) { t in +/// // CREATE VIRTUAL TABLE document USING fts4(content) +/// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("content") /// } /// @@ -11,8 +11,8 @@ public struct FTS4 : VirtualTableModule { /// Creates a FTS4 module suitable for the Database /// `create(virtualTable:using:)` method. /// - /// // CREATE VIRTUAL TABLE documents USING fts4(content) - /// try db.create(virtualTable: "documents", using: FTS4()) { t in + /// // CREATE VIRTUAL TABLE document USING fts4(content) + /// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("content") /// } /// @@ -137,7 +137,7 @@ public struct FTS4 : VirtualTableModule { /// You don't create instances of this class. Instead, you use the Database /// `create(virtualTable:using:)` method: /// -/// try db.create(virtualTable: "documents", using: FTS4()) { t in // t is FTS4TableDefinition +/// try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition /// t.column("content") /// } /// @@ -153,7 +153,7 @@ public final class FTS4TableDefinition { /// The virtual table tokenizer /// - /// try db.create(virtualTable: "documents", using: FTS4()) { t in + /// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.tokenizer = .porter /// } /// @@ -201,8 +201,8 @@ public final class FTS4TableDefinition { /// Support for the FTS5 `prefix` option /// - /// // CREATE VIRTUAL TABLE documents USING FTS4(content, prefix='2 4'); - /// db.create(virtualTable: "documents", using:FTS4()) { t in + /// // CREATE VIRTUAL TABLE document USING FTS4(content, prefix='2 4'); + /// db.create(virtualTable: "document", using:FTS4()) { t in /// t.prefixes = [2, 4] /// t.column("content") /// } @@ -212,7 +212,7 @@ public final class FTS4TableDefinition { /// Appends a table column. /// - /// try db.create(virtualTable: "documents", using: FTS4()) { t in + /// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("content") /// } /// @@ -242,7 +242,7 @@ public final class FTS4TableDefinition { /// /// You get instances of this class when you create an FTS4 table: /// -/// try db.create(virtualTable: "documents", using: FTS4()) { t in +/// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("content") // FTS4ColumnDefinition /// } /// @@ -261,7 +261,7 @@ public final class FTS4ColumnDefinition { #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Excludes the column from the full-text index. /// - /// try db.create(virtualTable: "documents", using: FTS4()) { t in + /// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("a") /// t.column("b").notIndexed() /// } @@ -280,7 +280,7 @@ public final class FTS4ColumnDefinition { #else /// Excludes the column from the full-text index. /// - /// try db.create(virtualTable: "documents", using: FTS4()) { t in + /// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("a") /// t.column("b").notIndexed() /// } @@ -300,7 +300,7 @@ public final class FTS4ColumnDefinition { /// Uses the column as the Int32 language id hidden column. /// - /// try db.create(virtualTable: "documents", using: FTS4()) { t in + /// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("a") /// t.column("lid").asLanguageId() /// } diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 5dcf53824..2af8a6da0 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -1,8 +1,8 @@ #if SQLITE_ENABLE_FTS5 /// FTS5 lets you define "fts5" virtual tables. /// - /// // CREATE VIRTUAL TABLE documents USING fts5(content) - /// try db.create(virtualTable: "documents", using: FTS5()) { t in + /// // CREATE VIRTUAL TABLE document USING fts5(content) + /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") /// } /// @@ -12,8 +12,8 @@ /// Creates a FTS5 module suitable for the Database /// `create(virtualTable:using:)` method. /// - /// // CREATE VIRTUAL TABLE documents USING fts5(content) - /// try db.create(virtualTable: "documents", using: FTS5()) { t in + /// // CREATE VIRTUAL TABLE document USING fts5(content) + /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") /// } /// @@ -156,7 +156,7 @@ /// You don't create instances of this class. Instead, you use the Database /// `create(virtualTable:using:)` method: /// - /// try db.create(virtualTable: "documents", using: FTS5()) { t in // t is FTS5TableDefinition + /// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition /// t.column("content") /// } /// @@ -172,7 +172,7 @@ /// The virtual table tokenizer /// - /// try db.create(virtualTable: "documents", using: FTS5()) { t in + /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.tokenizer = .porter() /// } /// @@ -254,7 +254,7 @@ /// Appends a table column. /// - /// try db.create(virtualTable: "documents", using: FTS5()) { t in + /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") /// } /// @@ -284,7 +284,7 @@ /// /// You get instances of this class when you create an FTS5 table: /// - /// try db.create(virtualTable: "documents", using: FTS5()) { t in + /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") // FTS5ColumnDefinition /// } /// @@ -300,7 +300,7 @@ /// Excludes the column from the full-text index. /// - /// try db.create(virtualTable: "documents", using: FTS5()) { t in + /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("a") /// t.column("b").notIndexed() /// } diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index eea47f9bb..fb604300b 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -11,7 +11,7 @@ /// VIRTUAL TABLE statement. In the example below, the arguments will /// be `["arg1", "arg2"]`. /// - /// CREATE VIRTUAL TABLE documents USING fts5( + /// CREATE VIRTUAL TABLE document USING fts5( /// tokenize='custom arg1 arg2' /// ) /// @@ -26,7 +26,7 @@ /// /// class MyTokenizer : FTS5CustomTokenizer { ... } /// - /// db.create(virtualTable: "books", using: FTS5()) { t in + /// db.create(virtualTable: "book", using: FTS5()) { t in /// let tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ["unicode61", "remove_diacritics", "0"]) /// t.tokenizer = tokenizer /// } diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index 1e7231990..ca94574c6 100644 --- a/GRDB/FTS/FTS5Pattern.swift +++ b/GRDB/FTS/FTS5Pattern.swift @@ -65,7 +65,7 @@ // that pattern. do { try DatabaseQueue().inDatabase { db in - try db.create(virtualTable: "documents", using: FTS5()) { t in + try db.create(virtualTable: "document", using: FTS5()) { t in if allowedColumns.isEmpty { t.column("__grdb__") } else { @@ -74,7 +74,7 @@ } } } - try db.makeSelectStatement("SELECT * FROM documents WHERE documents MATCH ?") + try db.makeSelectStatement("SELECT * FROM document WHERE document MATCH ?") .cursor(arguments: [rawPattern]) .next() // error on next() for invalid patterns } @@ -97,8 +97,8 @@ /// /// The pattern syntax is documented at https://www.sqlite.org/fts5.html#full_text_query_syntax /// - /// try db.makeFTS5Pattern(rawPattern: "and", forTable: "documents") // OK - /// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "documents") // malformed MATCH expression: [AND] + /// try db.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK + /// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND] public func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern { return try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map { $0.name }) } diff --git a/GRDB/FTS/FTS5TokenizerDescriptor.swift b/GRDB/FTS/FTS5TokenizerDescriptor.swift index 9752d9dd0..95c0e0431 100644 --- a/GRDB/FTS/FTS5TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS5TokenizerDescriptor.swift @@ -1,7 +1,7 @@ #if SQLITE_ENABLE_FTS5 /// An FTS5 tokenizer, suitable for FTS5 table definitions: /// - /// db.create(virtualTable: "books", using: FTS5()) { t in + /// db.create(virtualTable: "book", using: FTS5()) { t in /// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor /// } /// @@ -33,7 +33,7 @@ /// Creates an FTS5 tokenizer descriptor. /// - /// db.create(virtualTable: "books", using: FTS5()) { t in + /// db.create(virtualTable: "book", using: FTS5()) { t in /// let tokenizer = FTS5TokenizerDescriptor(components: ["porter", "unicode61", "remove_diacritics", "0"]) /// t.tokenizer = tokenizer /// } @@ -47,7 +47,7 @@ /// The "ascii" tokenizer /// - /// db.create(virtualTable: "books", using: FTS5()) { t in + /// db.create(virtualTable: "book", using: FTS5()) { t in /// t.tokenizer = .ascii() /// } /// @@ -66,7 +66,7 @@ /// The "porter" tokenizer /// - /// db.create(virtualTable: "books", using: FTS5()) { t in + /// db.create(virtualTable: "book", using: FTS5()) { t in /// t.tokenizer = .porter() /// } /// @@ -85,7 +85,7 @@ /// An "unicode61" tokenizer /// - /// db.create(virtualTable: "books", using: FTS5()) { t in + /// db.create(virtualTable: "book", using: FTS5()) { t in /// t.tokenizer = .unicode61() /// } /// diff --git a/GRDB/Legacy/Fixits-0.109.0.swift b/GRDB/Legacy/Fixits-0.109.0.swift index 6c2034ea6..1b9dcc727 100644 --- a/GRDB/Legacy/Fixits-0.109.0.swift +++ b/GRDB/Legacy/Fixits-0.109.0.swift @@ -1,4 +1,4 @@ extension FetchRequest { - @available(*, unavailable, renamed:"asRequest(of:)") + @available(*, unavailable, message:"Use QueryInterfaceRequest.asRequest(of:), or AnyFetchRequest") public func bound(to type: T.Type) -> AnyFetchRequest { preconditionFailure() } } diff --git a/GRDB/Legacy/Fixits-3.0.swift b/GRDB/Legacy/Fixits-3.0.swift index b1730ba26..78f41549f 100644 --- a/GRDB/Legacy/Fixits-3.0.swift +++ b/GRDB/Legacy/Fixits-3.0.swift @@ -18,6 +18,10 @@ public typealias MutablePersistable = MutablePersistableRecord @available(*, unavailable, renamed:"PersistableRecord") public typealias Persistable = PersistableRecord +/// :nodoc: +@available(*, unavailable, renamed:"TableAlias") +public typealias SQLTableQualifier = TableAlias + extension Database { /// :nodoc: @available(*, unavailable, message: "Use db.columns(in: tableName).count instead") diff --git a/GRDB/Legacy/Swift4.1.swift b/GRDB/Legacy/Swift4.1.swift deleted file mode 100644 index c1adaac2f..000000000 --- a/GRDB/Legacy/Swift4.1.swift +++ /dev/null @@ -1,24 +0,0 @@ -// Compatibility layer for Swift < 4.1 - -#if !swift(>=4.1) -extension Sequence { - // From future import SE-0187 - func compactMap(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] { - return try flatMap(transform) - } -} - -extension UnsafeMutablePointer { - // From future import SE-0184 - func deallocate() { - deallocate(capacity: 0) - } -} - -extension UnsafeMutableRawBufferPointer { - // From future import SE-0184 - func copyMemory(from source: C) where C : Collection, C.Element == UInt8 { - copyBytes(from: source) - } -} -#endif diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 7e8ba9b1a..00f0100ab 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -9,34 +9,37 @@ /// /// var migrator = DatabaseMigrator() /// -/// // v1.0 database -/// migrator.registerMigration("createAuthors") { db in -/// try db.execute(""" -/// CREATE TABLE authors ( -/// id INTEGER PRIMARY KEY, -/// creationDate TEXT, -/// name TEXT NOT NULL -/// ) -/// """) +/// // 1st migration +/// migrator.registerMigration("createLibrary") { db in +/// try db.create(table: "author") { t in +/// t.autoIncrementedPrimaryKey("id") +/// t.column("creationDate", .datetime) +/// t.column("name", .text).notNull() +/// } +/// +/// try db.create(table: "book") { t in +/// t.autoIncrementedPrimaryKey("id") +/// t.column("authorId", .integer) +/// .notNull() +/// .references("author", onDelete: .cascade) +/// t.column("title", .text).notNull() +/// } /// } /// -/// migrator.registerMigration("createBooks") { db in -/// try db.execute(""" -/// CREATE TABLE books ( -/// uuid TEXT PRIMARY KEY, -/// authorID INTEGER NOT NULL -/// REFERENCES authors(id) -/// ON DELETE CASCADE ON UPDATE CASCADE, -/// title TEXT NOT NULL -/// ) -/// """) -/// } -/// -/// // v2.0 database +/// // 2nd migration /// migrator.registerMigration("AddBirthYearToAuthors") { db in -/// try db.execute("ALTER TABLE authors ADD COLUMN birthYear INT") +/// try db.alter(table: "author") { t +/// t.add(column: "birthYear", .integer) +/// } /// } /// +/// // Migrations for future versions will be inserted here: +/// // +/// // // 3rd migration +/// // migrator.registerMigration("...") { db in +/// // ... +/// // } +/// /// try migrator.migrate(dbQueue) public struct DatabaseMigrator { @@ -46,14 +49,12 @@ public struct DatabaseMigrator { /// Registers a migration. /// - /// migrator.registerMigration("createPlayers") { db in - /// try db.execute(""" - /// CREATE TABLE players ( - /// id INTEGER PRIMARY KEY, - /// creationDate TEXT, - /// name TEXT NOT NULL - /// ) - /// """) + /// migrator.registerMigration("createAuthors") { db in + /// try db.create(table: "author") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("creationDate", .datetime) + /// t.column("name", .text).notNull() + /// } /// } /// /// - parameters: @@ -69,12 +70,13 @@ public struct DatabaseMigrator { /// /// // Add a NOT NULL constraint on players.name: /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - /// try db.execute(""" - /// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL); - /// INSERT INTO new_players SELECT * FROM players; - /// DROP TABLE players; - /// ALTER TABLE new_players RENAME TO players; - /// """) + /// try db.create(table: "new_player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("name", .text).notNull() + /// } + /// try db.execute("INSERT INTO new_player SELECT * FROM player") + /// try db.drop(table: "player") + /// try db.rename(table: "new_player", to: "player") /// } /// /// While your migration code runs with disabled foreign key checks, those @@ -96,12 +98,13 @@ public struct DatabaseMigrator { /// /// // Add a NOT NULL constraint on players.name: /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - /// try db.execute(""" - /// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL); - /// INSERT INTO new_players SELECT * FROM players; - /// DROP TABLE players; - /// ALTER TABLE new_players RENAME TO players; - /// """) + /// try db.create(table: "new_player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("name", .text).notNull() + /// } + /// try db.execute("INSERT INTO new_player SELECT * FROM player") + /// try db.drop(table: "player") + /// try db.rename(table: "new_player", to: "player") /// } /// /// While your migration code runs with disabled foreign key checks, those diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift new file mode 100644 index 000000000..8023699f2 --- /dev/null +++ b/GRDB/QueryInterface/Association/Association.swift @@ -0,0 +1,298 @@ +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// The base protocol for all associations that define a connection between two +/// record types. +public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { + associatedtype LeftAssociated + associatedtype RightAssociated + + /// The association key defines how rows fetched from this association + /// should be consumed. + /// + /// For example: + /// + /// struct Player: TableRecord { + /// // The default key of this association is the name of the + /// // database table for teams, let's say "team": + /// static let team = belongsTo(Team.self) + /// } + /// print(Player.team.key) // Prints "team" + /// + /// // Consume rows: + /// let request = Player.including(required: Player.team) + /// for row in Row.fetchAll(db, request) { + /// let team: Team = row["team"] // the association key + /// } + /// + /// The key can be redefined with the `forKey` method: + /// + /// let request = Player.including(required: Player.team.forKey("custom")) + /// for row in Row.fetchAll(db, request) { + /// let team: Team = row["custom"] + /// } + var key: String { get } + + /// Creates an association with the given key. + /// + /// This new key impacts how rows fetched from the resulting association + /// should be consumed: + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // Consume rows: + /// let request = Player.including(required: Player.team.forKey("custom")) + /// for row in Row.fetchAll(db, request) { + /// let team: Team = row["custom"] + /// } + func forKey(_ key: String) -> Self + + // TODO: this one prevents "through" associations like HasOneThrough, HasManyThrough, etc. + /// :nodoc: + var request: AssociationRequest { get } + + // TODO: this one prevents "through" associations like HasOneThrough, HasManyThrough, etc. + /// :nodoc: + func joinCondition(_ db: Database) throws -> JoinCondition + + /// :nodoc: + func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> Self +} + +extension Association { + /// Creates an association with a new net of selected columns. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.color + /// // FROM player + /// // JOIN team ON team.id = player.teamId + /// let association = Player.team.select([Column("color")]) + /// var request = Player.including(required: association) + /// + /// Any previous selection is replaced: + /// + /// // SELECT player.*, team.color + /// // FROM player + /// // JOIN team ON team.id = player.teamId + /// let association = Player.team + /// .select([Column("id")]) + /// .select([Column("color")]) + /// var request = Player.including(required: association) + public func select(_ selection: [SQLSelectable]) -> Self { + return mapRequest { $0.select(selection) } + } + + /// Creates an association with the provided *predicate promise* added to + /// the eventual set of already applied predicates. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamId AND 1 + /// let association = Player.team.filter { db in true } + /// var request = Player.including(required: association) + public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { + return mapRequest { $0.filter(predicate) } + } + + /// Creates an association with the provided *orderings*. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamId + /// // ORDER BY team.name + /// let association = Player.team.order(Column("name")) + /// var request = Player.including(required: association) + /// + /// Any previous ordering is replaced: + /// + /// // SELECT player.*, team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamId + /// // ORDER BY team.name + /// let association = Player.team + /// .order(Column("color")) + /// .reversed() + /// .order(Column("name")) + /// var request = Player.including(required: association) + public func order(_ orderings: [SQLOrderingTerm]) -> Self { + return mapRequest { $0.order(orderings) } + } + + /// Creates an association that reverses applied orderings. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamId + /// // ORDER BY team.name DESC + /// let association = Player.team.order(Column("name")).reversed() + /// var request = Player.including(required: association) + /// + /// If no ordering was applied, the returned association is identical. + /// + /// // SELECT player.*, team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamId + /// let association = Player.team.reversed() + /// var request = Player.including(required: association) + public func reversed() -> Self { + return mapRequest { $0.reversed() } + } + + /// Creates an association with the given key. + /// + /// This new key helps Decodable records decode rows fetched from the + /// resulting association: + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// struct PlayerInfo: FetchableRecord, Decodable { + /// let player: Player + /// let team: Team + /// + /// static func all() -> QueryInterfaceRequest { + /// return Player + /// .including(required: Player.team.forKey(CodingKeys.team)) + /// .asRequest(of: PlayerInfo.self) + /// } + /// } + /// + /// let playerInfos = PlayerInfo.all().fetchAll(db) + /// print(playerInfos.first?.team) + public func forKey(_ codingKey: CodingKey) -> Self { + return forKey(codingKey.stringValue) + } + + /// Creates an association that allows you to define expressions that target + /// a specific database table. + /// + /// In the example below, the "team.color = 'red'" condition in the where + /// clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... + /// // WHERE team.color = 'red' + /// let teamAlias = TableAlias() + /// let request = Player + /// .including(required: Player.team.aliased(teamAlias)) + /// .filter(teamAlias[Column("color")] == "red") + /// + /// When you give a name to a table alias, you can reliably inject sql + /// snippets in your requests: + /// + /// // SELECT player.*, custom.* + /// // JOIN team custom ON ... + /// // WHERE custom.color = 'red' + /// let teamAlias = TableAlias(name: "custom") + /// let request = Player + /// .including(required: Player.team.aliased(teamAlias)) + /// .filter(sql: "custom.color = ?", arguments: ["red"]) + public func aliased(_ alias: TableAlias) -> Self { + return mapRequest { $0.aliased(alias) } + } +} + +public typealias JoinCondition = (_ leftAlias: TableAlias, _ rightAlias: TableAlias) -> SQLExpression? + +/// Turns a ForeignKeyRequest into a JoinCondition +struct ForeignKeyJoinConditionRequest { + var foreignKeyRequest: ForeignKeyRequest + var originIsLeft: Bool + + func fetch(_ db: Database) throws -> JoinCondition { + let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping + let columnMapping: [(left: Column, right: Column)] + if originIsLeft { + columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } + } else { + columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } + } + return { (leftAlias, rightAlias) in + return columnMapping + .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } + .joined(operator: .and) + } + } +} + +extension Association { + /// Creates an association that includes another one. The columns of the + /// associated record are selected. The returned association does not + /// require that the associated database table contains a matching row. + public func including(optional association: A) -> Self where A.LeftAssociated == RightAssociated { + return mapRequest { $0.joining(.optional, association) } + } + + /// Creates an association that includes another one. The columns of the + /// associated record are selected. The returned association requires + /// that the associated database table contains a matching row. + public func including(required association: A) -> Self where A.LeftAssociated == RightAssociated { + return mapRequest { $0.joining(.required, association) } + } + + /// Creates an association that joins another one. The columns of the + /// associated record are not selected. The returned association does not + /// require that the associated database table contains a matching row. + public func joining(optional association: A) -> Self where A.LeftAssociated == RightAssociated { + return mapRequest { $0.joining(.optional, association.select([])) } + } + + /// Creates an association that joins another one. The columns of the + /// associated record are not selected. The returned association requires + /// that the associated database table contains a matching row. + public func joining(required association: A) -> Self where A.LeftAssociated == RightAssociated { + return mapRequest { $0.joining(.required, association.select([])) } + } +} + +extension Association where LeftAssociated: MutablePersistableRecord { + /// Support for MutablePersistableRecord.request(for:). + /// + /// For example: + /// + /// struct Team: { + /// static let players = hasMany(Player.self) + /// var players: QueryInterfaceRequest { + /// return request(for: Team.players) + /// } + /// } + /// + /// let team: Team = ... + /// let players = try team.players.fetchAll(db) // [Player] + func request(from record: LeftAssociated) -> QueryInterfaceRequest { + // Turn `JOIN associated ON associated.recordId = record.id` + // into `FROM associated WHERE associated.recordId = 1` + let associationAlias = TableAlias() + let recordAlias = TableAlias(tableName: LeftAssociated.databaseTableName) + return QueryInterfaceRequest(request) + .aliased(associationAlias) + .filter { db in + guard let joinCondition = try self.joinCondition(db)(recordAlias, associationAlias) else { + fatalError("Can't request from record without join condition") + } + let container = PersistenceContainer(record) // support for record classes: late construction of container + return joinCondition.resolvedExpression(inContext: [recordAlias: container]) + } + } +} diff --git a/GRDB/QueryInterface/Association/AssociationQuery.swift b/GRDB/QueryInterface/Association/AssociationQuery.swift new file mode 100644 index 000000000..a89a25361 --- /dev/null +++ b/GRDB/QueryInterface/Association/AssociationQuery.swift @@ -0,0 +1,138 @@ +struct AssociationQuery { + var source: SQLSource + var selection: [SQLSelectable] + var filterPromise: DatabasePromise + var ordering: QueryOrdering + var joins: [AssociationJoin] + + var alias: TableAlias? { + return source.alias + } +} + +extension AssociationQuery { + init(_ query: QueryInterfaceQuery) { + GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries") + GRDBPrecondition(query.groupByExpressions.isEmpty, "Can't join aggregated queries") + GRDBPrecondition(query.havingExpression == nil, "Can't join aggregated queries") + GRDBPrecondition(query.limit == nil, "Can't join limited queries") + + self.init( + source: query.source, + selection: query.selection, + filterPromise: query.filterPromise, + ordering: query.ordering, + joins: query.joins) + } +} + +extension AssociationQuery { + func select(_ selection: [SQLSelectable]) -> AssociationQuery { + var query = self + query.selection = selection + return query + } + + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> AssociationQuery { + var query = self + query.filterPromise = query.filterPromise.map { (db, filter) in + if let filter = filter { + return try filter && predicate(db) + } else { + return try predicate(db).sqlExpression + } + } + return query + } + + func order(_ orderings: [SQLOrderingTerm]) -> AssociationQuery { + return order(QueryOrdering(orderings: orderings)) + } + + func reversed() -> AssociationQuery { + return order(ordering.reversed) + } + + private func order(_ ordering: QueryOrdering) -> AssociationQuery { + var query = self + query.ordering = ordering + return query + } + + func joining(_ join: AssociationJoin) -> AssociationQuery { + var query = self + query.joins.append(join) + return query + } + + func qualified(with alias: TableAlias) -> AssociationQuery { + var query = self + query.source = source.qualified(with: alias) + return query + } +} + +extension AssociationQuery { + /// A finalized query is ready for SQL generation + var finalizedQuery: AssociationQuery { + var query = self + + let alias = TableAlias() + query.source = source.qualified(with: alias) + query.selection = selection.map { $0.qualifiedSelectable(with: alias) } + query.filterPromise = filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } + query.ordering = ordering.qualified(with: alias) + query.joins = joins.map { $0.finalizedJoin } + + return query + } + + /// precondition: self is the result of finalizedQuery + var finalizedAliases: [TableAlias] { + var aliases: [TableAlias] = [] + if let alias = alias { + aliases.append(alias) + } + return joins.reduce(into: aliases) { + $0.append(contentsOf: $1.finalizedAliases) + } + } + + /// precondition: self is the result of finalizedQuery + var finalizedSelection: [SQLSelectable] { + return joins.reduce(into: selection) { + $0.append(contentsOf: $1.finalizedSelection) + } + } + + /// precondition: self is the result of finalizedQuery + var finalizedOrdering: QueryOrdering { + return joins.reduce(ordering) { + $0.appending($1.finalizedOrdering) + } + } + + /// precondition: self is the result of finalizedQuery + func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { + let selectionWidth = try selection + .map { try $0.columnCount(db) } + .reduce(0, +) + + var endIndex = startIndex + selectionWidth + var scopes: [String: RowAdapter] = [:] + for join in joins { + if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [join.key]) { + GRDBPrecondition(scopes[join.key] == nil, "The association key \"\((keyPath + [join.key]).joined(separator: "."))\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + scopes[join.key] = joinAdapter + endIndex = joinEndIndex + } + } + + if selectionWidth == 0 && scopes.isEmpty { + return nil + } + + let adapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) + return (adapter: adapter.addingScopes(scopes), endIndex: endIndex) + } +} diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift new file mode 100644 index 000000000..ba9f08ade --- /dev/null +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -0,0 +1,49 @@ +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// In `SELECT a.*, b.* FROM a JOIN b ON b.aid = a.id AND b.name = 'foo'`, +/// the AssociationRequest is (`b.*` + `b.name = 'foo'`). +public struct AssociationRequest { + let query: AssociationQuery + + init(query: AssociationQuery) { + self.query = query + } + + init(_ request: QueryInterfaceRequest) { + self.init(query: AssociationQuery(request.query)) + } +} + +extension AssociationRequest { + func select(_ selection: [SQLSelectable]) -> AssociationRequest { + return AssociationRequest(query: query.select(selection)) + } + + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> AssociationRequest { + return AssociationRequest(query: query.filter(predicate)) + } + + func order(_ orderings: [SQLOrderingTerm]) -> AssociationRequest { + return AssociationRequest(query: query.order(orderings)) + } + + func reversed() -> AssociationRequest { + return AssociationRequest(query: query.reversed()) + } + + func aliased(_ alias: TableAlias) -> AssociationRequest { + return AssociationRequest(query: query.qualified(with: alias)) + } + + func joining(_ joinOperator: AssociationJoinOperator, _ association: A) + -> AssociationRequest + where A.LeftAssociated == T + { + let join = AssociationJoin( + joinOperator: joinOperator, + query: association.request.query, + key: association.key, + joinConditionPromise: DatabasePromise(association.joinCondition)) + return AssociationRequest(query: query.joining(join)) + } +} diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift new file mode 100644 index 000000000..7a6623eaa --- /dev/null +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -0,0 +1,67 @@ +public struct BelongsToAssociation : Association, TableRequest where + Left: TableRecord, + Right: TableRecord +{ + public typealias LeftAssociated = Left + public typealias RightAssociated = Right + + public var key: String + + /// :nodoc: + public var databaseTableName: String { return RightAssociated.databaseTableName } + + /// :nodoc: + public var request: AssociationRequest + + let foreignKeyRequest: ForeignKeyRequest + + public func forKey(_ key: String) -> BelongsToAssociation { + var association = self + association.key = key + return association + } + + /// :nodoc: + public func joinCondition(_ db: Database) throws -> JoinCondition { + return try ForeignKeyJoinConditionRequest(foreignKeyRequest: foreignKeyRequest, originIsLeft: true).fetch(db) + } + + /// :nodoc: + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> BelongsToAssociation { + var association = self + association.request = transform(request) + return association + } +} + +extension TableRecord { + // TODO: Make it public if and only if we really want to build an association from any request + static func belongsTo( + _ rightRequest: QueryInterfaceRequest, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + where Right: TableRecord + { + let foreignKeyRequest = ForeignKeyRequest( + originTable: databaseTableName, + destinationTable: Right.databaseTableName, + foreignKey: foreignKey) + + return BelongsToAssociation( + key: key ?? Right.databaseTableName, + request: AssociationRequest(rightRequest), + foreignKeyRequest: foreignKeyRequest) + } + + /// TODO + public static func belongsTo( + _ right: Right.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + where Right: TableRecord + { + return belongsTo(Right.all(), key: key, using: foreignKey) + } +} diff --git a/GRDB/QueryInterface/Association/ForeignKey.swift b/GRDB/QueryInterface/Association/ForeignKey.swift new file mode 100644 index 000000000..c509202b7 --- /dev/null +++ b/GRDB/QueryInterface/Association/ForeignKey.swift @@ -0,0 +1,16 @@ +/// A Foreign Key that helps building associations. +public struct ForeignKey { + let originColumns: [String] + let destinationColumns: [String]? + + /// TODO + public init(_ originColumns: [String], to destinationColumns: [String]? = nil) { + self.originColumns = originColumns + self.destinationColumns = destinationColumns + } + + /// TODO + public init(_ originColumns: [Column], to destinationColumns: [Column]? = nil) { + self.init(originColumns.map { $0.name }, to: destinationColumns?.map { $0.name }) + } +} diff --git a/GRDB/QueryInterface/Association/ForeignKeyRequest.swift b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift new file mode 100644 index 000000000..014c07b8c --- /dev/null +++ b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift @@ -0,0 +1,85 @@ +/// ForeignKeyRequest looks for the foreign keys associations need to +/// join tables. +/// +/// Mappings come from foreign keys, when they exist in the database schema. +/// +/// When the schema does not define any foreign key, we can still infer complete +/// mappings from partial information and primary keys. +struct ForeignKeyRequest { + let originTable: String + let destinationTable: String + let originColumns: [String]? + let destinationColumns: [String]? + + init(originTable: String, destinationTable: String, foreignKey: ForeignKey?) { + self.originTable = originTable + self.destinationTable = destinationTable + + self.originColumns = foreignKey?.originColumns + self.destinationColumns = foreignKey?.destinationColumns + } + + func fetch(_ db: Database) throws -> ForeignKeyInfo { + if let originColumns = originColumns, let destinationColumns = destinationColumns { + // Total information: no need to query the database schema. + GRDBPrecondition(originColumns.count == destinationColumns.count, "Number of columns don't match") + let mapping = zip(originColumns, destinationColumns).map { + (origin: $0, destination: $1) + } + return ForeignKeyInfo(destinationTable: destinationTable, mapping: mapping) + } + + // Incomplete information: let's look for schema foreign keys + let foreignKeys = try db.foreignKeys(on: originTable).filter { foreignKey in + if destinationTable.lowercased() != foreignKey.destinationTable.lowercased() { + return false + } + if let originColumns = originColumns { + let originColumns = Set(originColumns.lazy.map { $0.lowercased() }) + let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.origin.lowercased() }) + if originColumns != foreignKeyColumns { + return false + } + } + // TODO: test + if let destinationColumns = destinationColumns { + let destinationColumns = Set(destinationColumns.lazy.map { $0.lowercased() }) + let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.destination.lowercased() }) + if destinationColumns != foreignKeyColumns { + return false + } + } + return true + } + + // Matching foreign key(s) found + if let foreignKey = foreignKeys.first { + if foreignKeys.count == 1 { + // Non-ambiguous + // TODO: test + return foreignKey + } else { + // Ambiguous: can't choose + fatalError("Ambiguous foreign key from \(originTable) to \(destinationTable)") + } + } + + // No matching foreign key found: use the destination primary key + if let originColumns = originColumns { + let destinationColumns = try db.primaryKey(destinationTable).columns + if (originColumns.count == destinationColumns.count) { + // TODO: test + let mapping = zip(originColumns, destinationColumns).map { + (origin: $0, destination: $1) + } + return ForeignKeyInfo(destinationTable: destinationTable, mapping: mapping) + } + } + + fatalError("Could not infer foreign key from \(originTable) to \(destinationTable)") + } +} + +/// The (origin, destination) column pairs that join a left table to a right table. +/// :nodoc: +typealias ForeignKeyMapping = [(origin: String, destination: String)] diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift new file mode 100644 index 000000000..4c9d88edf --- /dev/null +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -0,0 +1,67 @@ +public struct HasManyAssociation : Association, TableRequest where + Left: TableRecord, + Right: TableRecord +{ + public typealias LeftAssociated = Left + public typealias RightAssociated = Right + + public var key: String + + /// :nodoc: + public var databaseTableName: String { return RightAssociated.databaseTableName } + + /// :nodoc: + public var request: AssociationRequest + + let foreignKeyRequest: ForeignKeyRequest + + public func forKey(_ key: String) -> HasManyAssociation { + var association = self + association.key = key + return association + } + + /// :nodoc: + public func joinCondition(_ db: Database) throws -> JoinCondition { + return try ForeignKeyJoinConditionRequest(foreignKeyRequest: foreignKeyRequest, originIsLeft: false).fetch(db) + } + + /// :nodoc: + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasManyAssociation { + var association = self + association.request = transform(request) + return association + } +} + +extension TableRecord { + // TODO: Make it public if and only if we really want to build an association from any request + static func hasMany( + _ rightRequest: QueryInterfaceRequest, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + where Right: TableRecord + { + let foreignKeyRequest = ForeignKeyRequest( + originTable: Right.databaseTableName, + destinationTable: databaseTableName, + foreignKey: foreignKey) + + return HasManyAssociation( + key: key ?? Right.databaseTableName, + request: AssociationRequest(rightRequest), + foreignKeyRequest: foreignKeyRequest) + } + + /// TODO + public static func hasMany( + _ right: Right.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + where Right: TableRecord + { + return hasMany(Right.all(), key: key, using: foreignKey) + } +} diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift new file mode 100644 index 000000000..b3c70de9e --- /dev/null +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -0,0 +1,67 @@ +public struct HasOneAssociation : Association, TableRequest where + Left: TableRecord, + Right: TableRecord +{ + public typealias LeftAssociated = Left + public typealias RightAssociated = Right + + public var key: String + + /// :nodoc: + public var databaseTableName: String { return RightAssociated.databaseTableName } + + /// :nodoc: + public var request: AssociationRequest + + let foreignKeyRequest: ForeignKeyRequest + + public func forKey(_ key: String) -> HasOneAssociation { + var association = self + association.key = key + return association + } + + /// :nodoc: + public func joinCondition(_ db: Database) throws -> JoinCondition { + return try ForeignKeyJoinConditionRequest(foreignKeyRequest: foreignKeyRequest, originIsLeft: false).fetch(db) + } + + /// :nodoc: + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasOneAssociation { + var association = self + association.request = transform(request) + return association + } +} + +extension TableRecord { + // TODO: Make it public if and only if we really want to build an association from any request + static func hasOne( + _ rightRequest: QueryInterfaceRequest, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + where Right: TableRecord + { + let foreignKeyRequest = ForeignKeyRequest( + originTable: Right.databaseTableName, + destinationTable: databaseTableName, + foreignKey: foreignKey) + + return HasOneAssociation( + key: key ?? Right.databaseTableName, + request: AssociationRequest(rightRequest), + foreignKeyRequest: foreignKeyRequest) + } + + /// TODO + public static func hasOne( + _ right: Right.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + where Right: TableRecord + { + return hasOne(Right.all(), key: key, using: foreignKey) + } +} diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index cd6ecb5c0..5cfb79769 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -28,14 +28,20 @@ public protocol ColumnExpression: SQLExpression { extension ColumnExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { + public func expressionSQL(_ context: inout SQLGenerationContext) -> String { return name.quotedDatabaseIdentifier } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return QualifiedColumn(name, qualifier: qualifier) + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return QualifiedColumn(name, alias: alias) + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return self } } @@ -61,25 +67,35 @@ public struct Column: ColumnExpression { /// A qualified column in the database, as in `SELECT t.a FROM t` struct QualifiedColumn: ColumnExpression { var name: String - private let qualifier: SQLTableQualifier + private let alias: TableAlias /// Creates a column given its name. - init(_ name: String, qualifier: SQLTableQualifier) { + init(_ name: String, alias: TableAlias) { self.name = name - self.qualifier = qualifier + self.alias = alias } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - if let qualifierName = qualifier.name { - return qualifierName.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + if let qualifier = context.qualifier(for: alias) { + return qualifier.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier } return name.quotedDatabaseIdentifier } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { // Never requalify return self } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + guard + let container = context[alias.root], + let value = container.value(forCaseInsensitiveColumn: name) else + { + return self + } + return value + } } /// Support for column enums: diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index 171b12868..0c1d56aaa 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -5,20 +5,20 @@ extension QueryInterfaceRequest { /// Creates a request with a full-text predicate added to the eventual /// set of already applied predicates. /// - /// // SELECT * FROM books WHERE books MATCH '...' + /// // SELECT * FROM book WHERE book MATCH '...' /// var request = Book.all() /// request = request.matching(pattern) /// /// If the search pattern is nil, the request does not match any /// database row. public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest { - switch query.source { - case .table(let name, let alias)?: - return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern ?? DatabaseValue.null)) - default: - // Programmer error - fatalError("fts3 match requires a table") + guard let pattern = pattern else { + return none() } + let alias = TableAlias() + let qualifiedQuery = query.qualified(with: alias) + let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) + return QueryInterfaceRequest(query: qualifiedQuery).filter(matchExpression) } } @@ -28,7 +28,7 @@ extension TableRecord { /// Returns a QueryInterfaceRequest with a matching predicate. /// - /// // SELECT * FROM books WHERE books MATCH '...' + /// // SELECT * FROM book WHERE book MATCH '...' /// var request = Book.matching(pattern) /// /// If the search pattern is nil, the request does not match any diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index 0394a5450..2affcfe44 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -6,7 +6,7 @@ /// Creates a request with a full-text predicate added to the eventual /// set of already applied predicates. /// - /// // SELECT * FROM books WHERE books MATCH '...' + /// // SELECT * FROM book WHERE book MATCH '...' /// var request = Book.all() /// request = request.matching(pattern) /// @@ -17,17 +17,13 @@ /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { - switch query.source { - case .table(let name, let alias)?: - if let pattern = pattern { - return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern)) - } else { - return filter(false) - } - default: - // Programmer error - fatalError("fts5 match requires a table") + guard let pattern = pattern else { + return none() } + let alias = TableAlias() + let qualifiedQuery = query.qualified(with: alias) + let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) + return QueryInterfaceRequest(query: qualifiedQuery).filter(matchExpression) } } @@ -37,7 +33,7 @@ /// Returns a QueryInterfaceRequest with a matching predicate. /// - /// // SELECT * FROM books WHERE books MATCH '...' + /// // SELECT * FROM book WHERE book MATCH '...' /// var request = Book.matching(pattern) /// /// If the search pattern is nil, the request does not match any diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 2c3cfbec4..1eb8ec312 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -17,70 +17,240 @@ struct DatabasePromise { } struct QueryInterfaceQuery { + var source: SQLSource var selection: [SQLSelectable] var isDistinct: Bool - var source: SQLSource? - var wherePromise: DatabasePromise + var filterPromise: DatabasePromise var groupByExpressions: [SQLExpression] var ordering: QueryOrdering var havingExpression: SQLExpression? var limit: SQLLimit? + var joins: [AssociationJoin] init( - select selection: [SQLSelectable], + source: SQLSource, + selection: [SQLSelectable] = [], isDistinct: Bool = false, - from source: SQLSource? = nil, - filter whereExpression: SQLExpression? = nil, - groupBy groupByExpressions: [SQLExpression] = [], - orderBy ordering: QueryOrdering = QueryOrdering(), - having havingExpression: SQLExpression? = nil, - limit: SQLLimit? = nil) + filterPromise: DatabasePromise = DatabasePromise(value: nil), + groupByExpressions: [SQLExpression] = [], + ordering: QueryOrdering = QueryOrdering(), + havingExpression: SQLExpression? = nil, + limit: SQLLimit? = nil, + joins: [AssociationJoin] = []) { + self.source = source self.selection = selection self.isDistinct = isDistinct - self.source = source - self.wherePromise = DatabasePromise(value: whereExpression) + self.filterPromise = filterPromise self.groupByExpressions = groupByExpressions self.ordering = ordering self.havingExpression = havingExpression self.limit = limit + self.joins = joins } - func mapWhereExpression(_ transform: @escaping (Database, SQLExpression?) throws -> SQLExpression?) -> QueryInterfaceQuery { + init(_ query: AssociationQuery) { + self.init( + source: query.source, + selection: query.selection, + filterPromise: query.filterPromise, + ordering: query.ordering, + joins: query.joins) + } + + var alias: TableAlias? { + return source.alias + } +} + +extension QueryInterfaceQuery { + func select(_ selection: [SQLSelectable]) -> QueryInterfaceQuery { var query = self - query.wherePromise = query.wherePromise.map(transform) + query.selection = selection return query } - func sql(_ db: Database, _ arguments: inout StatementArguments?) throws -> String { + func distinct() -> QueryInterfaceQuery { + var query = self + query.isDistinct = true + return query + } + + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceQuery { + var query = self + query.filterPromise = query.filterPromise.map { (db, filter) in + if let filter = filter { + return try filter && predicate(db) + } else { + return try predicate(db).sqlExpression + } + } + return query + } + + func group(_ expressions: [SQLExpressible]) -> QueryInterfaceQuery { + var query = self + query.groupByExpressions = expressions.map { $0.sqlExpression } + return query + } + + func having(_ predicate: SQLExpressible) -> QueryInterfaceQuery { + var query = self + if let havingExpression = query.havingExpression { + query.havingExpression = (havingExpression && predicate).sqlExpression + } else { + query.havingExpression = predicate.sqlExpression + } + return query + } + + func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceQuery { + return order(QueryOrdering(orderings: orderings)) + } + + func reversed() -> QueryInterfaceQuery { + return order(ordering.reversed) + } + + private func order(_ ordering: QueryOrdering) -> QueryInterfaceQuery { + var query = self + query.ordering = ordering + return query + } + + func unordered() -> QueryInterfaceQuery { + var query = self + query.ordering = QueryOrdering() + return query + } + + func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceQuery { + var query = self + query.limit = SQLLimit(limit: limit, offset: offset) + return query + } + + func joining(_ join: AssociationJoin) -> QueryInterfaceQuery { + var query = self + query.joins.append(join) + return query + } + + func qualified(with alias: TableAlias) -> QueryInterfaceQuery { + var query = self + query.source = source.qualified(with: alias) + return query + } +} + +extension QueryInterfaceQuery { + /// A finalized query is ready for SQL generation + var finalizedQuery: QueryInterfaceQuery { + var query = self + + let alias = TableAlias() + query.source = source.qualified(with: alias) + query.selection = query.selection.map { $0.qualifiedSelectable(with: alias) } + query.filterPromise = query.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } + query.groupByExpressions = query.groupByExpressions.map { $0.qualifiedExpression(with: alias) } + query.ordering = query.ordering.qualified(with: alias) + query.havingExpression = query.havingExpression?.qualifiedExpression(with: alias) + + query.joins = query.joins.map { $0.finalizedJoin } + + return query + } + + /// precondition: self is the result of finalizedQuery + var finalizedAliases: [TableAlias] { + var aliases: [TableAlias] = [] + if let alias = alias { + aliases.append(alias) + } + return joins.reduce(into: aliases) { + $0.append(contentsOf: $1.finalizedAliases) + } + } + + /// precondition: self is the result of finalizedQuery + var finalizedSelection: [SQLSelectable] { + return joins.reduce(into: selection) { + $0.append(contentsOf: $1.finalizedSelection) + } + } + + /// precondition: self is the result of finalizedQuery + var finalizedOrdering: QueryOrdering { + return joins.reduce(ordering) { + $0.appending($1.finalizedOrdering) + } + } + + /// precondition: self is the result of finalizedQuery + private func finalizedRowAdapter(_ db: Database) throws -> RowAdapter? { + if joins.isEmpty { + return nil + } + + let selectionWidth = try selection + .map { try $0.columnCount(db) } + .reduce(0, +) + + var endIndex = selectionWidth + var scopes: [String: RowAdapter] = [:] + for join in joins { + if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: [join.key]) { + GRDBPrecondition(scopes[join.key] == nil, "The association key \"\(join.key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + scopes[join.key] = joinAdapter + endIndex = joinEndIndex + } + } + + if selectionWidth == 0 && scopes.isEmpty { + return nil + } + + let adapter = RangeRowAdapter(0 ..< (0 + selectionWidth)) + return adapter.addingScopes(scopes) + } +} + +extension QueryInterfaceQuery { + /// precondition: self is the result of finalizedQuery + func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { var sql = "SELECT" if isDistinct { sql += " DISTINCT" } - assert(!selection.isEmpty) - sql += " " + selection.map { $0.resultColumnSQL(&arguments) }.joined(separator: ", ") + let selection = finalizedSelection + GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") + sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") - if let source = source { - sql += try " FROM " + source.sourceSQL(db, &arguments) + sql += try " FROM " + source.sourceSQL(db, &context) + + for join in joins { + sql += try " " + join.joinSQL(db, &context, leftAlias: alias!, isRequiredAllowed: true) } - if let whereExpression = try wherePromise.resolve(db) { - sql += " WHERE " + whereExpression.expressionSQL(&arguments) + if let filter = try filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&context) } if !groupByExpressions.isEmpty { - sql += " GROUP BY " + groupByExpressions.map { $0.expressionSQL(&arguments) }.joined(separator: ", ") + sql += " GROUP BY " + sql += groupByExpressions.map { $0.expressionSQL(&context) } + .joined(separator: ", ") } if let havingExpression = havingExpression { - sql += " HAVING " + havingExpression.expressionSQL(&arguments) + sql += " HAVING " + havingExpression.expressionSQL(&context) } - let orderings = self.ordering.resolve() + let orderings = finalizedOrdering.resolve() if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") } if let limit = limit { @@ -90,32 +260,49 @@ struct QueryInterfaceQuery { return sql } + /// precondition: self is the result of finalizedQuery + private func makeSelectStatement(_ db: Database) throws -> SelectStatement { + var context = SQLGenerationContext.queryGenerationContext(aliases: finalizedAliases) + let sql = try self.sql(db, &context) + let statement = try db.makeSelectStatement(sql) + statement.arguments = context.arguments! + return statement + } + + /// precondition: self is the result of finalizedQuery func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { guard groupByExpressions.isEmpty else { // Programmer error - fatalError("Can't delete query with GROUP BY expression") + fatalError("Can't delete query with GROUP BY clause") } guard havingExpression == nil else { // Programmer error - fatalError("Can't delete query with GROUP BY expression") + fatalError("Can't delete query with HAVING clause") } - var sql = "DELETE" - var arguments: StatementArguments? = StatementArguments() - - if let source = source { - sql += try " FROM " + source.sourceSQL(db, &arguments) + guard joins.isEmpty else { + // Programmer error + fatalError("Can't delete query with JOIN clause") } - if let whereExpression = try wherePromise.resolve(db) { - sql += " WHERE " + whereExpression.expressionSQL(&arguments) + guard case .table = source else { + // Programmer error + fatalError("Can't delete without any database table") + } + + var context = SQLGenerationContext.queryGenerationContext(aliases: finalizedAliases) + + var sql = try "DELETE FROM " + source.sourceSQL(db, &context) + + if let filter = try filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&context) } if let limit = limit { - let orderings = self.ordering.resolve() + let orderings = finalizedOrdering.resolve() if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") } if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") { @@ -126,25 +313,13 @@ struct QueryInterfaceQuery { } let statement = try db.makeUpdateStatement(sql) - statement.arguments = arguments! + statement.arguments = context.arguments! return statement } - /// Remove ordering - var unorderedQuery: QueryInterfaceQuery { - var query = self - query.ordering = QueryOrdering() - return query - } -} - -extension QueryInterfaceQuery { + /// precondition: self is the result of finalizedQuery func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - var arguments: StatementArguments? = StatementArguments() - let sql = try self.sql(db, &arguments) - let statement = try db.makeSelectStatement(sql) - try statement.setArgumentsWithValidation(arguments!) - return (statement, nil) + return try (makeSelectStatement(db), finalizedRowAdapter(db)) } func fetchCount(_ db: Database) throws -> Int { @@ -153,17 +328,16 @@ extension QueryInterfaceQuery { } /// The database region that the request looks into. + /// precondition: self is the result of finalizedQuery func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - let (statement, _) = try prepare(db) + let statement = try makeSelectStatement(db) let region = statement.fetchedRegion // Can we intersect the region with rowIds? // // Give up unless request feeds from a single database table - guard let source = source else { - return region - } - guard case .table(name: let tableName, alias: _) = source else { + guard case .table(tableName: let tableName, alias: _) = source else { + // TODO: try harder return region } @@ -174,17 +348,17 @@ extension QueryInterfaceQuery { } // Give up unless there is a where clause - guard let whereExpression = try wherePromise.resolve(db) else { + guard let filter = try filterPromise.resolve(db) else { return region } - // The whereExpression knows better - guard let rowIds = whereExpression.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { + // The filter knows better + guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { return region } // Database regions are case-insensitive: use the canonical table name - let canonicalTableName = try db.canonicalName(table: tableName) + let canonicalTableName = try db.canonicalTableName(tableName) return region.tableIntersection(canonicalTableName, rowIds: rowIds) } @@ -195,17 +369,17 @@ extension QueryInterfaceQuery { return trivialCountQuery } - guard let source = source, case .table = source else { - // SELECT ... FROM (something which is not a table) + guard joins.isEmpty, case .table = source else { + // SELECT ... FROM (something which is not a plain table) return trivialCountQuery } - assert(!selection.isEmpty) + GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") if selection.count == 1 { guard let count = self.selection[0].count(distinct: isDistinct) else { return trivialCountQuery } - var countQuery = unorderedQuery + var countQuery = self.unordered() countQuery.isDistinct = false countQuery.selection = [count.sqlSelectable] return countQuery @@ -219,7 +393,7 @@ extension QueryInterfaceQuery { // SELECT expr1, expr2, ... FROM tableName ... // -> // SELECT COUNT(*) FROM tableName ... - var countQuery = unorderedQuery + var countQuery = self.unordered() countQuery.selection = [SQLExpressionCount(AllColumns())] return countQuery } @@ -228,59 +402,245 @@ extension QueryInterfaceQuery { // SELECT COUNT(*) FROM (self) private var trivialCountQuery: QueryInterfaceQuery { return QueryInterfaceQuery( - select: [SQLExpressionCount(AllColumns())], - from: .query(query: unorderedQuery, alias: nil)) + source: .query(unordered()), + selection: [SQLExpressionCount(AllColumns())]) } } +// MARK: - AssociationJoin + +/// Not to be mismatched with SQL join operators (inner join, left join). +/// +/// AssociationJoinOperator is designed to be hierarchically nested, unlike +/// SQL join operators. +/// +/// Consider the following request for (A, B, C) tuples: +/// +/// let r = A.including(optional: A.b.including(required: B.c)) +/// +/// It chains three associations, the first optional, the second required. +/// +/// It looks like it means: "Give me all As, along with their Bs, granted those +/// Bs have their Cs. For As whose B has no C, give me a nil B". +/// +/// It can not be expressed as one left join, and a regular join, as below, +/// Because this would not honor the first optional: +/// +/// -- dubious +/// SELECT a.*, b.*, c.* +/// FROM a +/// LEFT JOIN b ON ... +/// JOIN c ON ... +/// +/// Instead, it should: +/// - allow (A + missing (B + C)) +/// - prevent (A + (B + missing C)). +/// +/// This can be expressed in SQL with two left joins, and an extra condition: +/// +/// -- likely correct +/// SELECT a.*, b.*, c.* +/// FROM a +/// LEFT JOIN b ON ... +/// LEFT JOIN c ON ... +/// WHERE NOT((b.id IS NOT NULL) AND (c.id IS NULL)) -- no B without C +/// +/// This is currently not implemented, and requires a little more thought. +/// I don't even know if inventing a whole new way to perform joins should even +/// be on the table. But we have a hierarchical way to express joined queries, +/// and they have a meaning: +/// +/// // what is my meaning? +/// A.including(optional: A.b.including(required: B.c)) +enum AssociationJoinOperator { + case required, optional +} + +struct AssociationJoin { + var joinOperator: AssociationJoinOperator + var query: AssociationQuery + var key: String + var joinConditionPromise: DatabasePromise + + var finalizedJoin: AssociationJoin { + var join = self + join.query = query.finalizedQuery + return join + } + + var finalizedAliases: [TableAlias] { + return query.finalizedAliases + } + + var finalizedSelection: [SQLSelectable] { + return query.finalizedSelection + } + + var finalizedOrdering: QueryOrdering { + return query.finalizedOrdering + } + + func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { + return try query.finalizedRowAdapter(db, fromIndex: startIndex, forKeyPath: keyPath) + } + + /// precondition: query is the result of finalizedQuery + func joinSQL(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { + var isRequiredAllowed = isRequiredAllowed + var sql = "" + switch joinOperator { + case .optional: + isRequiredAllowed = false + sql += "LEFT JOIN" + case .required: + guard isRequiredAllowed else { + // TODO: chainOptionalRequired + fatalError("Not implemented: chaining a required association behind an optional association") + } + sql += "JOIN" + } + + sql += try " " + query.source.sourceSQL(db, &context) + + let rightAlias = query.alias! + let filters = try [ + joinConditionPromise.resolve(db)(leftAlias, rightAlias), + query.filterPromise.resolve(db) + ].compactMap { $0 } + if !filters.isEmpty { + sql += " ON " + filters.joined(operator: .and).expressionSQL(&context) + } + + for join in query.joins { + sql += try " " + join.joinSQL(db, &context, leftAlias: rightAlias, isRequiredAllowed: isRequiredAllowed) + } + + return sql + } +} + +// MARK: - QueryOrdering + struct QueryOrdering { - private var orderings: [SQLOrderingTerm] + private var elements: [Element] = [] var isReversed: Bool - init(orderings: [SQLOrderingTerm] = [], isReversed: Bool = false) { - self.orderings = orderings + private enum Element { + case orderingTerm(SQLOrderingTerm) + case queryOrdering(QueryOrdering) + + var reversed: Element { + switch self { + case .orderingTerm(let orderingTerm): + return .orderingTerm(orderingTerm.reversed) + case .queryOrdering(let queryOrdering): + return .queryOrdering(queryOrdering.reversed) + } + } + + func qualified(with alias: TableAlias) -> Element { + switch self { + case .orderingTerm(let orderingTerm): + return .orderingTerm(orderingTerm.qualifiedOrdering(with: alias)) + case .queryOrdering(let queryOrdering): + return .queryOrdering(queryOrdering.qualified(with: alias)) + } + } + + func resolve() -> [SQLOrderingTerm] { + switch self { + case .orderingTerm(let orderingTerm): + return [orderingTerm] + case .queryOrdering(let queryOrdering): + return queryOrdering.resolve() + } + } + } + + private init(elements: [Element], isReversed: Bool) { + self.elements = elements self.isReversed = isReversed } - func reversed() -> QueryOrdering { + init() { + self.init( + elements: [], + isReversed: false) + } + + init(orderings: [SQLOrderingTerm]) { + self.init( + elements: orderings.map { .orderingTerm($0) }, + isReversed: false) + } + + var reversed: QueryOrdering { return QueryOrdering( - orderings: orderings, + elements: elements, isReversed: !isReversed) } - func appending(ordering: SQLOrderingTerm) -> QueryOrdering { + func qualified(with alias: TableAlias) -> QueryOrdering { return QueryOrdering( - orderings: orderings + [ordering], + elements: elements.map { $0.qualified(with: alias) }, + isReversed: isReversed) + } + + func appending(_ ordering: QueryOrdering) -> QueryOrdering { + return QueryOrdering( + elements: elements + [.queryOrdering(ordering)], isReversed: isReversed) } func resolve() -> [SQLOrderingTerm] { if isReversed { - return orderings.map { $0.reversed } + return elements.flatMap { $0.reversed.resolve() } } else { - return orderings + return elements.flatMap { $0.resolve() } } } } -indirect enum SQLSource { - case table(name: String, alias: String?) - case query(query: QueryInterfaceQuery, alias: String?) +// MARK: - SQLSource + +enum SQLSource { + case table(tableName: String, alias: TableAlias?) + indirect case query(QueryInterfaceQuery) - func sourceSQL(_ db: Database, _ arguments: inout StatementArguments?) throws -> String { + var alias: TableAlias? { switch self { - case .table(let table, let alias): - if let alias = alias { - return table.quotedDatabaseIdentifier + " AS " + alias.quotedDatabaseIdentifier + case .table(_, let alias): + return alias + case .query(let query): + return query.alias + } + } + + func sourceSQL(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { + switch self { + case .table(let tableName, let alias): + if let alias = alias, let aliasName = context.aliasName(for: alias) { + return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)" } else { - return table.quotedDatabaseIdentifier + return "\(tableName.quotedDatabaseIdentifier)" } - case .query(let query, let alias): - if let alias = alias { - return try "(" + query.sql(db, &arguments) + ") AS " + alias.quotedDatabaseIdentifier + case .query(let query): + return try "(\(query.sql(db, &context)))" + } + } + + func qualified(with alias: TableAlias) -> SQLSource { + switch self { + case .table(let tableName, let sourceAlias): + if let sourceAlias = sourceAlias { + alias.rebase(on: sourceAlias) + return self } else { - return try "(" + query.sql(db, &arguments) + ")" + alias.setTableName(tableName) + return .table(tableName: tableName, alias: alias) } + case .query(let query): + return .query(query.qualified(with: alias)) } } } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift new file mode 100644 index 000000000..32dafae77 --- /dev/null +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -0,0 +1,95 @@ +extension QueryInterfaceRequest where RowDecoder: TableRecord { + func joining(_ joinOperator: AssociationJoinOperator, _ association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == RowDecoder + { + let join = AssociationJoin( + joinOperator: joinOperator, + query: association.request.query, + key: association.key, + joinConditionPromise: DatabasePromise(association.joinCondition)) + return QueryInterfaceRequest(query: query.joining(join)) + } + + // MARK: - Associations + + /// Creates a request that includes an association. The columns of the + /// associated record are selected. The returned association does not + /// require that the associated database table contains a matching row. + public func including(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == RowDecoder { + return joining(.optional, association) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are selected. The returned association requires + /// that the associated database table contains a matching row. + public func including(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == RowDecoder { + return joining(.required, association) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are not selected. The returned association does not + /// require that the associated database table contains a matching row. + public func joining(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == RowDecoder { + return joining(.optional, association.select([])) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are not selected. The returned association requires + /// that the associated database table contains a matching row. + public func joining(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == RowDecoder { + return joining(.required, association.select([])) + } +} + +extension MutablePersistableRecord { + /// Creates a request that fetches the associated record(s). + /// + /// For example: + /// + /// struct Team: { + /// static let players = hasMany(Player.self) + /// var players: QueryInterfaceRequest { + /// return request(for: Team.players) + /// } + /// } + /// + /// let team: Team = ... + /// let players = try team.players.fetchAll(db) // [Player] + public func request(for association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + return association.request(from: self) + } +} + +extension TableRecord { + + // MARK: - Associations + + /// Creates a request that includes an association. The columns of the + /// associated record are selected. The returned association does not + /// require that the associated database table contains a matching row. + public static func including(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + return all().including(optional: association) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are selected. The returned association requires + /// that the associated database table contains a matching row. + public static func including(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + return all().including(required: association) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are not selected. The returned association does not + /// require that the associated database table contains a matching row. + public static func joining(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + return all().joining(optional: association) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are not selected. The returned association requires + /// that the associated database table contains a matching row. + public static func joining(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + return all().joining(required: association) + } +} diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index ac29e72a4..38ab39e52 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -7,6 +7,10 @@ public struct QueryInterfaceRequest { init(query: QueryInterfaceQuery) { self.query = query } + + init(_ request: AssociationRequest) { + self.query = QueryInterfaceQuery(request.query) + } } extension QueryInterfaceRequest : FetchRequest { @@ -19,7 +23,7 @@ extension QueryInterfaceRequest : FetchRequest { /// - returns: A prepared statement and an eventual row adapter. /// :nodoc: public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try query.prepare(db) + return try query.finalizedQuery.prepare(db) } /// Returns the number of rows fetched by the request. @@ -35,7 +39,7 @@ extension QueryInterfaceRequest : FetchRequest { /// - parameter db: A database connection. /// :nodoc: public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try query.fetchedRegion(db) + return try query.finalizedQuery.fetchedRegion(db) } } @@ -45,242 +49,146 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// Creates a request with a new net of selected columns. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// var request = Player.all() /// request = request.select([Column("id"), Column("email")]) /// /// Any previous selection is replaced: /// - /// // SELECT email FROM players + /// // SELECT email FROM player /// request /// .select([Column("id")]) /// .select([Column("email")]) public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { - var query = self.query - query.selection = selection - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.select(selection)) } /// Creates a request which returns distinct rows. /// - /// // SELECT DISTINCT * FROM players + /// // SELECT DISTINCT * FROM player /// var request = Player.all() /// request = request.distinct() /// - /// // SELECT DISTINCT name FROM players + /// // SELECT DISTINCT name FROM player /// var request = Player.select(Column("name")) /// request = request.distinct() public func distinct() -> QueryInterfaceRequest { - var query = self.query - query.isDistinct = true - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.distinct()) } - /// Creates a request with the provided *predicate* added to the + /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM player WHERE 1 /// var request = Player.all() - /// request = request.filter(Column("email") == "arthur@example.com") - public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in - if let expression = expression { - return expression && predicate.sqlExpression - } else { - return predicate.sqlExpression - } - }) - } - - /// Creates a request that matches nothing. - /// - /// // SELECT * FROM players WHERE 0 - /// var request = Player.all() - /// request = request.none() - public func none() -> QueryInterfaceRequest { - var query = self.query - query.wherePromise = DatabasePromise(value: false.sqlExpression) - return QueryInterfaceRequest(query: query) + /// request = request.filter { db in true } + public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { + return QueryInterfaceRequest(query: query.filter(predicate)) } /// Creates a request grouped according to *expressions*. public func group(_ expressions: [SQLExpressible]) -> QueryInterfaceRequest { - var query = self.query - query.groupByExpressions = expressions.map { $0.sqlExpression } - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.group(expressions)) } /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest { - var query = self.query - if let havingExpression = query.havingExpression { - query.havingExpression = (havingExpression && predicate).sqlExpression - } else { - query.havingExpression = predicate.sqlExpression - } - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.having(predicate)) } /// Creates a request with the provided *orderings*. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// var request = Player.all() /// request = request.order([Column("name")]) /// /// Any previous ordering is replaced: /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// request /// .order([Column("email")]) /// .reversed() /// .order([Column("name")]) public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { - var query = self.query - query.ordering = QueryOrdering(orderings: orderings) - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.order(orderings)) } - /// Creates a request sorted in reversed order. + /// Creates a request that reverses applied orderings. /// - /// // SELECT * FROM players ORDER BY name DESC + /// // SELECT * FROM player ORDER BY name DESC /// var request = Player.all().order(Column("name")) /// request = request.reversed() + /// + /// If no ordering was applied, the returned request is identical. + /// + /// // SELECT * FROM player + /// var request = Player.all() + /// request = request.reversed() public func reversed() -> QueryInterfaceRequest { - var query = self.query - query.ordering = query.ordering.reversed() - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.reversed()) } /// Creates a request which fetches *limit* rows, starting at *offset*. /// - /// // SELECT * FROM players LIMIT 1 + /// // SELECT * FROM player LIMIT 1 /// var request = Player.all() /// request = request.limit(1) /// /// Any previous limit is replaced. public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { - var query = self.query - query.limit = SQLLimit(limit: limit, offset: offset) - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.limit(limit, offset: offset)) + } + + /// Creates a request that allows you to define expressions that target + /// a specific database table. + /// + /// In the example below, the "team.avgScore < player.score" condition in + /// the ON clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... AND team.avgScore < player.score + /// let playerAlias = TableAlias() + /// let request = Player + /// .all() + /// .aliased(playerAlias) + /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) + public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + return QueryInterfaceRequest(query: query.qualified(with: alias)) + } + + /// Creates a request bound to type Target. + /// + /// The returned request can fetch if the type Target is fetchable (Row, + /// value, record). + /// + /// // Int? + /// let maxScore = try Player + /// .select(max(scoreColumn)) + /// .asRequest(of: Int.self) // <-- + /// .fetchOne(db) + /// + /// - parameter type: The fetched type Target + /// - returns: A typed request bound to type Target. + public func asRequest(of type: Target.Type) -> QueryInterfaceRequest { + return QueryInterfaceRequest(query: query) } } -extension QueryInterfaceRequest where T: TableRecord { - - // MARK: Request Derivation - - /// Creates a request with the provided primary key *predicate*. - /// - /// // SELECT * FROM players WHERE id = 1 - /// var request = Player.all() - /// request = request.filter(key: 1) - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func filter(key: PrimaryKeyType?) -> QueryInterfaceRequest { - guard let key = key else { - return T.none() - } - - return filter(keys: [key]) - } - - /// Creates a request with the provided primary key *predicate*. - /// - /// // SELECT * FROM players WHERE id IN (1, 2, 3) - /// var request = Player.all() - /// request = request.filter(keys: [1, 2, 3]) - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func filter(keys: Sequence) -> QueryInterfaceRequest where Sequence.Element: DatabaseValueConvertible { - let keys = Array(keys) - let makePredicate: (Column) -> SQLExpression - switch keys.count { - case 0: - return T.none() - case 1: - makePredicate = { $0 == keys[0] } - default: - makePredicate = { keys.contains($0) } - } - - return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in - let primaryKey = try db.primaryKey(T.databaseTableName) - GRDBPrecondition(primaryKey.columns.count == 1, "Requesting by key requires a single-column primary key in the table \(T.databaseTableName)") - let keysPredicate = makePredicate(Column(primaryKey.columns[0])) - if let expression = expression { - return expression && keysPredicate - } else { - return keysPredicate - } - }) - } - - /// Creates a request with the provided primary key *predicate*. - /// - /// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR' - /// var request = Player.all() - /// request = request.filter(key: ["personId": 1, "countryCode": "FR"]) - /// - /// When executed, this request raises a fatal error if there is no unique - /// index on the key columns. - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { - guard let key = key else { - return T.none() - } - - return filter(keys: [key]) - } - - /// Creates a request with the provided primary key *predicate*. - /// - /// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ... - /// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...]) - /// - /// When executed, this request raises a fatal error if there is no unique - /// index on the key columns. - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { - guard !keys.isEmpty else { - return T.none() - } - - return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in - let keyPredicates: [SQLExpression] = try keys.map { key in - // Prevent filter(keys: [["foo": 1, "bar": 2]]) where - // ("foo", "bar") is not a unique key (primary key or columns of a - // unique index) - guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: T.databaseTableName) else { - fatalError("table \(T.databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))") - } - - let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() } - let columnPredicates: [SQLExpression] = key - // Sort key columns in the same order as the unique index - .sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! } - .map { (column, value) in Column(column) == value } - return columnPredicates.joined(operator: .and) - } - - let keysPredicate = keyPredicates.joined(operator: .or) - - if let expression = expression { - return expression && keysPredicate - } else { - return keysPredicate - } - }) +/// Conditional conformance to TableRequest when RowDecoder conforms +/// to TableRecord: +/// +/// let request = Player.all() +/// request.filter(key: ...) +/// request.filter(keys: ...) +extension QueryInterfaceRequest: TableRequest where RowDecoder: TableRecord { + /// :nodoc: + public var databaseTableName: String { + return RowDecoder.databaseTableName } } @@ -306,7 +214,7 @@ extension TableRecord { /// Creates a request which fetches all records. /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// let request = Player.all() /// /// The selection defaults to all columns. This default can be changed for @@ -314,19 +222,19 @@ extension TableRecord { /// for individual requests with the `TableRecord.select` method. public static func all() -> QueryInterfaceRequest { let query = QueryInterfaceQuery( - select: databaseSelection, - from: .table(name: databaseTableName, alias: nil)) + source: .table(tableName: databaseTableName, alias: nil), + selection: databaseSelection) return QueryInterfaceRequest(query: query) } /// Creates a request which fetches no record. public static func none() -> QueryInterfaceRequest { - return filter(false) + return all().none() // don't laugh } /// Creates a request which selects *selection*. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// let request = Player.select(Column("id"), Column("email")) public static func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { return all().select(selection) @@ -334,7 +242,7 @@ extension TableRecord { /// Creates a request which selects *selection*. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// let request = Player.select([Column("id"), Column("email")]) public static func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { return all().select(selection) @@ -342,7 +250,7 @@ extension TableRecord { /// Creates a request which selects *sql*. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// let request = Player.select(sql: "id, email") public static func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { return all().select(sql: sql, arguments: arguments) @@ -350,7 +258,7 @@ extension TableRecord { /// Creates a request with the provided *predicate*. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM player WHERE email = 'arthur@example.com' /// let request = Player.filter(Column("email") == "arthur@example.com") /// /// The selection defaults to all columns. This default can be changed for @@ -362,7 +270,7 @@ extension TableRecord { /// Creates a request with the provided primary key *predicate*. /// - /// // SELECT * FROM players WHERE id = 1 + /// // SELECT * FROM player WHERE id = 1 /// let request = Player.filter(key: 1) /// /// The selection defaults to all columns. This default can be changed for @@ -374,7 +282,7 @@ extension TableRecord { /// Creates a request with the provided primary key *predicate*. /// - /// // SELECT * FROM players WHERE id IN (1, 2, 3) + /// // SELECT * FROM player WHERE id IN (1, 2, 3) /// let request = Player.filter(keys: [1, 2, 3]) /// /// The selection defaults to all columns. This default can be changed for @@ -386,7 +294,7 @@ extension TableRecord { /// Creates a request with the provided primary key *predicate*. /// - /// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR' + /// // SELECT * FROM passport WHERE personId = 1 AND countryCode = 'FR' /// let request = Passport.filter(key: ["personId": 1, "countryCode": "FR"]) /// /// When executed, this request raises a fatal error if there is no unique @@ -401,7 +309,7 @@ extension TableRecord { /// Creates a request with the provided primary key *predicate*. /// - /// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ... + /// // SELECT * FROM passport WHERE (personId = 1 AND countryCode = 'FR') OR ... /// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...]) /// /// When executed, this request raises a fatal error if there is no unique @@ -416,7 +324,7 @@ extension TableRecord { /// Creates a request with the provided *predicate*. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM player WHERE email = 'arthur@example.com' /// let request = Player.filter(sql: "email = ?", arguments: ["arthur@example.com"]) /// /// The selection defaults to all columns. This default can be changed for @@ -429,7 +337,7 @@ extension TableRecord { /// Creates a request sorted according to the /// provided *orderings*. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// let request = Player.order(Column("name")) /// /// The selection defaults to all columns. This default can be changed for @@ -442,7 +350,7 @@ extension TableRecord { /// Creates a request sorted according to the /// provided *orderings*. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// let request = Player.order([Column("name")]) /// /// The selection defaults to all columns. This default can be changed for @@ -454,7 +362,7 @@ extension TableRecord { /// Creates a request sorted according to *sql*. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// let request = Player.order(sql: "name") /// /// The selection defaults to all columns. This default can be changed for @@ -467,7 +375,7 @@ extension TableRecord { /// Creates a request which fetches *limit* rows, starting at /// *offset*. /// - /// // SELECT * FROM players LIMIT 1 + /// // SELECT * FROM player LIMIT 1 /// let request = Player.limit(1) /// /// The selection defaults to all columns. This default can be changed for @@ -476,4 +384,24 @@ extension TableRecord { public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { return all().limit(limit, offset: offset) } + + /// Creates a request that allows you to define expressions that target + /// a specific database table. + /// + /// In the example below, the "team.avgScore < player.score" condition in + /// the ON clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... AND team.avgScore < player.score + /// let playerAlias = TableAlias() + /// let request = Player + /// .aliased(playerAlias) + /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) + public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + return all().aliased(alias) + } } diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift index 4fa777d9b..8ae46b0a4 100644 --- a/GRDB/QueryInterface/RequestProtocols.swift +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -4,13 +4,13 @@ public protocol SelectionRequest { /// Creates a request with a new net of selected columns. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// var request = Player.all() /// request = request.select([Column("id"), Column("email")]) /// /// Any previous selection is replaced: /// - /// // SELECT email FROM players + /// // SELECT email FROM player /// request /// .select([Column("id")]) /// .select([Column("email")]) @@ -20,13 +20,13 @@ public protocol SelectionRequest { extension SelectionRequest { /// Creates a request with a new net of selected columns. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// var request = Player.all() /// request = request.select(Column("id"), Column("email")) /// /// Any previous selection is replaced: /// - /// // SELECT email FROM players + /// // SELECT email FROM player /// request /// .select(Column("id")) /// .select(Column("email")) @@ -36,13 +36,13 @@ extension SelectionRequest { /// Creates a request with a new net of selected columns. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// var request = Player.all() /// request = request.select(sql: "id, email") /// /// Any previous selection is replaced: /// - /// // SELECT email FROM players + /// // SELECT email FROM player /// request /// .select(sql: "id") /// .select(sql: "email") @@ -55,32 +55,151 @@ extension SelectionRequest { /// The protocol for all requests that can be filtered. public protocol FilteredRequest { - /// Creates a request with the provided *predicate* added to the + /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM player WHERE 1 /// var request = Player.all() - /// request = request.filter(Column("email") == "arthur@example.com") - func filter(_ predicate: SQLExpressible) -> Self - - /// Creates a request that matches nothing. - /// - /// // SELECT * FROM players WHERE 0 - /// var request = Player.all() - /// request = request.none() - func none() -> Self + /// request = request.filter { db in true } + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self } extension FilteredRequest { /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM player WHERE email = 'arthur@example.com' + /// var request = Player.all() + /// request = request.filter(Column("email") == "arthur@example.com") + public func filter(_ predicate: SQLExpressible) -> Self { + return filter { _ in predicate } + } + + /// Creates a request with the provided *predicate* added to the + /// eventual set of already applied predicates. + /// + /// // SELECT * FROM player WHERE email = 'arthur@example.com' /// var request = Player.all() /// request = request.filter(sql: "email = ?", arguments: ["arthur@example.com"]) public func filter(sql: String, arguments: StatementArguments? = nil) -> Self { return filter(SQLExpressionLiteral(sql, arguments: arguments)) } + + /// Creates a request that matches nothing. + /// + /// // SELECT * FROM player WHERE 0 + /// var request = Player.all() + /// request = request.none() + public func none() -> Self { + return filter(false) + } +} + +// MARK: - TableRequest { + +/// The protocol for all requests that feed from a database table +public protocol TableRequest { + /// The name of the database table + var databaseTableName: String { get } + + /// Creates a request that allows you to define expressions that target + /// a specific database table. + /// + /// In the example below, the "team.avgScore < player.score" condition in + /// the ON clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... AND team.avgScore < player.score + /// let playerAlias = TableAlias() + /// let request = Player + /// .all() + /// .aliased(playerAlias) + /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) + func aliased(_ alias: TableAlias) -> Self +} + +extension TableRequest where Self: FilteredRequest { + + /// Creates a request with the provided primary key *predicate*. + public func filter(key: PrimaryKeyType?) -> Self { + guard let key = key else { + return none() + } + return filter(keys: [key]) + } + + /// Creates a request with the provided primary key *predicate*. + public func filter(keys: Sequence) -> Self where Sequence.Element: DatabaseValueConvertible { + let keys = Array(keys) + let makePredicate: (Column) -> SQLExpression + switch keys.count { + case 0: + return none() + case 1: + makePredicate = { $0 == keys[0] } + default: + makePredicate = { keys.contains($0) } + } + + let databaseTableName = self.databaseTableName + return filter { db in + let primaryKey = try db.primaryKey(databaseTableName) + GRDBPrecondition( + primaryKey.columns.count == 1, + "Requesting by key requires a single-column primary key in the table \(databaseTableName)") + return makePredicate(Column(primaryKey.columns[0])) + } + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + public func filter(key: [String: DatabaseValueConvertible?]?) -> Self { + guard let key = key else { + return none() + } + return filter(keys: [key]) + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + public func filter(keys: [[String: DatabaseValueConvertible?]]) -> Self { + guard !keys.isEmpty else { + return none() + } + + let databaseTableName = self.databaseTableName + return filter { db in + try keys + .map { key in + // Prevent filter(keys: [["foo": 1, "bar": 2]]) where + // ("foo", "bar") is not a unique key (primary key or columns of a + // unique index) + guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { + fatalError("table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))") + } + + let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() } + return key + // Sort key columns in the same order as the unique index + .sorted { (kv1, kv2) in + let index1 = lowercaseOrderedColumns.index(of: kv1.key.lowercased())! + let index2 = lowercaseOrderedColumns.index(of: kv2.key.lowercased())! + return index1 < index2 + } + .map { (column, value) in Column(column) == value } + .joined(operator: .and) + } + .joined(operator: .or) + } + } } // MARK: - AggregatingRequest @@ -129,27 +248,28 @@ extension AggregatingRequest { public protocol OrderedRequest { /// Creates a request with the provided *orderings*. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// var request = Player.all() /// request = request.order([Column("name")]) /// /// Any previous ordering is replaced: /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// request /// .order([Column("email")]) /// .reversed() /// .order([Column("name")]) func order(_ orderings: [SQLOrderingTerm]) -> Self - /// Creates a request that reverses applied orderings. If no ordering - /// was applied, the returned request is identical. + /// Creates a request that reverses applied orderings. /// - /// // SELECT * FROM players ORDER BY name DESC + /// // SELECT * FROM player ORDER BY name DESC /// var request = Player.all().order(Column("name")) /// request = request.reversed() /// - /// // SELECT * FROM players + /// If no ordering was applied, the returned request is identical. + /// + /// // SELECT * FROM player /// var request = Player.all() /// request = request.reversed() func reversed() -> Self @@ -158,13 +278,13 @@ public protocol OrderedRequest { extension OrderedRequest { /// Creates a request with the provided *orderings*. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// var request = Player.all() /// request = request.order(Column("name")) /// /// Any previous ordering is replaced: /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// request /// .order(Column("email")) /// .reversed() @@ -175,13 +295,13 @@ extension OrderedRequest { /// Creates a request with the provided *sql* used for sorting. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// var request = Player.all() /// request = request.order(sql: "name") /// /// Any previous ordering is replaced: /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// request /// .order(sql: "email") /// .order(sql: "name") diff --git a/GRDB/QueryInterface/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQLCollatedExpression.swift index 3266580c0..d56036c13 100644 --- a/GRDB/QueryInterface/SQLCollatedExpression.swift +++ b/GRDB/QueryInterface/SQLCollatedExpression.swift @@ -5,8 +5,8 @@ /// /// let email: SQLCollatedExpression = Column("email").collating(.nocase) /// -/// // SELECT * FROM players WHERE email = 'arthur@example.com' COLLATE NOCASE -/// Players.filter(email == "arthur@example.com") +/// // SELECT * FROM player WHERE email = 'arthur@example.com' COLLATE NOCASE +/// Player.filter(email == "arthur@example.com") public struct SQLCollatedExpression { /// The tainted expression public let expression: SQLExpression @@ -18,8 +18,8 @@ public struct SQLCollatedExpression { /// /// let email: SQLCollatedExpression = Column("email").collating(.nocase) /// - /// // SELECT * FROM players ORDER BY email COLLATE NOCASE ASC - /// Players.order(email.asc) + /// // SELECT * FROM player ORDER BY email COLLATE NOCASE ASC + /// Player.order(email.asc) /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var asc: SQLOrderingTerm { @@ -30,8 +30,8 @@ public struct SQLCollatedExpression { /// /// let email: SQLCollatedExpression = Column("email").collating(.nocase) /// - /// // SELECT * FROM players ORDER BY email COLLATE NOCASE DESC - /// Players.order(email.desc) + /// // SELECT * FROM player ORDER BY email COLLATE NOCASE DESC + /// Player.order(email.desc) /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var desc: SQLOrderingTerm { @@ -58,7 +58,13 @@ extension SQLCollatedExpression : SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String { - return sqlExpression.orderingTermSQL(&arguments) + public func orderingTermSQL(_ context: inout SQLGenerationContext) -> String { + return sqlExpression.orderingTermSQL(&context) + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { + return SQLCollatedExpression(expression.qualifiedExpression(with: alias), collationName: collationName) } } diff --git a/GRDB/QueryInterface/SQLCollection.swift b/GRDB/QueryInterface/SQLCollection.swift index 22923ae0e..3242b5ea7 100644 --- a/GRDB/QueryInterface/SQLCollection.swift +++ b/GRDB/QueryInterface/SQLCollection.swift @@ -9,22 +9,7 @@ public protocol SQLCollection { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns an SQL string that represents the collection. - /// - /// When the arguments parameter is nil, any value must be written down as - /// a literal in the returned SQL: - /// - /// var arguments: StatementArguments? = nil - /// let collection = SQLExpressionsArray([1,2,3]) - /// collection.collectionSQL(&arguments) // "1,2,3" - /// - /// When the arguments parameter is not nil, then values may be replaced by - /// `?` or colon-prefixed tokens, and fed into arguments. - /// - /// var arguments = StatementArguments() - /// let collection = SQLExpressionsArray([1,2,3]) - /// collection.collectionSQL(&arguments) // "?,?,?" - /// arguments // [1,2,3] - func collectionSQL(_ arguments: inout StatementArguments?) -> String + func collectionSQL(_ context: inout SQLGenerationContext) -> String /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// @@ -58,8 +43,8 @@ struct SQLExpressionsArray : SQLCollection { self.expressions = expressions.map { $0.sqlExpression } } - func collectionSQL(_ arguments: inout StatementArguments?) -> String { - return (expressions.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") + func collectionSQL(_ context: inout SQLGenerationContext) -> String { + return (expressions.map { $0.expressionSQL(&context) } as [String]).joined(separator: ", ") } func contains(_ value: SQLExpressible) -> SQLExpression { diff --git a/GRDB/QueryInterface/SQLExpressible.swift b/GRDB/QueryInterface/SQLExpressible.swift index 9d7aa31db..f90778684 100644 --- a/GRDB/QueryInterface/SQLExpressible.swift +++ b/GRDB/QueryInterface/SQLExpressible.swift @@ -64,8 +64,8 @@ extension SQLExpressible where Self: SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String { - return sqlExpression.expressionSQL(&arguments) + public func orderingTermSQL(_ context: inout SQLGenerationContext) -> String { + return sqlExpression.expressionSQL(&context) } } @@ -75,14 +75,14 @@ extension SQLExpressible where Self: SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - return sqlExpression.expressionSQL(&arguments) + public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { + return sqlExpression.expressionSQL(&context) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func countedSQL(_ arguments: inout StatementArguments?) -> String { - return sqlExpression.expressionSQL(&arguments) + public func countedSQL(_ context: inout SQLGenerationContext) -> String { + return sqlExpression.expressionSQL(&context) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index a7a7f8dcc..9cf63ab84 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -8,17 +8,17 @@ extension SQLExpression { /// /// :nodoc: public var literal: SQLExpressionLiteral { - var arguments: StatementArguments? = [] - let sql = expressionSQL(&arguments) - return SQLExpressionLiteral(sql, arguments: arguments) + var context = SQLGenerationContext.literalGenerationContext(withArguments: true) + let sql = expressionSQL(&context) + return SQLExpressionLiteral(sql, arguments: context.arguments) } /// The expression as a quoted SQL literal (not public in order to avoid abuses) /// /// "foo'bar".databaseValue.sql // "'foo''bar'"" var sql: String { - var arguments: StatementArguments? = nil - return expressionSQL(&arguments) + var context = SQLGenerationContext.literalGenerationContext(withArguments: false) + return expressionSQL(&context) } } @@ -66,14 +66,13 @@ public struct SQLExpressionLiteral : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { - if let literalArguments = self.arguments { - guard arguments != nil else { + public func expressionSQL(_ context: inout SQLGenerationContext) -> String { + if let arguments = arguments { + if context.appendArguments(arguments) == false { // GRDB limitation: we don't know how to look for `?` in sql and // replace them with with literals. fatalError("Not implemented") } - arguments! += literalArguments } if unsafeRaw { return sql @@ -84,7 +83,13 @@ public struct SQLExpressionLiteral : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return self + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return self } } @@ -137,8 +142,6 @@ public struct SQLUnaryOperator : Hashable { /// SQLExpressionUnary is an expression made of an unary operator and /// an operand expression. /// -/// SQLExpressionUnary(.not, Column("favorite")) -/// /// :nodoc: public struct SQLExpressionUnary : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -165,14 +168,20 @@ public struct SQLExpressionUnary : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&arguments) + public func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&context) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionUnary(op, expression.qualifiedExpression(with: qualifier)) + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionUnary(op, expression.qualifiedExpression(with: alias)) + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return SQLExpressionUnary(op, expression.resolvedExpression(inContext: context)) } } @@ -268,8 +277,8 @@ public struct SQLExpressionBinary : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return "(" + lhs.expressionSQL(&arguments) + " " + op.sql + " " + rhs.expressionSQL(&arguments) + ")" + public func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return "(" + lhs.expressionSQL(&context) + " " + op.sql + " " + rhs.expressionSQL(&context) + ")" } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -281,11 +290,157 @@ public struct SQLExpressionBinary : SQLExpression { return SQLExpressionNot(self) } } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionBinary(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias)) + } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func matchedRowIds(rowIdName: String?) -> Set? { - // FIXME: this implementation ignores column qualifiers + public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return SQLExpressionBinary(op, lhs.resolvedExpression(inContext: context), rhs.resolvedExpression(inContext: context)) + } +} + +// MARK: - SQLExpressionAnd + +struct SQLExpressionAnd : SQLExpression { + let expressions: [SQLExpression] + + init(_ expressions: [SQLExpression]) { + self.expressions = expressions + } + + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + guard let first = expressions.first else { + // Ruby [].all? # => true + return true.sqlExpression.expressionSQL(&context) + } + if expressions.count == 1 { + return first.expressionSQL(&context) + } + let expressionSQLs = expressions.map { $0.expressionSQL(&context) } + return "(" + expressionSQLs.joined(separator: " AND ") + ")" + } + + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionAnd(expressions.map { $0.qualifiedExpression(with: alias) }) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return SQLExpressionAnd(expressions.map { $0.resolvedExpression(inContext: context) }) + } + + func matchedRowIds(rowIdName: String?) -> Set? { + let matchedRowIds = expressions.compactMap { + $0.matchedRowIds(rowIdName: rowIdName) + } + guard let first = matchedRowIds.first else { + return nil + } + return matchedRowIds.suffix(from: 1).reduce(into: first) { $0.formIntersection($1) } + } +} + +// MARK: - SQLExpressionOr + +struct SQLExpressionOr : SQLExpression { + let expressions: [SQLExpression] + + init(_ expressions: [SQLExpression]) { + self.expressions = expressions + } + + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + guard let first = expressions.first else { + // Ruby [].any? # => false + return false.sqlExpression.expressionSQL(&context) + } + if expressions.count == 1 { + return first.expressionSQL(&context) + } + let expressionSQLs = expressions.map { $0.expressionSQL(&context) } + return "(" + expressionSQLs.joined(separator: " OR ") + ")" + } + + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionOr(expressions.map { $0.qualifiedExpression(with: alias) }) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return SQLExpressionOr(expressions.map { $0.resolvedExpression(inContext: context) }) + } + + func matchedRowIds(rowIdName: String?) -> Set? { + if expressions.isEmpty { + return [] + } + var result: Set = [] + for expr in expressions { + guard let matchedRowIds = expr.matchedRowIds(rowIdName: rowIdName) else { + return nil + } + result.formUnion(matchedRowIds) + } + return result + } +} + +// MARK: - SQLExpressionEqual + +struct SQLExpressionEqual: SQLExpression { + var lhs: SQLExpression + var rhs: SQLExpression + var op: Operator + + init(_ op: Operator, _ lhs: SQLExpression, _ rhs: SQLExpression) { + self.lhs = lhs + self.rhs = rhs + self.op = op + } + + enum Operator: String { + case equal = "=" + case notEqual = "<>" + case `is` = "IS" + case isNot = "IS NOT" + + var negated: Operator { + switch self { + case .equal: return .notEqual + case .notEqual: return .equal + case .is: return .isNot + case .isNot: return .is + } + } + } + + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return "(" + + lhs.expressionSQL(&context) + + " " + + op.rawValue + + " " + + rhs.expressionSQL(&context) + + ")" + } + + var negated: SQLExpression { + return SQLExpressionEqual(op.negated, lhs, rhs) + } + + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionEqual(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias)) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return SQLExpressionEqual(op, lhs.resolvedExpression(inContext: context), rhs.resolvedExpression(inContext: context)) + } + + func matchedRowIds(rowIdName: String?) -> Set? { + // FIXME: this implementation ignores column aliases switch op { case .equal, .is: // Look for `id ==/IS 1`, `rowid ==/IS 1`, `1 ==/IS id`, `1 ==/IS rowid` @@ -312,92 +467,10 @@ public struct SQLExpressionBinary : SQLExpression { return nil } - default: + case .notEqual, .isNot: return nil } } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionBinary(op, lhs.qualifiedExpression(with: qualifier), rhs.qualifiedExpression(with: qualifier)) - } -} - -// MARK: - SQLExpressionAnd - -struct SQLExpressionAnd : SQLExpression { - let expressions: [SQLExpression] - - init(_ expressions: [SQLExpression]) { - self.expressions = expressions - } - - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - guard let expression = expressions.first else { - // Ruby [].all? # => true - return true.sqlExpression.expressionSQL(&arguments) - } - if expressions.count == 1 { - return expression.expressionSQL(&arguments) - } - let expressionSQLs = expressions.map { $0.expressionSQL(&arguments) } - return "(" + expressionSQLs.joined(separator: " AND ") + ")" - } - - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionAnd(expressions.map { $0.qualifiedExpression(with: qualifier) }) - } - - func matchedRowIds(rowIdName: String?) -> Set? { - let matchedRowIds = expressions.compactMap { - $0.matchedRowIds(rowIdName: rowIdName) - } - guard let first = matchedRowIds.first else { - return nil - } - return matchedRowIds.suffix(from: 1).reduce(into: first) { $0.formIntersection($1) } - } -} - -// MARK: - SQLExpressionOr - -struct SQLExpressionOr : SQLExpression { - let expressions: [SQLExpression] - - init(_ expressions: [SQLExpression]) { - self.expressions = expressions - } - - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - guard let expression = expressions.first else { - // Ruby [].any? # => false - return false.sqlExpression.expressionSQL(&arguments) - } - if expressions.count == 1 { - return expression.expressionSQL(&arguments) - } - let expressionSQLs = expressions.map { $0.expressionSQL(&arguments) } - return "(" + expressionSQLs.joined(separator: " OR ") + ")" - } - - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionOr(expressions.map { $0.qualifiedExpression(with: qualifier) }) - } - - func matchedRowIds(rowIdName: String?) -> Set? { - if expressions.isEmpty { - return [] - } - var result: Set = [] - for expr in expressions { - guard let matchedRowIds = expr.matchedRowIds(rowIdName: rowIdName) else { - return nil - } - result.formUnion(matchedRowIds) - } - return result - } } // MARK: - SQLExpressionContains @@ -418,11 +491,11 @@ struct SQLExpressionContains : SQLExpression { self.isNegated = negated } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { + func expressionSQL(_ context: inout SQLGenerationContext) -> String { return "(" + - expression.expressionSQL(&arguments) + + expression.expressionSQL(&context) + (isNegated ? " NOT IN (" : " IN (") + - collection.collectionSQL(&arguments) + + collection.collectionSQL(&context) + "))" } @@ -430,9 +503,16 @@ struct SQLExpressionContains : SQLExpression { return SQLExpressionContains(expression, collection, negated: !isNegated) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionContains(expression.qualifiedExpression(with: alias), collection, negated: isNegated) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return SQLExpressionContains(expression.resolvedExpression(inContext: context), collection, negated: isNegated) + } + func matchedRowIds(rowIdName: String?) -> Set? { - // FIXME: this implementation ignores column qualifiers + // FIXME: this implementation ignores column aliases // Look for `id IN (1, 2, 3)` guard let column = expression as? ColumnExpression, let array = collection as? SQLExpressionsArray else @@ -444,7 +524,7 @@ struct SQLExpressionContains : SQLExpression { if let rowIdName = rowIdName { rowIdNames.append(rowIdName.lowercased()) } - + guard rowIdNames.contains(column.name.lowercased()) else { return nil } @@ -458,10 +538,6 @@ struct SQLExpressionContains : SQLExpression { } return rowIDs } - - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionContains(expression.qualifiedExpression(with: qualifier), collection, negated: isNegated) - } } // MARK: - SQLExpressionBetween @@ -484,13 +560,13 @@ struct SQLExpressionBetween : SQLExpression { self.isNegated = negated } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { + func expressionSQL(_ context: inout SQLGenerationContext) -> String { return "(" + - expression.expressionSQL(&arguments) + + expression.expressionSQL(&context) + (isNegated ? " NOT BETWEEN " : " BETWEEN ") + - lowerBound.expressionSQL(&arguments) + + lowerBound.expressionSQL(&context) + " AND " + - upperBound.expressionSQL(&arguments) + + upperBound.expressionSQL(&context) + ")" } @@ -498,11 +574,19 @@ struct SQLExpressionBetween : SQLExpression { return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return SQLExpressionBetween( - expression.qualifiedExpression(with: qualifier), - lowerBound.qualifiedExpression(with: qualifier), - upperBound.qualifiedExpression(with: qualifier), + expression.qualifiedExpression(with: alias), + lowerBound.qualifiedExpression(with: alias), + upperBound.qualifiedExpression(with: alias), + negated: isNegated) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return SQLExpressionBetween( + expression.resolvedExpression(inContext: context), + lowerBound.resolvedExpression(inContext: context), + upperBound.resolvedExpression(inContext: context), negated: isNegated) } } @@ -518,7 +602,7 @@ public struct SQLFunctionName : Hashable { /// The SQL function name /// /// :nodoc: - public let sql: String + public var sql: String /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// @@ -530,22 +614,6 @@ public struct SQLFunctionName : Hashable { public init(_ sql: String) { self.sql = sql } - - #if !swift(>=4.1) - /// The hash value - /// - /// :nodoc: - public var hashValue: Int { - return sql.hashValue - } - - /// Equality operator - /// - /// :nodoc: - public static func == (lhs: SQLFunctionName, rhs: SQLFunctionName) -> Bool { - return lhs.sql == rhs.sql - } - #endif } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -590,14 +658,20 @@ public struct SQLExpressionFunction : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return functionName.sql + "(" + (self.arguments.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") + ")" + public func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return functionName.sql + "(" + (self.arguments.map { $0.expressionSQL(&context) } as [String]).joined(separator: ", ") + ")" } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualifiedExpression(with: qualifier) }) + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualifiedExpression(with: alias) }) + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return SQLExpressionFunction(functionName, arguments: arguments.map { $0.resolvedExpression(inContext: context) }) } } @@ -615,12 +689,16 @@ struct SQLExpressionCount : SQLExpression { self.counted = counted } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return "COUNT(" + counted.countedSQL(&arguments) + ")" + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return "COUNT(" + counted.countedSQL(&context) + ")" } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionCount(counted.qualifiedSelectable(with: qualifier)) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionCount(counted.qualifiedSelectable(with: alias)) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return self } } @@ -637,12 +715,39 @@ struct SQLExpressionCountDistinct : SQLExpression { self.counted = counted } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return "COUNT(DISTINCT " + counted.expressionSQL(&arguments) + ")" + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return "COUNT(DISTINCT " + counted.expressionSQL(&context) + ")" } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionCountDistinct(counted.qualifiedExpression(with: qualifier)) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionCountDistinct(counted.qualifiedExpression(with: alias)) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return self + } +} + +// MARK: - TableMatchExpression + +struct TableMatchExpression: SQLExpression { + var alias: TableAlias + var pattern: SQLExpression + + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return "(" + context.resolvedName(for: alias).quotedDatabaseIdentifier + " MATCH " + pattern.expressionSQL(&context) + ")" + } + + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return TableMatchExpression( + alias: self.alias, + pattern: pattern.qualifiedExpression(with: alias)) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return TableMatchExpression( + alias: alias, + pattern: pattern.resolvedExpression(inContext: context)) } } @@ -661,8 +766,8 @@ struct SQLExpressionCollate : SQLExpression { self.collationName = collationName } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - let sql = expression.expressionSQL(&arguments) + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + let sql = expression.expressionSQL(&context) if sql.last! == ")" { return String(sql.prefix(upTo: sql.index(sql.endIndex, offsetBy: -1))) + " COLLATE " + collationName.rawValue + ")" } else { @@ -670,7 +775,11 @@ struct SQLExpressionCollate : SQLExpression { } } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionCollate(expression.qualifiedExpression(with: qualifier), collationName: collationName) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionCollate(expression.qualifiedExpression(with: alias), collationName: collationName) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return SQLExpressionCollate(expression.resolvedExpression(inContext: context), collationName: collationName) } } diff --git a/GRDB/QueryInterface/SQLExpression.swift b/GRDB/QueryInterface/SQLExpression.swift index b41be52db..4d491ebca 100644 --- a/GRDB/QueryInterface/SQLExpression.swift +++ b/GRDB/QueryInterface/SQLExpression.swift @@ -23,22 +23,7 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns an SQL string that represents the expression. - /// - /// When the arguments parameter is nil, any value must be written down as - /// a literal in the returned SQL: - /// - /// var arguments: StatementArguments? = nil - /// let expression = "foo'bar".databaseValue - /// expression.expressionSQL(&arguments) // "'foo''bar'" - /// - /// When the arguments parameter is not nil, then values may be replaced by - /// `?` or colon-prefixed tokens, and fed into arguments. - /// - /// var arguments = StatementArguments() - /// let expression = "foo'bar".databaseValue - /// expression.expressionSQL(&arguments) // "?" - /// arguments // ["foo'bar"] - func expressionSQL(_ arguments: inout StatementArguments?) -> String + func expressionSQL(_ context: inout SQLGenerationContext) -> String /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// @@ -59,10 +44,13 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns the rowIds matched by the expression. - func matchedRowIds(rowIdName: String?) -> Set? // TODO: this method should take SQLTableQualifier in account + func matchedRowIds(rowIdName: String?) -> Set? // FIXME: this method should take TableAlias in account /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression + func qualifiedExpression(with alias: TableAlias) -> SQLExpression + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression } extension SQLExpression { @@ -93,8 +81,17 @@ extension SQLExpression { /// The default implementation returns qualifiedExpression(with:) /// /// :nodoc: - public func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { - return qualifiedExpression(with: qualifier) + public func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + return qualifiedExpression(with: alias) + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// The default implementation returns qualifiedExpression(with:) + /// + /// :nodoc: + public func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { + return qualifiedExpression(with: alias) } } @@ -139,15 +136,19 @@ struct SQLExpressionNot : SQLExpression { self.expression = expression } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return "NOT \(expression.expressionSQL(&arguments))" + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return "NOT \(expression.expressionSQL(&context))" } var negated: SQLExpression { return expression } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionNot(expression.qualifiedExpression(with: qualifier)) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionNot(expression.qualifiedExpression(with: alias)) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return SQLExpressionNot(expression.resolvedExpression(inContext: context)) } } diff --git a/GRDB/QueryInterface/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGenerationContext.swift new file mode 100644 index 000000000..9e8590fa9 --- /dev/null +++ b/GRDB/QueryInterface/SQLGenerationContext.swift @@ -0,0 +1,265 @@ +/// SQLGenerationContext is responsible for preventing SQL injection and +/// disambiguating table names when GRDB generates SQL queries. +public struct SQLGenerationContext { + private(set) var arguments: StatementArguments? + private var resolvedNames: [TableAlias: String] + private var qualifierNeeded: Bool + + /// Used for SQLExpression -> SQLExpressionLiteral conversion + static func literalGenerationContext(withArguments: Bool) -> SQLGenerationContext { + return SQLGenerationContext( + arguments: withArguments ? [] : nil, + resolvedNames: [:], + qualifierNeeded: false) + } + + /// Used for QueryInterfaceQuery.makeSelectStatement() and QueryInterfaceQuery.makeDeleteStatement() + static func queryGenerationContext(aliases: [TableAlias]) -> SQLGenerationContext { + return SQLGenerationContext( + arguments: [], + resolvedNames: aliases.resolvedNames, + qualifierNeeded: aliases.count > 1) + } + + /// Used for TableRecord.selectionSQL + static func recordSelectionGenerationContext(alias: TableAlias) -> SQLGenerationContext { + return SQLGenerationContext( + arguments: nil, + resolvedNames: [:], + qualifierNeeded: true) + } + + /// Returns whether arguments could be appended + mutating func appendArguments(_ newArguments: StatementArguments) -> Bool { + guard let arguments = arguments else { + return false + } + self.arguments = arguments + newArguments + return true + } + + /// May be nil, when a qualifier is not needed: + /// + /// WHERE .column == 1 + /// SELECT .* + /// + /// WHERE column == 1 + /// SELECT * + func qualifier(for alias: TableAlias) -> String? { + if alias.hasUserName { + return alias.identityName + } + if qualifierNeeded == false { + return nil + } + return resolvedName(for: alias) + } + + /// WHERE MATCH pattern + func resolvedName(for alias: TableAlias) -> String { + return resolvedNames[alias.root] ?? alias.identityName + } + + /// FROM tableName + func aliasName(for alias: TableAlias) -> String? { + let resolvedName = self.resolvedName(for: alias) + if resolvedName != alias.tableName { + return resolvedName + } + return nil + } +} + +// MARK: - TableAlias + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +public class TableAlias: Hashable { + private enum Impl { + /// A TableAlias is undefined when it is created by the GRDB user: + /// + /// let alias = TableAlias() + /// let alias = TableAlias(name: "player") + case undefined(userName: String?) + + /// A TableAlias is a table when explicitly specified: + /// + /// let alias = TableAlias(tableName: "player") + /// + /// Or when it has been qualified by a request: + /// + /// let alias = TableAlias() + /// let request = Player.all().aliased(alias) + case table(tableName: String, userName: String?) + case derived(TableAlias) + } + private var impl: Impl + + // exposed for SQLGenerationContext and expression.resolvedExpression + var root: TableAlias { + if case .derived(let base) = impl { + return base.root + } else { + return self + } + } + + // exposed to SQLGenerationContext + fileprivate var identityName: String { + return userName ?? tableName + } + + // exposed to SQLGenerationContext + fileprivate var hasUserName: Bool { + return userName != nil + } + + var tableName: String { + switch impl { + case .undefined: + fatalError("Undefined alias has no table name") + case .table(tableName: let tableName, userName: _): + return tableName + case .derived(let base): + return base.tableName + } + } + + private var userName: String? { + switch impl { + case .undefined(let userName): + return userName + case .table(tableName: _, userName: let userName): + return userName + case .derived(let base): + return base.userName + } + } + + public init(name: String? = nil) { + self.impl = .undefined(userName: name) + } + + init(tableName: String, userName: String? = nil) { + self.impl = .table(tableName: tableName, userName: userName) + } + + func rebase(on base: TableAlias) { + switch impl { + case .undefined(let userName): + if let userName = userName { + // rename + base.setUserName(userName) + } + self.impl = .derived(base) + default: + fatalError("Not implemented") + } + } + + func setUserName(_ userName: String) { + switch impl { + case .undefined: + self.impl = .undefined(userName: userName) + case .table(tableName: let tableName, userName: _): + self.impl = .table(tableName: tableName, userName: userName) + case .derived(let base): + base.setUserName(userName) + } + } + + func setTableName(_ tableName: String) { + switch impl { + case .undefined(let userName): + self.impl = .table(tableName: tableName, userName: userName) + case .table(tableName: let initialTableName, userName: _): + GRDBPrecondition(tableName.lowercased() == initialTableName.lowercased(), "Can't change table name of a table alias") + case .derived(let base): + base.setTableName(tableName) + } + } + + /// Returns a qualified value that is able to resolve ambiguities in + /// joined queries. + public subscript(_ selectable: SQLSelectable) -> SQLSelectable { + return selectable.qualifiedSelectable(with: self) + } + + /// Returns a qualified expression that is able to resolve ambiguities in + /// joined queries. + public subscript(_ expression: SQLExpression) -> SQLExpression { + return expression.qualifiedExpression(with: self) + } + + /// :nodoc: + public var hashValue: Int { + if case .derived(let base) = impl { + return base.hashValue + } else { + return ObjectIdentifier(self).hashValue + } + } + + /// :nodoc: + public static func == (lhs: TableAlias, rhs: TableAlias) -> Bool { + return ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root) + } +} + +extension Array where Element == TableAlias { + /// Resolve ambiguities in aliases' names. + fileprivate var resolvedNames: [TableAlias: String] { + let aliases = map { $0.root } + + // It is a programmer error to reuse the same (===) TableAlias for + // multiple tables. + GRDBPrecondition(aliases.count == Set(aliases).count, "A TableAlias most not be used to refer to multiple tables") + + let groups = Dictionary.init(grouping: aliases) { + $0.identityName.lowercased() + } + + var uniqueLowercaseNames: Set = [] + var ambiguousGroups: [[TableAlias]] = [] + + for (lowercaseName, group) in groups { + if group.count > 1 { + // It is a programmer error to reuse the same alias for multiple tables + GRDBPrecondition(group.filter({ $0.hasUserName }).count < 2, "ambiguous alias: \(group[0].identityName)") + ambiguousGroups.append(group) + } else { + uniqueLowercaseNames.insert(lowercaseName) + } + } + + var resolvedNames: [TableAlias: String] = [:] + for group in ambiguousGroups { + var index = 1 + for alias in group { + if alias.hasUserName { continue } + let radical = alias.identityName.databaseQualifierRadical + var resolvedName: String + repeat { + resolvedName = "\(radical)\(index)" + index += 1 + } while uniqueLowercaseNames.contains(resolvedName.lowercased()) + uniqueLowercaseNames.insert(resolvedName.lowercased()) + resolvedNames[alias] = resolvedName + } + } + return resolvedNames + } +} + +extension String { + /// "bar" => "bar" + /// "foo12" => "foo" + var databaseQualifierRadical: String { + let digits: ClosedRange = "0"..."9" + let radicalEndIndex = self // "foo12" + .reversed() // "21oof" + .prefix(while: { digits.contains($0) }) // "21" + .endIndex // reversed(foo^12) + .base // foo^12 + return String(prefix(upTo: radicalEndIndex)) + } +} diff --git a/GRDB/QueryInterface/SQLOrdering.swift b/GRDB/QueryInterface/SQLOrdering.swift index e3e8624ba..51e944bee 100644 --- a/GRDB/QueryInterface/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQLOrdering.swift @@ -15,22 +15,10 @@ public protocol SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns an SQL string that represents the ordering term. - /// - /// When the arguments parameter is nil, any value must be written down as - /// a literal in the returned SQL: - /// - /// var arguments: StatementArguments? = nil - /// let orderingTerm = Column("name") ?? "Anonymous" - /// orderingTerm.orderingTermSQL(&arguments) // "IFNULL(name, 'Anonymous')" - /// - /// When the arguments parameter is not nil, then values may be replaced by - /// `?` or colon-prefixed tokens, and fed into arguments. - /// - /// var arguments = StatementArguments() - /// let orderingTerm = Column("name") ?? "Anonymous" - /// orderingTerm.orderingTermSQL(&arguments) // "IFNULL(name, ?)" - /// arguments // ["Anonymous"] - func orderingTermSQL(_ arguments: inout StatementArguments?) -> String + func orderingTermSQL(_ context: inout SQLGenerationContext) -> String + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm } // MARK: - SQLOrdering @@ -48,12 +36,21 @@ enum SQLOrdering : SQLOrderingTerm { } } - func orderingTermSQL(_ arguments: inout StatementArguments?) -> String { + func orderingTermSQL(_ context: inout SQLGenerationContext) -> String { switch self { case .asc(let expression): - return expression.expressionSQL(&arguments) + " ASC" + return expression.expressionSQL(&context) + " ASC" case .desc(let expression): - return expression.expressionSQL(&arguments) + " DESC" + return expression.expressionSQL(&context) + " DESC" + } + } + + func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { + switch self { + case .asc(let expression): + return SQLOrdering.asc(expression.qualifiedExpression(with: alias)) + case .desc(let expression): + return SQLOrdering.desc(expression.qualifiedExpression(with: alias)) } } } diff --git a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift index 0e45abddd..411b88829 100644 --- a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift @@ -8,11 +8,11 @@ /// For example: /// /// struct Player : TableRecord { -/// static var databaseTableName = "players" +/// static var databaseTableName = "player" /// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] /// } /// -/// // SELECT *, rowid FROM players +/// // SELECT *, rowid FROM player /// let request = Player.all() public struct AllColumns { public init() { } @@ -21,13 +21,13 @@ public struct AllColumns { extension AllColumns : SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { + public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { return "*" } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func countedSQL(_ arguments: inout StatementArguments?) -> String { + public func countedSQL(_ context: inout SQLGenerationContext) -> String { return "*" } @@ -47,14 +47,14 @@ extension AllColumns : SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { - return QualifiedAllColumns(qualifier: qualifier) + public func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + return QualifiedAllColumns(alias: alias) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func columnCount(_ db: Database) throws -> Int { - fatalError("Can't compute number of columns without a qualifier") + fatalError("Can't compute number of columns without an alias") } } @@ -62,37 +62,40 @@ extension AllColumns : SQLSelectable { /// QualifiedAllColumns is the `t.*` in `SELECT t.*`. struct QualifiedAllColumns { - private let qualifier: SQLTableQualifier + private let alias: TableAlias - init(qualifier: SQLTableQualifier) { - self.qualifier = qualifier + init(alias: TableAlias) { + self.alias = alias } } extension QualifiedAllColumns : SQLSelectable { - func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - if let qualifierName = qualifier.name { - return qualifierName.quotedDatabaseIdentifier + ".*" + func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { + if let qualifier = context.qualifier(for: alias) { + return qualifier.quotedDatabaseIdentifier + ".*" } return "*" } - func countedSQL(_ arguments: inout StatementArguments?) -> String { - // SELECT COUNT(t.*) is invalid SQL - fatalError("Not implemented, or invalid query") + func countedSQL(_ context: inout SQLGenerationContext) -> String { + if context.qualifier(for: alias) != nil { + // SELECT COUNT(t.*) is invalid SQL + fatalError("Not implemented, or invalid query") + } + return "*" } func count(distinct: Bool) -> SQLCount? { return nil } - func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { + func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { // Never requalify return self } func columnCount(_ db: Database) throws -> Int { - return try db.columns(in: qualifier.tableName).count + return try db.columns(in: alias.tableName).count } } @@ -100,27 +103,27 @@ extension QualifiedAllColumns : SQLSelectable { struct SQLAliasedExpression : SQLSelectable { let expression: SQLExpression - let alias: String + let name: String - init(_ expression: SQLExpression, alias: String) { + init(_ expression: SQLExpression, name: String) { self.expression = expression - self.alias = alias + self.name = name } - func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - return expression.resultColumnSQL(&arguments) + " AS " + alias.quotedDatabaseIdentifier + func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { + return expression.resultColumnSQL(&context) + " AS " + name.quotedDatabaseIdentifier } - func countedSQL(_ arguments: inout StatementArguments?) -> String { - return expression.countedSQL(&arguments) + func countedSQL(_ context: inout SQLGenerationContext) -> String { + return expression.countedSQL(&context) } func count(distinct: Bool) -> SQLCount? { return expression.count(distinct: distinct) } - func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { - return SQLAliasedExpression(expression.qualifiedExpression(with: qualifier), alias: alias) + func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + return SQLAliasedExpression(expression.qualifiedExpression(with: alias), name: name) } func columnCount(_ db: Database) throws -> Int { diff --git a/GRDB/QueryInterface/SQLSelectable.swift b/GRDB/QueryInterface/SQLSelectable.swift index 48dd59720..bbc0e43a9 100644 --- a/GRDB/QueryInterface/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQLSelectable.swift @@ -8,10 +8,10 @@ /// :nodoc: public protocol SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func resultColumnSQL(_ arguments: inout StatementArguments?) -> String + func resultColumnSQL(_ context: inout SQLGenerationContext) -> String /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func countedSQL(_ arguments: inout StatementArguments?) -> String + func countedSQL(_ context: inout SQLGenerationContext) -> String /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) func count(distinct: Bool) -> SQLCount? @@ -20,7 +20,7 @@ public protocol SQLSelectable { func columnCount(_ db: Database) throws -> Int /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable + func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable } // MARK: - SQLSelectionLiteral @@ -34,19 +34,18 @@ struct SQLSelectionLiteral : SQLSelectable { self.arguments = arguments } - func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - if let literalArguments = self.arguments { - guard arguments != nil else { + func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { + if let arguments = arguments { + if context.appendArguments(arguments) == false { // GRDB limitation: we don't know how to look for `?` in sql and // replace them with with literals. fatalError("Not implemented") } - arguments! += literalArguments } return sql } - func countedSQL(_ arguments: inout StatementArguments?) -> String { + func countedSQL(_ context: inout SQLGenerationContext) -> String { fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.") } @@ -58,30 +57,11 @@ struct SQLSelectionLiteral : SQLSelectable { fatalError("Selection literals don't known how many columns they contain. To resolve this error, select one or several SQLExpressionLiteral instead.") } - func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { + func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { return self } } -// MARK: - SQLTableQualifier - -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// :nodoc: -public class SQLTableQualifier { - var tableName: String - private var alias: String? - - init(tableName: String, alias: String?) { - self.tableName = tableName - self.alias = alias - } - - var name: String? { - return alias - } -} - // MARK: - Counting /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) diff --git a/GRDB/QueryInterface/SQLSpecificExpressible+QueryInterface.swift b/GRDB/QueryInterface/SQLSpecificExpressible+QueryInterface.swift index ffe8c1735..fd56ad41d 100644 --- a/GRDB/QueryInterface/SQLSpecificExpressible+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSpecificExpressible+QueryInterface.swift @@ -25,8 +25,8 @@ extension SQLSpecificExpressible { /// Returns a value that can be used as an argument to QueryInterfaceRequest.select() /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func aliased(_ alias: String) -> SQLSelectable { - return SQLAliasedExpression(sqlExpression, alias: alias) + public func aliased(_ name: String) -> SQLSelectable { + return SQLAliasedExpression(sqlExpression, name: name) } } diff --git a/GRDB/QueryInterface/Support/SQLOperators.swift b/GRDB/QueryInterface/Support/SQLOperators.swift index f0e8a78db..0dd16b0f2 100644 --- a/GRDB/QueryInterface/Support/SQLOperators.swift +++ b/GRDB/QueryInterface/Support/SQLOperators.swift @@ -1,38 +1,24 @@ // MARK: - Egality and Identity Operators (=, <>, IS, IS NOT) -extension SQLBinaryOperator { - /// The `=` binary operator - static let equal = SQLBinaryOperator("=", negated: "<>") - - /// The `<>` binary operator - static let notEqual = SQLBinaryOperator("<>", negated: "=") - - /// The `IS` binary operator - static let `is` = SQLBinaryOperator("IS", negated: "IS NOT") - - /// The `IS NOT` binary operator - static let isNot = SQLBinaryOperator("IS NOT", negated: "IS") -} - // Outputs "x = y" or "x IS NULL" private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression { switch (lhs, rhs) { case (let lhs, let rhs as DatabaseValue): switch rhs.storage { case .null: - return SQLExpressionBinary(.is, lhs, DatabaseValue.null) + return SQLExpressionEqual(.is, lhs, rhs) default: - return SQLExpressionBinary(.equal, lhs, rhs) + return SQLExpressionEqual(.equal, lhs, rhs) } case (let lhs as DatabaseValue, let rhs): switch lhs.storage { case .null: - return SQLExpressionBinary(.is, rhs, DatabaseValue.null) + return SQLExpressionEqual(.is, rhs, lhs) default: - return SQLExpressionBinary(.equal, lhs, rhs) + return SQLExpressionEqual(.equal, lhs, rhs) } default: - return SQLExpressionBinary(.equal, lhs, rhs) + return SQLExpressionEqual(.equal, lhs, rhs) } } @@ -229,7 +215,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // name IS 'Arthur' /// Column("name") === "Arthur" public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - return SQLExpressionBinary(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) + return SQLExpressionEqual(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -246,9 +232,9 @@ public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress /// "Arthur" === Column("name") public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { if let lhs = lhs { - return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression) } else { - return SQLExpressionBinary(.is, rhs.sqlExpression, DatabaseValue.null) + return SQLExpressionEqual(.is, rhs.sqlExpression, DatabaseValue.null) } } @@ -265,7 +251,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress /// // email IS login /// Column("email") === Column("login") public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -273,7 +259,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ /// // name IS NOT 'Arthur' /// Column("name") !== "Arthur" public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - return SQLExpressionBinary(.isNot, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) + return SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -290,9 +276,9 @@ public func !== (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress /// "Arthur" !== Column("name") public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { if let lhs = lhs { - return SQLExpressionBinary(.isNot, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) } else { - return SQLExpressionBinary(.isNot, rhs.sqlExpression, DatabaseValue.null) + return SQLExpressionEqual(.isNot, rhs.sqlExpression, DatabaseValue.null) } } @@ -309,7 +295,7 @@ public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress /// // email IS NOT login /// Column("email") !== Column("login") public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.isNot, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) } @@ -768,7 +754,7 @@ extension Sequence where Element == SQLExpression { /// /// For example: /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// // WHERE (registered /// // AND (score >= 1000) /// // AND (name IS NOT NULL)) @@ -781,10 +767,10 @@ extension Sequence where Element == SQLExpression { /// When the sequence is empty, `joined(operator: .and)` returns true, /// and `joined(operator: .or)` returns false: /// - /// // SELECT * FROM players WHERE 1 + /// // SELECT * FROM player WHERE 1 /// Player.filter([].joined(operator: .and)) /// - /// // SELECT * FROM players WHERE 0 + /// // SELECT * FROM player WHERE 0 /// Player.filter([].joined(operator: .or)) public func joined(operator: SQLLogicalBinaryOperator) -> SQLExpression { let expressions = Array(self) diff --git a/GRDB/QueryInterface/TableDefinition.swift b/GRDB/QueryInterface/TableDefinition.swift index 1602b707e..ca8b231df 100644 --- a/GRDB/QueryInterface/TableDefinition.swift +++ b/GRDB/QueryInterface/TableDefinition.swift @@ -5,7 +5,7 @@ extension Database { #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Creates a database table. /// - /// try db.create(table: "pointOfInterests") { t in + /// try db.create(table: "place") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// t.column("favorite", .boolean).notNull().default(false) @@ -34,7 +34,7 @@ extension Database { #else /// Creates a database table. /// - /// try db.create(table: "pointOfInterests") { t in + /// try db.create(table: "place") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// t.column("favorite", .boolean).notNull().default(false) @@ -66,7 +66,7 @@ extension Database { /// Creates a database table. /// - /// try db.create(table: "pointOfInterests") { t in + /// try db.create(table: "place") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// t.column("favorite", .boolean).notNull().default(false) @@ -103,7 +103,7 @@ extension Database { /// Modifies a database table. /// - /// try db.alter(table: "players") { t in + /// try db.alter(table: "player") { t in /// t.add(column: "url", .text) /// } /// @@ -223,7 +223,7 @@ extension Database { /// You don't create instances of this class. Instead, you use the Database /// `create(table:)` method: /// -/// try db.create(table: "players") { t in // t is TableDefinition +/// try db.create(table: "player") { t in // t is TableDefinition /// t.column(...) /// } /// @@ -250,7 +250,7 @@ public final class TableDefinition { /// Defines the auto-incremented primary key. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.autoIncrementedPrimaryKey("id") /// } /// @@ -282,7 +282,7 @@ public final class TableDefinition { /// Appends a table column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("name", .text) /// } /// @@ -301,7 +301,7 @@ public final class TableDefinition { /// Defines the table primary key. /// - /// try db.create(table: "citizenships") { t in + /// try db.create(table: "citizenship") { t in /// t.column("citizenID", .integer) /// t.column("countryCode", .text) /// t.primaryKey(["citizenID", "countryCode"]) @@ -323,7 +323,7 @@ public final class TableDefinition { /// Adds a unique key. /// - /// try db.create(table: "pointOfInterests") { t in + /// try db.create(table: "place") { t in /// t.column("latitude", .double) /// t.column("longitude", .double) /// t.uniqueKey(["latitude", "longitude"]) @@ -344,7 +344,7 @@ public final class TableDefinition { /// t.column("issueDate", .date) /// t.column("citizenID", .integer) /// t.column("countryCode", .text) - /// t.foreignKey(["citizenID", "countryCode"], references: "citizenships", onDelete: .cascade) + /// t.foreignKey(["citizenID", "countryCode"], references: "citizenship", onDelete: .cascade) /// } /// /// See https://www.sqlite.org/foreignkeys.html @@ -365,7 +365,7 @@ public final class TableDefinition { /// Adds a CHECK constraint. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("personalPhone", .text) /// t.column("workPhone", .text) /// let personalPhone = Column("personalPhone") @@ -382,7 +382,7 @@ public final class TableDefinition { /// Adds a CHECK constraint. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("personalPhone", .text) /// t.column("workPhone", .text) /// t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL") @@ -509,7 +509,7 @@ public final class TableDefinition { /// You don't create instances of this class. Instead, you use the Database /// `alter(table:)` method: /// -/// try db.alter(table: "players") { t in // t is TableAlteration +/// try db.alter(table: "player") { t in // t is TableAlteration /// t.add(column: ...) /// } /// @@ -524,7 +524,7 @@ public final class TableAlteration { /// Appends a column to the table. /// - /// try db.alter(table: "players") { t in + /// try db.alter(table: "player") { t in /// t.add(column: "url", .text) /// } /// @@ -566,11 +566,11 @@ public final class TableAlteration { /// /// You get instances of this class when you create or alter a database table: /// -/// try db.create(table: "players") { t in +/// try db.create(table: "player") { t in /// t.column(...) // ColumnDefinition /// } /// -/// try db.alter(table: "players") { t in +/// try db.alter(table: "player") { t in /// t.add(column: ...) // ColumnDefinition /// } /// @@ -599,7 +599,7 @@ public final class ColumnDefinition { /// Adds a primary key constraint on the column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("id", .integer).primaryKey() /// } /// @@ -619,7 +619,7 @@ public final class ColumnDefinition { /// Adds a NOT NULL constraint on the column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("name", .text).notNull() /// } /// @@ -636,7 +636,7 @@ public final class ColumnDefinition { /// Adds a UNIQUE constraint on the column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("email", .text).unique() /// } /// @@ -653,7 +653,7 @@ public final class ColumnDefinition { /// Adds an index of the column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("email", .text).indexed() /// } /// @@ -670,7 +670,7 @@ public final class ColumnDefinition { /// Adds a CHECK constraint on the column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("name", .text).check { length($0) > 0 } /// } /// @@ -687,7 +687,7 @@ public final class ColumnDefinition { /// Adds a CHECK constraint on the column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("name", .text).check(sql: "LENGTH(name) > 0") /// } /// @@ -705,7 +705,7 @@ public final class ColumnDefinition { /// Defines the default column value. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("name", .text).defaults(to: "Anonymous") /// } /// @@ -721,7 +721,7 @@ public final class ColumnDefinition { /// Defines the default column value. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP") /// } /// @@ -739,7 +739,7 @@ public final class ColumnDefinition { // Defines the default column collation. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("email", .text).collate(.nocase) /// } /// @@ -755,7 +755,7 @@ public final class ColumnDefinition { // Defines the default column collation. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("name", .text).collate(.localizedCaseInsensitiveCompare) /// } /// @@ -771,8 +771,8 @@ public final class ColumnDefinition { /// Defines a foreign key. /// - /// try db.create(table: "books") { t in - /// t.column("authorId", .integer).references("authors", onDelete: .cascade) + /// try db.create(table: "book") { t in + /// t.column("authorId", .integer).references("author", onDelete: .cascade) /// } /// /// See https://www.sqlite.org/foreignkeys.html diff --git a/GRDB/QueryInterface/VirtualTableModule.swift b/GRDB/QueryInterface/VirtualTableModule.swift index 053460a3b..3814a1132 100644 --- a/GRDB/QueryInterface/VirtualTableModule.swift +++ b/GRDB/QueryInterface/VirtualTableModule.swift @@ -2,7 +2,7 @@ /// the `Database.create(virtualTable:using:)` method: /// /// let module = ... -/// try db.create(virtualTable: "items", using: module) { t in +/// try db.create(virtualTable: "item", using: module) { t in /// ... /// } /// @@ -13,7 +13,7 @@ public protocol VirtualTableModule { /// The type of the closure argument in the /// `Database.create(virtualTable:using:)` method: /// - /// try db.create(virtualTable: "items", using: module) { t in + /// try db.create(virtualTable: "item", using: module) { t in /// // t is TableDefinition /// } associatedtype TableDefinition @@ -24,7 +24,7 @@ public protocol VirtualTableModule { /// Returns a table definition that is passed as the closure argument in the /// `Database.create(virtualTable:using:)` method: /// - /// try db.create(virtualTable: "items", using: module) { t in + /// try db.create(virtualTable: "item", using: module) { t in /// // t is the result of makeTableDefinition() /// } func makeTableDefinition() -> TableDefinition @@ -70,7 +70,7 @@ extension Database { /// Creates a virtual database table. /// /// let module = ... - /// try db.create(virtualTable: "pointOfInterests", using: module) { t in + /// try db.create(virtualTable: "book", using: module) { t in /// ... /// } /// @@ -80,7 +80,7 @@ extension Database { /// Use this method to create full-text tables using the FTS3, FTS4, or /// FTS5 modules: /// - /// try db.create(virtualTable: "books", using: FTS4()) { t in + /// try db.create(virtualTable: "book", using: FTS4()) { t in /// t.column("title") /// t.column("author") /// t.column("body") diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index e6135260c..44e510cfa 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -273,4 +273,3 @@ extension FetchableRecord where Self: Decodable { try! self.init(from: RowDecoder(row: row, codingPath: [])) } } - diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index 9cda45372..937736486 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -4,7 +4,7 @@ extension FetchableRecord where Self: TableRecord { /// A cursor over all records fetched from the database. /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// let players = try Player.fetchCursor(db) // Cursor of Player /// while let player = try players.next() { // Player /// ... @@ -30,7 +30,7 @@ extension FetchableRecord where Self: TableRecord { /// An array of all records fetched from the database. /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// let players = try Player.fetchAll(db) // [Player] /// /// The selection defaults to all columns. This default can be changed for @@ -45,7 +45,7 @@ extension FetchableRecord where Self: TableRecord { /// The first found record. /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// let player = try Player.fetchOne(db) // Player? /// /// The selection defaults to all columns. This default can be changed for diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 31cc9bd1b..b4212b398 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -36,7 +36,7 @@ public protocol FetchableRecord { /// /// struct Player : FetchableRecord { ... } /// try dbQueue.read { db in -/// let players: RecordCursor = try Player.fetchCursor(db, "SELECT * FROM players") +/// let players: RecordCursor = try Player.fetchCursor(db, "SELECT * FROM player") /// } public final class RecordCursor : Cursor { private let statement: SelectStatement @@ -73,7 +73,7 @@ extension FetchableRecord { /// A cursor over records fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement("SELECT * FROM players") + /// let statement = try db.makeSelectStatement("SELECT * FROM player") /// let players = try Player.fetchCursor(statement) // Cursor of Player /// while let player = try players.next() { // Player /// ... @@ -96,7 +96,7 @@ extension FetchableRecord { /// Returns an array of records fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement("SELECT * FROM players") + /// let statement = try db.makeSelectStatement("SELECT * FROM player") /// let players = try Player.fetchAll(statement) // [Player] /// /// - parameters: @@ -111,7 +111,7 @@ extension FetchableRecord { /// Returns a single record fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement("SELECT * FROM players") + /// let statement = try db.makeSelectStatement("SELECT * FROM player") /// let player = try Player.fetchOne(statement) // Player? /// /// - parameters: @@ -131,7 +131,7 @@ extension FetchableRecord { /// Returns a cursor over records fetched from an SQL query. /// - /// let players = try Player.fetchCursor(db, "SELECT * FROM players") // Cursor of Player + /// let players = try Player.fetchCursor(db, "SELECT * FROM player") // Cursor of Player /// while let player = try players.next() { // Player /// ... /// } @@ -154,7 +154,7 @@ extension FetchableRecord { /// Returns an array of records fetched from an SQL query. /// - /// let players = try Player.fetchAll(db, "SELECT * FROM players") // [Player] + /// let players = try Player.fetchAll(db, "SELECT * FROM player") // [Player] /// /// - parameters: /// - db: A database connection. @@ -169,7 +169,7 @@ extension FetchableRecord { /// Returns a single record fetched from an SQL query. /// - /// let player = try Player.fetchOne(db, "SELECT * FROM players") // Player? + /// let player = try Player.fetchOne(db, "SELECT * FROM player") // Player? /// /// - parameters: /// - db: A database connection. diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 38cbb0118..904895c9c 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -18,7 +18,7 @@ public final class FetchedRecordsController { /// /// let controller = FetchedRecordsController( /// dbQueue, - /// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name", + /// sql: "SELECT * FROM wine WHERE color = ? ORDER BY name", /// arguments: [Color.red], /// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id }) /// @@ -402,17 +402,17 @@ extension FetchedRecordsController where Record: TableRecord { /// /// let controller = FetchedRecordsController( /// dbQueue, - /// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name", + /// sql: "SELECT * FROM wine WHERE color = ? ORDER BY name", /// arguments: [Color.red]) /// /// The records are compared by primary key (single-column primary key, /// compound primary key, or implicit rowid). For a database table which /// has an `id` primary key, this initializer is equivalent to: /// - /// // Assuming the wines table has an `id` primary key: + /// // Assuming the wine table has an `id` primary key: /// let controller = FetchedRecordsController( /// dbQueue, - /// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name", + /// sql: "SELECT * FROM wine WHERE color = ? ORDER BY name", /// arguments: [Color.red], /// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id }) /// @@ -451,7 +451,7 @@ extension FetchedRecordsController where Record: TableRecord { /// compound primary key, or implicit rowid). For a database table which /// has an `id` primary key, this initializer is equivalent to: /// - /// // Assuming the wines table has an `id` primary key: + /// // Assuming the wine table has an `id` primary key: /// let controller = FetchedRecordsController( /// dbQueue, /// request: request, @@ -1049,4 +1049,3 @@ private final class Item : FetchableRecord, Equatable { return lhs.row == rhs.row } } - diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 389035274..b33cd862b 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -126,6 +126,15 @@ public struct PersistenceContainer { } } + // Returns nil if column is not defined + func value(forCaseInsensitiveColumn column: String) -> DatabaseValue? { + let lowercaseColumn = column.lowercased() + for (key, value) in storage where key.lowercased() == lowercaseColumn { + return value?.databaseValue ?? .null + } + return nil + } + var isEmpty: Bool { return storage.isEmpty } @@ -614,16 +623,16 @@ extension MutablePersistableRecord { /// Delete records identified by their primary keys; returns the number of /// deleted rows. /// - /// // DELETE FROM players WHERE id IN (1, 2, 3) + /// // DELETE FROM player WHERE id IN (1, 2, 3) /// try Player.deleteAll(db, keys: [1, 2, 3]) /// - /// // DELETE FROM countries WHERE code IN ('FR', 'US', 'DE') + /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') /// try Country.deleteAll(db, keys: ["FR", "US", "DE"]) /// /// When the table has no explicit primary key, GRDB uses the hidden /// "rowid" column: /// - /// // DELETE FROM documents WHERE rowid IN (1, 2, 3) + /// // DELETE FROM document WHERE rowid IN (1, 2, 3) /// try Document.deleteAll(db, keys: [1, 2, 3]) /// /// - parameters: @@ -643,16 +652,16 @@ extension MutablePersistableRecord { /// Delete a record, identified by its primary key; returns whether a /// database row was deleted. /// - /// // DELETE FROM players WHERE id = 123 + /// // DELETE FROM player WHERE id = 123 /// try Player.deleteOne(db, key: 123) /// - /// // DELETE FROM countries WHERE code = 'FR' + /// // DELETE FROM country WHERE code = 'FR' /// try Country.deleteOne(db, key: "FR") /// /// When the table has no explicit primary key, GRDB uses the hidden /// "rowid" column: /// - /// // DELETE FROM documents WHERE rowid = 1 + /// // DELETE FROM document WHERE rowid = 1 /// try Document.deleteOne(db, key: 1) /// /// - parameters: @@ -982,16 +991,8 @@ private struct InsertQuery: Hashable { let tableName: String let insertedColumns: [String] - // Not generated by Swift 4.1 + // TODO: remove when Swift can generate it var hashValue: Int { return tableName.hashValue } - - #if !swift(>=4.1) - static func == (lhs: InsertQuery, rhs: InsertQuery) -> Bool { - if lhs.tableName != rhs.tableName { return false } - if lhs.onConflict != rhs.onConflict { return false } - return lhs.insertedColumns == rhs.insertedColumns - } - #endif } extension InsertQuery { @@ -1023,17 +1024,8 @@ private struct UpdateQuery: Hashable { let updatedColumns: [String] let conditionColumns: [String] - // Not generated by Swift 4.1 + // TODO: remove when Swift can generate it var hashValue: Int { return tableName.hashValue } - - #if !swift(>=4.1) - static func == (lhs: UpdateQuery, rhs: UpdateQuery) -> Bool { - if lhs.tableName != rhs.tableName { return false } - if lhs.onConflict != rhs.onConflict { return false } - if lhs.updatedColumns != rhs.updatedColumns { return false } - return lhs.conditionColumns == rhs.conditionColumns - } - #endif } extension UpdateQuery { diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index ad24dc289..021a15a66 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -32,7 +32,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// /// class Player : Record { /// override class var databaseTableName: String { - /// return "players" + /// return "player" /// } /// } /// @@ -64,7 +64,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// /// Unless this method is overriden, requests select all columns: /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// try Player.fetchAll(db) /// /// You can override this property and provide an explicit list @@ -76,7 +76,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// } /// } /// - /// // SELECT id, name FROM players + /// // SELECT id, name FROM player /// try RestrictedPlayer.fetchAll(db) /// /// You can also add extra columns such as the `rowid` column: @@ -87,7 +87,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// } /// } /// - /// // SELECT *, rowid FROM players + /// // SELECT *, rowid FROM player /// try ExtendedPlayer.fetchAll(db) open class var databaseSelection: [SQLSelectable] { return [AllColumns()] diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index db1483e0c..60c9478d4 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -12,10 +12,10 @@ public protocol TableRecord { /// The name of the database table used to build requests. /// /// struct Player : TableRecord { - /// static var databaseTableName = "players" + /// static var databaseTableName = "player" /// } /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// try Player.fetchAll(db) static var databaseTableName: String { get } @@ -23,28 +23,28 @@ public protocol TableRecord { /// /// Unless said otherwise, requests select all columns: /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// try Player.fetchAll(db) /// /// You can provide a custom implementation and provide an explicit list /// of columns: /// /// struct RestrictedPlayer : TableRecord { - /// static var databaseTableName = "players" + /// static var databaseTableName = "player" /// static var databaseSelection = [Column("id"), Column("name")] /// } /// - /// // SELECT id, name FROM players + /// // SELECT id, name FROM player /// try RestrictedPlayer.fetchAll(db) /// /// You can also add extra columns such as the `rowid` column: /// /// struct ExtendedPlayer : TableRecord { - /// static var databaseTableName = "players" + /// static var databaseTableName = "player" /// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] /// } /// - /// // SELECT *, rowid FROM players + /// // SELECT *, rowid FROM player /// try ExtendedPlayer.fetchAll(db) static var databaseSelection: [SQLSelectable] { get } } @@ -77,20 +77,20 @@ extension TableRecord { /// For example: /// /// struct Player: TableRecord { - /// static let databaseTableName = "players" + /// static let databaseTableName = "player" /// } /// - /// // SELECT "players".* FROM players - /// let sql = "SELECT \(Player.selectionSQL()) FROM players" + /// // SELECT "player".* FROM player + /// let sql = "SELECT \(Player.selectionSQL()) FROM player" /// - /// // SELECT "p".* FROM players AS p - /// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM players AS p" + /// // SELECT "p".* FROM player AS p + /// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM player p" public static func selectionSQL(alias: String? = nil) -> String { - let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: alias ?? databaseTableName) - let selection = databaseSelection.map { $0.qualifiedSelectable(with: qualifier) } - var arguments: StatementArguments? = nil + let alias = TableAlias(tableName: databaseTableName, userName: alias) + let selection = databaseSelection.map { $0.qualifiedSelectable(with: alias) } + var context = SQLGenerationContext.recordSelectionGenerationContext(alias: alias) return selection - .map { $0.resultColumnSQL(&arguments) } + .map { $0.resultColumnSQL(&context) } .joined(separator: ", ") } @@ -99,11 +99,11 @@ extension TableRecord { /// For example: /// /// struct Player: TableRecord { - /// static let databaseTableName = "players" + /// static let databaseTableName = "player" /// } /// /// try dbQueue.write { db in - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("name", .text) /// t.column("score", .integer) @@ -113,10 +113,9 @@ extension TableRecord { /// try Player.numberOfSelectedColumns(db) /// } public static func numberOfSelectedColumns(_ db: Database) throws -> Int { - let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: nil) + let alias = TableAlias(tableName: databaseTableName) return try databaseSelection - .map { try $0.qualifiedSelectable(with: qualifier).columnCount(db) } + .map { try $0.qualifiedSelectable(with: alias).columnCount(db) } .reduce(0, +) } } - diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 1f5d77772..c498b799b 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -195,6 +195,84 @@ 564F9C241F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; 564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; + 5653EB8F20961FC000F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */; }; + 5653EB9020961FC000F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */; }; + 5653EB9120961FC000F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */; }; + 5653EB9220961FC000F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */; }; + 5653EB9320961FC000F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8720961FBF00F46237 /* AssociationQuery.swift */; }; + 5653EB9420961FC000F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8720961FBF00F46237 /* AssociationQuery.swift */; }; + 5653EB9520961FC000F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */; }; + 5653EB9620961FC000F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */; }; + 5653EB9720961FC000F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8920961FBF00F46237 /* ForeignKey.swift */; }; + 5653EB9820961FC000F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8920961FBF00F46237 /* ForeignKey.swift */; }; + 5653EB9920961FC000F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */; }; + 5653EB9A20961FC000F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */; }; + 5653EB9B20961FC000F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */; }; + 5653EB9C20961FC000F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */; }; + 5653EB9D20961FC000F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8C20961FBF00F46237 /* Association.swift */; }; + 5653EB9E20961FC000F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8C20961FBF00F46237 /* Association.swift */; }; + 5653EBA220961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EBA320961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EBB820961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EBB920961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EBBA20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EBBB20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EBBC20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EBBD20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EBBE20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EBBF20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EBC020961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EBC120961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EBC220961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EBC320961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EBC420961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EBC520961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EBC620961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EBC720961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EBC820961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EBC920961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EBCA20961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EBCB20961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EBCC20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EBCD20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EBCE20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EBCF20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EBD020961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EBD120961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EBD220961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EBD320961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EBD420961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EBD520961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EBD620961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EBD720961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EBD820961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EBD920961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EBDA20961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EBDB20961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EBDC20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EBDD20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EBDE20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EBDF20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EBE020961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EBE120961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EBE220961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EBE320961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EBE420961FE800F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */; }; + 5653EBE520961FE800F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */; }; + 5653EBE620961FE800F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */; }; + 5653EBE720961FE800F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */; }; + 5653EBE820961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EBE920961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EBEA20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EBEB20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EBEC20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EBED20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EBEE20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EBEF20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EC17209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */; }; + 5653EC18209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */; }; + 5653EC1A209873E600F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC19209873E600F46237 /* SQLGenerationContext.swift */; }; + 5653EC1B209873E600F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC19209873E600F46237 /* SQLGenerationContext.swift */; }; 5657AABA1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABD1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB101D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -478,8 +556,6 @@ 5698AD391DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 569A98FC2039B72D008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */; }; 569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */; }; - 569B7FA8201C904C0069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA6201C904C0069DE70 /* Swift4.1.swift */; }; - 569B7FA9201C904C0069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA6201C904C0069DE70 /* Swift4.1.swift */; }; 569C1EB31CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; 569C1EB41CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; 569C1EB61CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; @@ -755,8 +831,6 @@ 56F3E74F1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; 56F3E7641E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */; }; 56F3E7671E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */; }; - 56FC98791D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; - 56FC987C1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FEE7FC1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE7FD1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE8001F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; @@ -885,6 +959,31 @@ 564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; + 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; + 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; + 5653EB8720961FBF00F46237 /* AssociationQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationQuery.swift; sourceTree = ""; }; + 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; + 5653EB8920961FBF00F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; + 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; + 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; + 5653EB8C20961FBF00F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; + 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; + 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; + 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToFetchableRecordTests.swift; sourceTree = ""; }; + 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelDecodableRecordTests.swift; sourceTree = ""; }; + 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLDerivationTests.swift; sourceTree = ""; }; + 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationTableAliasTestsSQLTests.swift; sourceTree = ""; }; + 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLTests.swift; sourceTree = ""; }; + 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRowScopeSearchTests.swift; sourceTree = ""; }; + 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLDerivationTests.swift; sourceTree = ""; }; + 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainRowScopesTests.swift; sourceTree = ""; }; + 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelRowScopesTests.swift; sourceTree = ""; }; + 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLTests.swift; sourceTree = ""; }; + 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; + 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; + 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; + 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; + 5653EC19209873E600F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; 5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -976,7 +1075,6 @@ 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = ""; }; 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = ""; }; 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-3.0.swift"; sourceTree = ""; }; - 569B7FA6201C904C0069DE70 /* Swift4.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = ""; }; 569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = ""; }; 56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; @@ -1074,7 +1172,6 @@ 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = ""; }; 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = ""; }; 56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.101.1.swift"; sourceTree = ""; }; - 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; @@ -1317,6 +1414,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EBA420961FD300F46237 /* Association */, 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, @@ -1333,17 +1431,20 @@ 56300B6D1C53F592005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EB8420961FBF00F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, + 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */, 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */, - 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */, + 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */, + 5653EC19209873E600F46237 /* SQLGenerationContext.swift */, 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, @@ -1368,6 +1469,42 @@ name = DatabaseQueue; sourceTree = ""; }; + 5653EB8420961FBF00F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EB8C20961FBF00F46237 /* Association.swift */, + 5653EB8720961FBF00F46237 /* AssociationQuery.swift */, + 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */, + 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */, + 5653EB8920961FBF00F46237 /* ForeignKey.swift */, + 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */, + 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */, + 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */, + ); + path = Association; + sourceTree = ""; + }; + 5653EBA420961FD300F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */, + 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */, + 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */, + 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */, + 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */, + 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */, + 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */, + 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */, + 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */, + 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */, + 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */, + 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */, + 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */, + 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */, + ); + name = Association; + sourceTree = ""; + }; 5659F4861EA8D94E004A4992 /* Utils */ = { isa = PBXGroup; children = ( @@ -1613,7 +1750,6 @@ 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */, - 569B7FA6201C904C0069DE70 /* Swift4.1.swift */, ); path = Legacy; sourceTree = ""; @@ -1996,21 +2132,25 @@ 56BB6EAA1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 566B910A1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91241FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 5653EB9B20961FC000F46237 /* AssociationRequest.swift in Sources */, 56CEB5121EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4911EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842920413D6F00E50BFD /* DatabaseSnapshot.swift in Sources */, 56CEB4F21EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 560FC51C1CB003810014AA8E /* QueryInterfaceRequest.swift in Sources */, 560FC51D1CB003810014AA8E /* SQLCollatedExpression.swift in Sources */, + 5653EB9920961FC000F46237 /* ForeignKeyRequest.swift in Sources */, 566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215B1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D41D981D5E00FF74B8 /* SQLOperators.swift in Sources */, + 5653EB9120961FC000F46237 /* HasOneAssociation.swift in Sources */, 56CEB5621EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FB1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD361DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, 566B91141FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 560FC51F1CB003810014AA8E /* CGFloat.swift in Sources */, 5674A7091F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, + 5653EC17209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */, 5659F4A11EA8D997004A4992 /* Result.swift in Sources */, 560FC5201CB003810014AA8E /* Date.swift in Sources */, 560FC5221CB003810014AA8E /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, @@ -2020,13 +2160,14 @@ 5698AC381D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */, 5659F4991EA8D989004A4992 /* Pool.swift in Sources */, - 569B7FA8201C904C0069DE70 /* Swift4.1.swift in Sources */, + 5653EB8F20961FC000F46237 /* BelongsToAssociation.swift in Sources */, 5674A6FA1F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54D1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759B1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 567404891CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 56E06F131E859068008AE2A4 /* Fixits-0.102.0.swift in Sources */, 560FC5241CB003810014AA8E /* DatabaseWriter.swift in Sources */, + 5653EBA220961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5698AD191DAAD17B0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7641E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 56B964B21DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, @@ -2053,9 +2194,9 @@ 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */, 566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 560FC5351CB003810014AA8E /* Statement.swift in Sources */, + 5653EB9320961FC000F46237 /* AssociationQuery.swift in Sources */, 5690C3411D23E82A00E59934 /* Data.swift in Sources */, 5659F4891EA8D94E004A4992 /* Utils.swift in Sources */, - 56FC98791D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 560FC5361CB003810014AA8E /* DatabaseMigrator.swift in Sources */, 560FC5371CB003810014AA8E /* DatabaseSchemaCache.swift in Sources */, 560FC5381CB003810014AA8E /* DatabaseDateComponents.swift in Sources */, @@ -2071,14 +2212,18 @@ 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD221DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */, + 5653EB9720961FC000F46237 /* ForeignKey.swift in Sources */, 569A98FC2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, + 5653EB9520961FC000F46237 /* HasManyAssociation.swift in Sources */, 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */, 567071F8208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 560FC53F1CB003810014AA8E /* Row.swift in Sources */, 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */, + 5653EC1A209873E600F46237 /* SQLGenerationContext.swift in Sources */, 560FC5411CB003810014AA8E /* PersistableRecord.swift in Sources */, 566475A31D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6EA1F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB9D20961FC000F46237 /* Association.swift in Sources */, 5657AABA1D107001006283EF /* NSData.swift in Sources */, 560FC5421CB003810014AA8E /* StatementColumnConvertible.swift in Sources */, 56CEB5541EAA359A00BFAF62 /* SQLExpression.swift in Sources */, @@ -2097,6 +2242,7 @@ 5698ACD81DA925420056AF8C /* RowTestCase.swift in Sources */, 56A8C2411D1918EE0096E9D4 /* FoundationNSUUIDTests.swift in Sources */, 562EA8301F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EBC020961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 562206031E420EA3005860AC /* DatabasePoolBackupTests.swift in Sources */, 5657AB571D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 564448841EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2115,6 +2261,7 @@ 562393191DECC02000A6B01F /* RowFetchTests.swift in Sources */, 560FC56B1CB00B880014AA8E /* DatabaseCollationTests.swift in Sources */, 560FC56C1CB00B880014AA8E /* UpdateStatementTests.swift in Sources */, + 5653EBE020961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 560FC56D1CB00B880014AA8E /* DatabaseMigratorTests.swift in Sources */, 560FC5701CB00B880014AA8E /* DatabasePoolCollationTests.swift in Sources */, 560FC5711CB00B880014AA8E /* RecordPrimaryKeySingleTests.swift in Sources */, @@ -2123,11 +2270,14 @@ 56B021CA1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 562205F61E420E48005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 560FC5741CB00B880014AA8E /* DatabasePoolFunctionTests.swift in Sources */, + 5653EBDC20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 560FC5761CB00B880014AA8E /* RowCopiedFromStatementTests.swift in Sources */, 560FC5771CB00B880014AA8E /* DatabaseQueueSchemaCacheTests.swift in Sources */, + 5653EBCC20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */, 562756441E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56AF746C1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 56B14E801D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, + 5653EBE420961FE800F46237 /* AssociationChainSQLTests.swift in Sources */, 562206051E420EA3005860AC /* DatabasePoolReadOnlyTests.swift in Sources */, 562206041E420EA3005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 56176C611EACCCC7000F3F2B /* FTS5RecordTests.swift in Sources */, @@ -2155,6 +2305,7 @@ 560FC57F1CB00B880014AA8E /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 5698ACB71DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5672DE5A1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, + 5653EBE820961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56176C601EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */, 5674A7111F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -2165,8 +2316,10 @@ 567E55ED1D2BDD3D00CC6F79 /* EncryptionTests.swift in Sources */, 56741EA91E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56176C641EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, + 5653EBB820961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 560FC5841CB00B880014AA8E /* PersistableRecordTests.swift in Sources */, 560FC5871CB00B880014AA8E /* RecordSubClassTests.swift in Sources */, + 5653EBBC20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */, 5674A72C1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 56C3F7541CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, @@ -2179,8 +2332,10 @@ 56071A4E1DB54ED200CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, 56A4CDB11D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 567156141CB141D0007DC145 /* DatabaseQueueInMemoryTests.swift in Sources */, + 5653EBEC20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 560FC58E1CB00B880014AA8E /* RecordPrimaryKeyRowIDTests.swift in Sources */, 560FC58F1CB00B880014AA8E /* DatabaseReaderTests.swift in Sources */, + 5653EBD020961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 560FC5901CB00B880014AA8E /* RecordEditedTests.swift in Sources */, 560FC5911CB00B880014AA8E /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 56CC924C201E059100CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2188,9 +2343,12 @@ 560FC5921CB00B880014AA8E /* FetchableRecordTests.swift in Sources */, 56A5EF101EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5657AB371D108BA9006283EF /* FoundationDataTests.swift in Sources */, + 5653EBD820961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */, 560FC5941CB00B880014AA8E /* DatabaseValueConvertibleSubclassTests.swift in Sources */, + 5653EBC820961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 565EFAEF1D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, 560FC5961CB00B880014AA8E /* DatabaseValueConvertibleFetchTests.swift in Sources */, + 5653EBC420961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 560FC5971CB00B880014AA8E /* DatabaseErrorTests.swift in Sources */, 560FC5991CB00B880014AA8E /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 564F9C1F1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -2222,6 +2380,7 @@ 5698AC8A1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5698AC041D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 5690C3381D23E7D200E59934 /* FoundationDateTests.swift in Sources */, + 5653EBD420961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 6340BF811E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 5622060B1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, 562205F41E420E48005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, @@ -2244,6 +2403,7 @@ 5698ACD91DA925420056AF8C /* RowTestCase.swift in Sources */, 567156221CB16729007DC145 /* StatementColumnConvertibleFetchTests.swift in Sources */, 562EA8311F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EBC120961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 562206001E420EA3005860AC /* DatabasePoolBackupTests.swift in Sources */, 567156231CB16729007DC145 /* RecordPrimaryKeyNoneTests.swift in Sources */, 564448851EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2262,6 +2422,7 @@ 5623931A1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 5671562E1CB16729007DC145 /* DatabasePoolCollationTests.swift in Sources */, 5671562F1CB16729007DC145 /* RecordPrimaryKeySingleTests.swift in Sources */, + 5653EBE120961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 567156301CB16729007DC145 /* StatementColumnConvertibleTests.swift in Sources */, 56C3F7551CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, @@ -2270,11 +2431,14 @@ 56B14E811D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 562205F91E420E49005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 566AD8C81D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */, + 5653EBDD20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 567156321CB16729007DC145 /* DatabasePoolFunctionTests.swift in Sources */, 567156341CB16729007DC145 /* RowCopiedFromStatementTests.swift in Sources */, + 5653EBCD20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */, 562756451E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 569C1EB41CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */, 56AF746D1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, + 5653EBE520961FE800F46237 /* AssociationChainSQLTests.swift in Sources */, 562206021E420EA3005860AC /* DatabasePoolReadOnlyTests.swift in Sources */, 562206011E420EA3005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 56176C671EACCCC8000F3F2B /* FTS5RecordTests.swift in Sources */, @@ -2302,6 +2466,7 @@ 5671563F1CB16729007DC145 /* RecordCopyTests.swift in Sources */, 5698ACB81DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 567156401CB16729007DC145 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, + 5653EBE920961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56176C661EACCCC8000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */, 5674A7131F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -2312,8 +2477,10 @@ 5690C3391D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 56741EAA1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56176C6A1EACCCC8000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, + 5653EBB920961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 567156461CB16729007DC145 /* TransactionObserverTests.swift in Sources */, 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, + 5653EBBD20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 567156481CB16729007DC145 /* DatabaseValueTests.swift in Sources */, 5674A72E1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 5671564A1CB16729007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */, @@ -2326,8 +2493,10 @@ 56071A4F1DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, 5671564D1CB16729007DC145 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 5671564E1CB16729007DC145 /* DatabaseReaderTests.swift in Sources */, + 5653EBED20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 5671564F1CB16729007DC145 /* RecordEditedTests.swift in Sources */, 567156501CB16729007DC145 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, + 5653EBD120961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 567156511CB16729007DC145 /* FetchableRecordTests.swift in Sources */, 56A8C2441D1918EE0096E9D4 /* FoundationUUIDTests.swift in Sources */, 56CC924D201E059100CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2335,9 +2504,12 @@ 567156531CB16729007DC145 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56A5EF111EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5690C3281D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, + 5653EBD920961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */, 5657AB381D108BA9006283EF /* FoundationDataTests.swift in Sources */, + 5653EBC920961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 561667031D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, 565EFAF01D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, + 5653EBC520961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 567156551CB16729007DC145 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 567156561CB16729007DC145 /* DatabaseErrorTests.swift in Sources */, 564F9C201F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -2369,6 +2541,7 @@ 5698AC8B1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5698AC051D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 567156621CB16729007DC145 /* CGFloatTests.swift in Sources */, + 5653EBD520961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 6340BF821E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 5622060A1E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, 562205F71E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, @@ -2391,21 +2564,25 @@ 56BB6EAD1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 566B910D1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91271FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 5653EB9C20961FC000F46237 /* AssociationRequest.swift in Sources */, 56CEB5151EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4941EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842A20413D8500E50BFD /* DatabaseSnapshot.swift in Sources */, 56CEB4F51EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56AFC9F11CB1A8BB00F48B96 /* QueryInterfaceRequest.swift in Sources */, 56AFC9F21CB1A8BB00F48B96 /* SQLCollatedExpression.swift in Sources */, + 5653EB9A20961FC000F46237 /* ForeignKeyRequest.swift in Sources */, 566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215E1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D71D981D5E00FF74B8 /* SQLOperators.swift in Sources */, + 5653EB9220961FC000F46237 /* HasOneAssociation.swift in Sources */, 56CEB5651EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FE1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD391DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, 566B91171FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56AFC9F31CB1A8BB00F48B96 /* Database.swift in Sources */, 5674A7061F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, + 5653EC18209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */, 5659F4A41EA8D997004A4992 /* Result.swift in Sources */, 56AFC9F41CB1A8BB00F48B96 /* CGFloat.swift in Sources */, 56AFC9F51CB1A8BB00F48B96 /* Date.swift in Sources */, @@ -2415,13 +2592,14 @@ 5698AC3B1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */, 5659F49C1EA8D989004A4992 /* Pool.swift in Sources */, - 569B7FA9201C904C0069DE70 /* Swift4.1.swift in Sources */, + 5653EB9020961FC000F46237 /* BelongsToAssociation.swift in Sources */, 5674A6F71F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB5501EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759E1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 5674048B1CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 56E06F161E85906C008AE2A4 /* Fixits-0.102.0.swift in Sources */, 56AFC9F91CB1A8BB00F48B96 /* DatabaseWriter.swift in Sources */, + 5653EBA320961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5698AD1A1DAAD17C0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7671E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 56B964B51DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, @@ -2448,9 +2626,9 @@ 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */, 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */, + 5653EB9420961FC000F46237 /* AssociationQuery.swift in Sources */, 5690C3441D23E82A00E59934 /* Data.swift in Sources */, 5659F48C1EA8D94E004A4992 /* Utils.swift in Sources */, - 56FC987C1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56AFCA0B1CB1A8BB00F48B96 /* Row.swift in Sources */, 56AFCA0C1CB1A8BB00F48B96 /* DatabaseSchemaCache.swift in Sources */, 56AFCA0D1CB1A8BB00F48B96 /* DatabaseDateComponents.swift in Sources */, @@ -2466,14 +2644,18 @@ 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD251DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, + 5653EB9820961FC000F46237 /* ForeignKey.swift in Sources */, 569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, + 5653EB9620961FC000F46237 /* HasManyAssociation.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, 56AFCA151CB1A8BB00F48B96 /* PersistableRecord.swift in Sources */, 567071F9208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */, + 5653EC1B209873E600F46237 /* SQLGenerationContext.swift in Sources */, 566475A61D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABD1D107001006283EF /* NSData.swift in Sources */, 5674A6E71F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB9E20961FC000F46237 /* Association.swift in Sources */, 56AFCA181CB1A8BB00F48B96 /* FetchedRecordsController.swift in Sources */, 56AFCA191CB1A8BB00F48B96 /* DatabaseValue.swift in Sources */, 56CEB5571EAA359A00BFAF62 /* SQLExpression.swift in Sources */, @@ -2492,6 +2674,7 @@ 56AFCA311CB1AA9900F48B96 /* RecordPrimaryKeyNoneTests.swift in Sources */, 56AFCA321CB1AA9900F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */, 562EA8341F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EBC220961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 5698ACD31DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 56AFCA331CB1AA9900F48B96 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564448881EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2510,6 +2693,7 @@ 56AFCA3B1CB1AA9900F48B96 /* DatabaseMigratorTests.swift in Sources */, 5657AB4B1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 56AFCA3E1CB1AA9900F48B96 /* DatabasePoolCollationTests.swift in Sources */, + 5653EBE220961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56FF455B1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56AFCA3F1CB1AA9900F48B96 /* RecordPrimaryKeySingleTests.swift in Sources */, 56AFCA411CB1AA9900F48B96 /* StatementColumnConvertibleTests.swift in Sources */, @@ -2518,11 +2702,14 @@ 56AFCA441CB1AA9900F48B96 /* RowCopiedFromStatementTests.swift in Sources */, 56C3F7571CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 562393351DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, + 5653EBDE20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 5698ACDC1DA925430056AF8C /* RowTestCase.swift in Sources */, 56AFCA451CB1AA9900F48B96 /* DatabaseQueueSchemaCacheTests.swift in Sources */, + 5653EBCE20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */, 562756481E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56AFCA461CB1AA9900F48B96 /* RecordPrimaryKeyMultipleTests.swift in Sources */, 56AFCA471CB1AA9900F48B96 /* RowFromStatementTests.swift in Sources */, + 5653EBE620961FE800F46237 /* AssociationChainSQLTests.swift in Sources */, 56AFCA491CB1AA9900F48B96 /* StatementArgumentsTests.swift in Sources */, 5672DE6B1CDB751D0022BA81 /* DatabasePoolBackupTests.swift in Sources */, 56176C731EACCCCA000F3F2B /* FTS5RecordTests.swift in Sources */, @@ -2550,6 +2737,7 @@ 56AFCA521CB1AA9900F48B96 /* PersistableRecordTests.swift in Sources */, 56AFCA531CB1AA9900F48B96 /* DatabaseValueConversionTests.swift in Sources */, 5657AB531D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, + 5653EBEA20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 5698AC9B1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56176C721EACCCCA000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */, @@ -2560,8 +2748,10 @@ 56AFCA561CB1AA9900F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */, 56AFCA571CB1AA9900F48B96 /* TransactionObserverTests.swift in Sources */, 56741EAD1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, + 5653EBBA20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 56176C761EACCCCA000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 5623935C1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, + 5653EBBE20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5698AC851DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 5698AC451DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 5674A72B1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -2574,8 +2764,10 @@ 56A4CDB51D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56AFCA5B1CB1AA9900F48B96 /* DatabaseValueTests.swift in Sources */, 56AFCA5C1CB1AA9900F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */, + 5653EBEE20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 56AFCA5D1CB1AA9900F48B96 /* DatabaseReaderTests.swift in Sources */, 56A8C2491D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */, + 5653EBD220961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 56AFCA5E1CB1AA9900F48B96 /* FetchableRecordTests.swift in Sources */, 56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, @@ -2583,9 +2775,12 @@ 56AFCA611CB1AA9900F48B96 /* RecordEditedTests.swift in Sources */, 56AFCA621CB1AA9900F48B96 /* DatabasePoolSchemaCacheTests.swift in Sources */, 56A5EF141EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, + 5653EBDA20961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */, 5623931D1DECC02000A6B01F /* RowFetchTests.swift in Sources */, + 5653EBCA20961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 56AFCA631CB1AA9900F48B96 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5698AC8E1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, + 5653EBC620961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 56AFCA641CB1AA9900F48B96 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56A8C24A1D1918F10096E9D4 /* FoundationUUIDTests.swift in Sources */, 56AFCA651CB1AA9900F48B96 /* DatabaseErrorTests.swift in Sources */, @@ -2617,6 +2812,7 @@ 56AFCA731CB1AA9900F48B96 /* DatabaseQueueInMemoryTests.swift in Sources */, 56AFCA741CB1AA9900F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */, 567A80581D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, + 5653EBD620961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 6340BF851E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 56AFCA751CB1AA9900F48B96 /* CGFloatTests.swift in Sources */, 562393531DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, @@ -2639,6 +2835,7 @@ 56AFCA8A1CB1ABC800F48B96 /* RecordPrimaryKeyNoneTests.swift in Sources */, 56AFCA8B1CB1ABC800F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */, 562EA8351F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EBC320961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 5698ACD41DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 56AFCA8C1CB1ABC800F48B96 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564448891EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2657,6 +2854,7 @@ 56AFCA911CB1ABC800F48B96 /* QueryInterfaceExpressionsTests.swift in Sources */, 56AFCA921CB1ABC800F48B96 /* SelectStatementTests.swift in Sources */, 56AFCA931CB1ABC800F48B96 /* UpdateStatementTests.swift in Sources */, + 5653EBE320961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56AFCA941CB1ABC800F48B96 /* DatabaseMigratorTests.swift in Sources */, 5657AB641D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 56FF455C1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, @@ -2665,11 +2863,14 @@ 5657AB5C1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 56AFCA981CB1ABC800F48B96 /* RecordPrimaryKeySingleTests.swift in Sources */, 562393361DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, + 5653EBDF20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 5698ACDD1DA925430056AF8C /* RowTestCase.swift in Sources */, 56AFCA9A1CB1ABC800F48B96 /* StatementColumnConvertibleTests.swift in Sources */, + 5653EBCF20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */, 562756491E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56AFCA9B1CB1ABC800F48B96 /* DatabasePoolFunctionTests.swift in Sources */, 5672DE5E1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, + 5653EBE720961FE800F46237 /* AssociationChainSQLTests.swift in Sources */, 56AFCA9D1CB1ABC800F48B96 /* RowCopiedFromStatementTests.swift in Sources */, 56AFCA9E1CB1ABC800F48B96 /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56176C791EACCCCB000F3F2B /* FTS5RecordTests.swift in Sources */, @@ -2697,6 +2898,7 @@ 56A8C24B1D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */, 56AFCAAB1CB1ABC800F48B96 /* PersistableRecordTests.swift in Sources */, 56FF45461D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 5653EBEB20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 5698AC9C1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56176C781EACCCCB000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F2203DA2A4000C443C /* JoinSupportTests.swift in Sources */, @@ -2707,8 +2909,10 @@ 5657AB441D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 5623935D1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 56741EAE1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, + 5653EBBB20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 56176C7C1EACCCCB000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 5698AC861DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, + 5653EBBF20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5698AC461DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 56AF74711D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 5674A7281F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -2721,8 +2925,10 @@ 56A4CDB61D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 5657AB4C1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 56AFCAB31CB1ABC800F48B96 /* RecordSubClassTests.swift in Sources */, + 5653EBEF20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 56AFCAB41CB1ABC800F48B96 /* DatabaseValueTests.swift in Sources */, 5657AB3C1D108BA9006283EF /* FoundationDataTests.swift in Sources */, + 5653EBD320961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5634B10C1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 56AFCAB51CB1ABC800F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */, @@ -2730,9 +2936,12 @@ 56AFCAB71CB1ABC800F48B96 /* FetchableRecordTests.swift in Sources */, 56B15D0D1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56A5EF151EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, + 5653EBDB20961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */, 5623931E1DECC02000A6B01F /* RowFetchTests.swift in Sources */, + 5653EBCB20961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 56AFCAB81CB1ABC800F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5698AC8F1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, + 5653EBC720961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 56AFCAB91CB1ABC800F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56AFCABA1CB1ABC800F48B96 /* RecordEditedTests.swift in Sources */, 56AFCABB1CB1ABC800F48B96 /* DatabasePoolSchemaCacheTests.swift in Sources */, @@ -2764,6 +2973,7 @@ 56AFCACC1CB1ABC800F48B96 /* DatabaseQueueInMemoryTests.swift in Sources */, 56AFCACD1CB1ABC800F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */, 56AFCACE1CB1ABC800F48B96 /* CGFloatTests.swift in Sources */, + 5653EBD720961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 6340BF861E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 567A80591D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 562393541DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index ecf88c2b8..90f2ee9c5 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -51,6 +51,54 @@ 564F9C251F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; + 5653EB4120961F6100F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */; }; + 5653EB4220961F6100F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */; }; + 5653EB4320961F6100F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3820961F6000F46237 /* HasOneAssociation.swift */; }; + 5653EB4420961F6100F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3820961F6000F46237 /* HasOneAssociation.swift */; }; + 5653EB4520961F6100F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3920961F6000F46237 /* AssociationQuery.swift */; }; + 5653EB4620961F6100F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3920961F6000F46237 /* AssociationQuery.swift */; }; + 5653EB4720961F6100F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */; }; + 5653EB4820961F6100F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */; }; + 5653EB4920961F6100F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3B20961F6000F46237 /* ForeignKey.swift */; }; + 5653EB4A20961F6100F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3B20961F6000F46237 /* ForeignKey.swift */; }; + 5653EB4B20961F6100F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */; }; + 5653EB4C20961F6100F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */; }; + 5653EB4D20961F6100F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3D20961F6100F46237 /* AssociationRequest.swift */; }; + 5653EB4E20961F6100F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3D20961F6100F46237 /* AssociationRequest.swift */; }; + 5653EB4F20961F6100F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3E20961F6100F46237 /* Association.swift */; }; + 5653EB5020961F6100F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3E20961F6100F46237 /* Association.swift */; }; + 5653EB5420961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EB5520961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EB6820961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EB6920961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EB6A20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EB6B20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EB6C20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EB6D20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5B20961FB100F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EB6F20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5B20961FB100F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EB7020961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5C20961FB100F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EB7120961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5C20961FB100F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EB7220961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5D20961FB100F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EB7320961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5D20961FB100F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EB7620961FB200F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5F20961FB100F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EB7720961FB200F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5F20961FB100F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EB7820961FB200F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EB7920961FB200F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EB7A20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6120961FB100F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EB7B20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6120961FB100F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EB7C20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EB7D20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EB7E20961FB200F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */; }; + 5653EB7F20961FB200F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */; }; + 5653EB8020961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EB8120961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EB8220961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EC082098737400F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC072098737400F46237 /* SQLGenerationContext.swift */; }; + 5653EC092098737400F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC072098737400F46237 /* SQLGenerationContext.swift */; }; 5657AABB1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABE1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB111D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -189,8 +237,6 @@ 5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 569A98F82039B716008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98F62039B716008D7DBF /* Fixits-3.0.swift */; }; 569A98F92039B716008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98F62039B716008D7DBF /* Fixits-3.0.swift */; }; - 569B7FA4201C90430069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA2201C90430069DE70 /* Swift4.1.swift */; }; - 569B7FA5201C90430069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA2201C90430069DE70 /* Swift4.1.swift */; }; 569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */; }; 569EF0E7200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */; }; 56A4CDB31D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; }; @@ -586,6 +632,30 @@ 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; + 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; + 5653EB3820961F6000F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; + 5653EB3920961F6000F46237 /* AssociationQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationQuery.swift; sourceTree = ""; }; + 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; + 5653EB3B20961F6000F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; + 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; + 5653EB3D20961F6100F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; + 5653EB3E20961F6100F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; + 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; + 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; + 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToFetchableRecordTests.swift; sourceTree = ""; }; + 5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelDecodableRecordTests.swift; sourceTree = ""; }; + 5653EB5B20961FB100F46237 /* AssociationBelongsToSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLDerivationTests.swift; sourceTree = ""; }; + 5653EB5C20961FB100F46237 /* AssociationTableAliasTestsSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationTableAliasTestsSQLTests.swift; sourceTree = ""; }; + 5653EB5D20961FB100F46237 /* AssociationHasOneSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLTests.swift; sourceTree = ""; }; + 5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRowScopeSearchTests.swift; sourceTree = ""; }; + 5653EB5F20961FB100F46237 /* AssociationHasOneSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLDerivationTests.swift; sourceTree = ""; }; + 5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainRowScopesTests.swift; sourceTree = ""; }; + 5653EB6120961FB100F46237 /* AssociationParallelRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelRowScopesTests.swift; sourceTree = ""; }; + 5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLTests.swift; sourceTree = ""; }; + 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; + 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; + 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; + 5653EC072098737400F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; 5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -671,7 +741,6 @@ 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = ""; }; 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = ""; }; 569A98F62039B716008D7DBF /* Fixits-3.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-3.0.swift"; sourceTree = ""; }; - 569B7FA2201C90430069DE70 /* Swift4.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = ""; }; 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = ""; }; 56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; @@ -991,6 +1060,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EB5620961F8900F46237 /* Association */, 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, @@ -1007,17 +1077,20 @@ 56300B6D1C53F592005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EB3620961F6000F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, + 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */, 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */, 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */, + 5653EC072098737400F46237 /* SQLGenerationContext.swift */, 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, @@ -1042,6 +1115,42 @@ name = DatabaseQueue; sourceTree = ""; }; + 5653EB3620961F6000F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EB3E20961F6100F46237 /* Association.swift */, + 5653EB3920961F6000F46237 /* AssociationQuery.swift */, + 5653EB3D20961F6100F46237 /* AssociationRequest.swift */, + 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */, + 5653EB3B20961F6000F46237 /* ForeignKey.swift */, + 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */, + 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */, + 5653EB3820961F6000F46237 /* HasOneAssociation.swift */, + ); + path = Association; + sourceTree = ""; + }; + 5653EB5620961F8900F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */, + 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */, + 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */, + 5653EB5B20961FB100F46237 /* AssociationBelongsToSQLDerivationTests.swift */, + 5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */, + 5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */, + 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */, + 5653EB5F20961FB100F46237 /* AssociationHasOneSQLDerivationTests.swift */, + 5653EB5D20961FB100F46237 /* AssociationHasOneSQLTests.swift */, + 5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */, + 5653EB6120961FB100F46237 /* AssociationParallelRowScopesTests.swift */, + 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */, + 5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */, + 5653EB5C20961FB100F46237 /* AssociationTableAliasTestsSQLTests.swift */, + ); + name = Association; + sourceTree = ""; + }; 5659F4861EA8D94E004A4992 /* Utils */ = { isa = PBXGroup; children = ( @@ -1287,7 +1396,6 @@ 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, 569A98F62039B716008D7DBF /* Fixits-3.0.swift */, - 569B7FA2201C90430069DE70 /* Swift4.1.swift */, ); path = Legacy; sourceTree = ""; @@ -1699,15 +1807,18 @@ F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */, 566B910E1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91281FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 5653EB4E20961F6100F46237 /* AssociationRequest.swift in Sources */, 56CEB5161EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4951EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, 56CEB4F61EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */, + 5653EB4C20961F6100F46237 /* ForeignKeyRequest.swift in Sources */, 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215F1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D81D981D5E00FF74B8 /* SQLOperators.swift in Sources */, + 5653EB4420961F6100F46237 /* HasOneAssociation.swift in Sources */, 56CEB5661EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -1723,13 +1834,14 @@ F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */, 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */, 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */, - 569B7FA5201C90430069DE70 /* Swift4.1.swift in Sources */, + 5653EB4220961F6100F46237 /* BelongsToAssociation.swift in Sources */, 5674A6F61F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB5511EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 566475D11D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 5664759F1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 56E06F171E85906D008AE2A4 /* Fixits-0.102.0.swift in Sources */, + 5653EB5520961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */, F3BA802B1CFB289B003DC1BA /* QueryInterfaceRequest.swift in Sources */, 5698AD171DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7681E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, @@ -1756,6 +1868,7 @@ F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, + 5653EB4620961F6100F46237 /* AssociationQuery.swift in Sources */, F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48D1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA80231CFB288C003DC1BA /* NSString.swift in Sources */, @@ -1774,14 +1887,18 @@ 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */, + 5653EB4A20961F6100F46237 /* ForeignKey.swift in Sources */, 569A98F92039B716008D7DBF /* Fixits-3.0.swift in Sources */, + 5653EB4820961F6100F46237 /* HasManyAssociation.swift in Sources */, F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */, 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, + 5653EC092098737400F46237 /* SQLGenerationContext.swift in Sources */, 566475A71D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABE1D107001006283EF /* NSData.swift in Sources */, 5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB5020961F6100F46237 /* Association.swift in Sources */, F3BA800E1CFB2876003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80191CFB2876003DC1BA /* Statement.swift in Sources */, 56CEB5581EAA359A00BFAF62 /* SQLExpression.swift in Sources */, @@ -1800,6 +1917,7 @@ F3BA80B91CFB2FD1003DC1BA /* DatabasePoolBackupTests.swift in Sources */, F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 562EA8361F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EB6D20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, F3BA80DD1CFB300E003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, F3BA80521CFB2B59003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */, @@ -1818,6 +1936,7 @@ F3BA80511CFB2B59003DC1BA /* DatabaseQueueReleaseMemoryTests.swift in Sources */, F3BA81221CFB3063003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */, F3BA80F81CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, + 5653EB7D20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 5698AC0A1D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */, 562393371DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, @@ -1826,11 +1945,14 @@ 5623935E1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 566AD8CD1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */, + 5653EB7B20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 5698AC871DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, F3BA80D11CFB2FF3003DC1BA /* MutablePersistableRecordTests.swift in Sources */, + 5653EB7320961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */, F3BA80CF1CFB2FEA003DC1BA /* SchedulingWatchdogTests.swift in Sources */, F3BA80E71CFB3016003DC1BA /* RowCopiedFromStatementTests.swift in Sources */, F3BA812A1CFB3063003DC1BA /* RecordSubClassTests.swift in Sources */, + 5653EB7F20961FB200F46237 /* AssociationChainSQLTests.swift in Sources */, 6340BF871E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, F3BA80D21CFB2FF3003DC1BA /* PersistableRecordTests.swift in Sources */, @@ -1858,6 +1980,7 @@ F3BA81151CFB305E003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */, F3BA80DC1CFB300E003DC1BA /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5698AD021DAA8ACB0056AF8C /* FTS5CustomTokenizerTests.swift in Sources */, + 5653EB8120961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56B964CA1DA521450002DA19 /* FTS5PatternTests.swift in Sources */, 564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */, 5674A70E1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -1868,8 +1991,10 @@ F3BA80F11CFB3019003DC1BA /* DatabaseSavepointTests.swift in Sources */, 56ED8A801DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */, F3BA81031CFB303D003DC1BA /* FetchedRecordsControllerTests.swift in Sources */, + 5653EB6920961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */, F3BA80B71CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, 5698ACCC1DA62A2D0056AF8C /* FTS5TokenizerTests.swift in Sources */, + 5653EB6B20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5690C33E1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -1882,8 +2007,10 @@ F3BA80BD1CFB2FD1003DC1BA /* DatabasePoolFunctionTests.swift in Sources */, F3BA81261CFB3063003DC1BA /* RecordCopyTests.swift in Sources */, 56A8C24D1D1918F30096E9D4 /* FoundationNSUUIDTests.swift in Sources */, + 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 5698AC471DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */, + 5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */, @@ -1891,9 +2018,12 @@ F3BA80F91CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 56A5EF161EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, F3BA80DA1CFB300E003DC1BA /* DatabaseTimestampTests.swift in Sources */, + 5653EB7920961FB200F46237 /* AssociationChainRowScopesTests.swift in Sources */, F3BA81201CFB3063003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */, + 5653EB7120961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, F3BA812B1CFB3063003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, 5698ACA51DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, + 5653EB6F20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, F3BA80B11CFB2FC4003DC1BA /* DatabaseTests.swift in Sources */, 56A8C24E1D1918F30096E9D4 /* FoundationUUIDTests.swift in Sources */, 564F9C251F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -1925,6 +2055,7 @@ F3BA80501CFB2B59003DC1BA /* DatabasePoolSchemaCacheTests.swift in Sources */, F3BA80BB1CFB2FD1003DC1BA /* DatabasePoolConcurrencyTests.swift in Sources */, F3BA81141CFB305E003DC1BA /* QueryInterfaceRequestTests.swift in Sources */, + 5653EB7720961FB200F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, F3BA81271CFB3063003DC1BA /* RecordEditedTests.swift in Sources */, 56FF455D1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, F3BA80C51CFB2FD8003DC1BA /* DatabaseQueueBackupTests.swift in Sources */, @@ -1947,15 +2078,18 @@ F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */, 566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91251FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 5653EB4D20961F6100F46237 /* AssociationRequest.swift in Sources */, 56CEB5131EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4921EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, 56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */, + 5653EB4B20961F6100F46237 /* ForeignKeyRequest.swift in Sources */, 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215C1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D51D981D5E00FF74B8 /* SQLOperators.swift in Sources */, + 5653EB4320961F6100F46237 /* HasOneAssociation.swift in Sources */, 56CEB5631EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -1971,13 +2105,14 @@ F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */, 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */, 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */, - 569B7FA4201C90430069DE70 /* Swift4.1.swift in Sources */, + 5653EB4120961F6100F46237 /* BelongsToAssociation.swift in Sources */, 5674A6F51F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54E1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 566475CE1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 5664759C1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 56E06F141E859069008AE2A4 /* Fixits-0.102.0.swift in Sources */, + 5653EB5420961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */, F3BA80871CFB2E70003DC1BA /* QueryInterfaceRequest.swift in Sources */, 5698AD161DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7651E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, @@ -2004,6 +2139,7 @@ F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, 566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, + 5653EB4520961F6100F46237 /* AssociationQuery.swift in Sources */, F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */, @@ -2022,14 +2158,18 @@ 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */, + 5653EB4920961F6100F46237 /* ForeignKey.swift in Sources */, 569A98F82039B716008D7DBF /* Fixits-3.0.swift in Sources */, + 5653EB4720961F6100F46237 /* HasManyAssociation.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */, 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, + 5653EC082098737400F46237 /* SQLGenerationContext.swift in Sources */, 566475A41D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, 5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB4F20961F6100F46237 /* Association.swift in Sources */, F3BA806A1CFB2E55003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80751CFB2E55003DC1BA /* Statement.swift in Sources */, 56CEB5551EAA359A00BFAF62 /* SQLExpression.swift in Sources */, @@ -2048,6 +2188,7 @@ F3BA812C1CFB3064003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 5698AC991DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EB6C20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56A8C2451D1918EF0096E9D4 /* FoundationNSUUIDTests.swift in Sources */, 5657AB591D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2066,6 +2207,7 @@ 56A8C2461D1918EF0096E9D4 /* FoundationUUIDTests.swift in Sources */, F3BA80F61CFB301E003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */, F3BA80E61CFB3012003DC1BA /* DatabaseFunctionTests.swift in Sources */, + 5653EB7C20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 5698ACDA1DA925430056AF8C /* RowTestCase.swift in Sources */, F3BA811D1CFB305F003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA80AD1CFB2FA6003DC1BA /* DataMemoryTests.swift in Sources */, @@ -2074,11 +2216,14 @@ 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, F3BA81301CFB3064003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, + 5653EB7A20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */, F3BA80FB1CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, F3BA80EE1CFB3017003DC1BA /* RowAdapterTests.swift in Sources */, + 5653EB7220961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */, F3BA80D31CFB2FF4003DC1BA /* MutablePersistableRecordTests.swift in Sources */, 562393751DEE104400A6B01F /* MapCursorTests.swift in Sources */, F3BA80D01CFB2FEC003DC1BA /* SchedulingWatchdogTests.swift in Sources */, + 5653EB7E20961FB200F46237 /* AssociationChainSQLTests.swift in Sources */, F3BA80EC1CFB3017003DC1BA /* RowCopiedFromStatementTests.swift in Sources */, F3BA80D41CFB2FF4003DC1BA /* PersistableRecordTests.swift in Sources */, 6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, @@ -2106,6 +2251,7 @@ F3BA811C1CFB305F003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */, 5698ACD11DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 562205FB1E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, + 5653EB8020961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 5657AB611D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */, 5674A70C1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -2116,8 +2262,10 @@ F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */, 5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, F3BA80E21CFB300F003DC1BA /* DatabaseValueConvertibleFetchTests.swift in Sources */, + 5653EB6820961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */, F3BA80F21CFB301A003DC1BA /* DatabaseSavepointTests.swift in Sources */, F3BA80B81CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, + 5653EB6A20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5698AC061D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, 5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -2130,8 +2278,10 @@ F3BA80C01CFB2FD2003DC1BA /* DatabasePoolCollationTests.swift in Sources */, 5698ACA11DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, F3BA80C31CFB2FD2003DC1BA /* DatabasePoolFunctionTests.swift in Sources */, + 5653EB8220961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, F3BA80D51CFB2FFB003DC1BA /* DatabaseReaderTests.swift in Sources */, F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, + 5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2139,9 +2289,12 @@ F3BA80E01CFB300F003DC1BA /* DatabaseTimestampTests.swift in Sources */, 56A5EF121EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, F3BA80B21CFB2FC5003DC1BA /* DatabaseTests.swift in Sources */, + 5653EB7820961FB200F46237 /* AssociationChainRowScopesTests.swift in Sources */, F3BA80AE1CFB2FA6003DC1BA /* DatabaseRegionTests.swift in Sources */, + 5653EB7020961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, F3BA81311CFB3064003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */, 5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, + 5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */, 5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -2173,6 +2326,7 @@ F3BA811A1CFB305F003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */, F3BA81111CFB3057003DC1BA /* StatementArguments+FoundationTests.swift in Sources */, F3BA81371CFB3064003DC1BA /* RecordInitializersTests.swift in Sources */, + 5653EB7620961FB200F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, F3BA80C91CFB2FD8003DC1BA /* DatabaseQueueBackupTests.swift in Sources */, 56AF746E1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 56ED8A7F1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */, diff --git a/Makefile b/Makefile index 847fc35ac..a223d02e6 100644 --- a/Makefile +++ b/Makefile @@ -44,26 +44,12 @@ XCPRETTY_PATH := $(shell command -v xcpretty 2> /dev/null) # xcodebuild actions to run test targets TEST_ACTIONS = clean build build-for-testing test-without-building -# xcodebuild destination to run tests on iOS 8.1 (requires a pre-installed simulator) -MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=8.1" - # When adding support for an Xcode version, look for available devices with `instruments -s devices` ifeq ($(XCODEVERSION),9.3) MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.3" -else ifeq ($(XCODEVERSION),9.2) - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.2" -else ifeq ($(XCODEVERSION),9.1) - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.1" -else ifeq ($(XCODEVERSION),9.0) - ifeq ($(XCODEVERSION_PATCH),1) - # Xcode 9.0.1: @groue's personal computer - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0.1" - else - # Xcode 9.0: Travis https://docs.travis-ci.com/user/reference/osx/#Xcode-9.0 - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0" - endif + MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=9.0" else - # Xcode < 9.0 is not supported + # Swift 4.1 required: Xcode < 9.3 is not supported endif # If xcpretty is available, use it for xcodebuild output diff --git a/README.md b/README.md index 1e0990dbb..9efb31247 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,16 @@ -GRDB 2 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](https://developer.apple.com/swift/) [![Platforms](https://img.shields.io/cocoapods/p/GRDB.swift.svg)](https://developer.apple.com/swift/) [![License](https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000)](/LICENSE) [![Build Status](https://travis-ci.org/groue/GRDB.swift.svg?branch=master)](https://travis-ci.org/groue/GRDB.swift) +GRDB 3 [![Swift](https://img.shields.io/badge/swift-4.1-orange.svg?style=flat)](https://developer.apple.com/swift/) [![Platforms](https://img.shields.io/cocoapods/p/GRDB.swift.svg)](https://developer.apple.com/swift/) [![License](https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000)](/LICENSE) [![Build Status](https://travis-ci.org/groue/GRDB.swift.svg?branch=master)](https://travis-ci.org/groue/GRDB.swift) ========== ### A toolkit for SQLite databases, with a focus on application development **Latest release**: March 30, 2018 • version 2.10.0 • [CHANGELOG](CHANGELOG.md) -**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ • Swift 4+ / Xcode 9+ +**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ • Swift 4+ / Xcode 9.3+ | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | -| **Swift 4+** | **v2.10.0** | +| **Swift 4.1** | **v3.0.0** | +| Swift 4 | [v2.10.0](https://github.com/groue/GRDB.swift/tree/v2.10.0) | | Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | | Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | | Swift 3 | [v1.0](https://github.com/groue/GRDB.swift/tree/v1.0) | @@ -96,7 +97,7 @@ See [Database Connections](#database-connections) ```swift try dbQueue.write { db in try db.execute(""" - CREATE TABLE places ( + CREATE TABLE place ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, favorite BOOLEAN NOT NULL DEFAULT 0, @@ -105,7 +106,7 @@ try dbQueue.write { db in """) try db.execute(""" - INSERT INTO places (title, favorite, latitude, longitude) + INSERT INTO place (title, favorite, latitude, longitude) VALUES (?, ?, ?, ?) """, arguments: ["Paris", true, 48.85341, 2.3488]) @@ -123,7 +124,7 @@ See [Executing Updates](#executing-updates) ```swift try dbQueue.read { db in // Fetch database rows - let rows = try Row.fetchCursor(db, "SELECT * FROM places") + let rows = try Row.fetchCursor(db, "SELECT * FROM place") while let row = try rows.next() { let title: String = row["title"] let isFavorite: Bool = row["favorite"] @@ -133,12 +134,12 @@ try dbQueue.read { db in } // Fetch values - let placeCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM places")! // Int - let placeTitles = try String.fetchAll(db, "SELECT title FROM places") // [String] + let placeCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM place")! // Int + let placeTitles = try String.fetchAll(db, "SELECT title FROM place") // [String] } let placeCount = try dbQueue.read { db in - try Int.fetchOne(db, "SELECT COUNT(*) FROM places")! + try Int.fetchOne(db, "SELECT COUNT(*) FROM place")! } ``` @@ -162,7 +163,7 @@ struct Place { try dbQueue.write { db in // Create database table - try db.create(table: "places") { t in + try db.create(table: "place") { t in t.autoIncrementedPrimaryKey("id") t.column("title", .text).notNull() t.column("favorite", .boolean).notNull().defaults(to: false) @@ -209,7 +210,7 @@ try dbQueue.write { db in let favoriteCount = try Place.filter(Column("favorite")).fetchCount(db) // SQL is always welcome - let places = try Place.fetchAll(db, "SELECT * FROM places") + let places = try Place.fetchAll(db, "SELECT * FROM place") } ``` @@ -230,7 +231,7 @@ Place.filter(key: 1) }) // Track SQL requests -SQLRequest("SELECT * FROM places WHERE favorite ORDER BY title") +SQLRequest("SELECT * FROM place WHERE favorite ORDER BY title") .rx .fetchAll(in: dbQueue) .subscribe(onNext: { places: [Place] in @@ -389,7 +390,7 @@ SQLite creates the database file if it does not already exist. The connection is ```swift // Modify the database: try dbQueue.write { db in - try db.create(table: "places") { ... } + try db.create(table: "place") { ... } try Place(...).insert(db) } @@ -459,7 +460,7 @@ SQLite creates the database file if it does not already exist. The connection is ```swift // Modify the database: try dbPool.write { db in - try db.create(table: "places") { ... } + try db.create(table: "place") { ... } try Place(...).insert(db) } @@ -565,20 +566,20 @@ For example: ```swift try dbQueue.write { db in try db.execute(""" - CREATE TABLE players ( + CREATE TABLE player ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, score INT) """) try db.execute( - "INSERT INTO players (name, score) VALUES (:name, :score)", + "INSERT INTO player (name, score) VALUES (:name, :score)", arguments: ["name": "Barbara", "score": 1000]) // Join multiple statements with a semicolon: try db.execute(""" - INSERT INTO players (name, score) VALUES (?, ?); - INSERT INTO players (name, score) VALUES (?, ?) + INSERT INTO player (name, score) VALUES (?, ?); + INSERT INTO player (name, score) VALUES (?, ?) """, arguments: ["Arthur", 750, "Barbara", 1000]) } ``` @@ -591,7 +592,7 @@ Never ever embed values directly in your SQL strings, and always use arguments i ```swift try db.execute( - "INSERT INTO players (name, score) VALUES (?, ?)", + "INSERT INTO player (name, score) VALUES (?, ?)", arguments: ["Arthur", 1000]) let playerId = db.lastInsertedRowID ``` @@ -613,7 +614,7 @@ let playerId = player.id ```swift try dbQueue.read { db in - if let row = try Row.fetchOne(db, "SELECT * FROM wines WHERE id = ?", arguments: [1]) { + if let row = try Row.fetchOne(db, "SELECT * FROM wine WHERE id = ?", arguments: [1]) { let name: String = row["name"] let color: Color = row["color"] print(name, color) @@ -626,7 +627,7 @@ try dbQueue.read { db in ```swift try dbQueue.read { db in - let urls = try URL.fetchCursor(db, "SELECT url FROM wines") + let urls = try URL.fetchCursor(db, "SELECT url FROM wine") while let url = try urls.next() { print(url) } @@ -638,7 +639,7 @@ try dbQueue.read { db in ```swift let wines = try dbQueue.read { db in - try Wine.fetchAll(db, "SELECT * FROM wines") + try Wine.fetchAll(db, "SELECT * FROM wine") } ``` @@ -743,24 +744,24 @@ If you don't see, or don't care about the difference, use arrays. If you care ab ```swift // All URL hosts let hosts = try URL - .fetchCursor(db, "SELECT url FROM links") + .fetchCursor(db, "SELECT url FROM link") .map { url in url.host } // Prints all Github links try URL - .fetchCursor(db, "SELECT url FROM links") + .fetchCursor(db, "SELECT url FROM link") .filter { url in url.host == "github.com" } .forEach { url in print(url) } // Turn a cursor into an array: let cursor = URL - .fetchCursor(db, "SELECT url FROM links") + .fetchCursor(db, "SELECT url FROM link") .filter { url in url.host == "github.com" } let githubURLs = try Array(cursor) // [URL] // Turn a cursor into a set: let cursor = URL - .fetchCursor(db, "SELECT url FROM links") + .fetchCursor(db, "SELECT url FROM link") .flatMap { url in url.host } let hosts = try Set(cursor) // Set ``` @@ -786,7 +787,7 @@ try dbQueue.read { db in try Row.fetchAll(db, "SELECT ...", arguments: ...) // [Row] try Row.fetchOne(db, "SELECT ...", arguments: ...) // Row? - let rows = try Row.fetchCursor(db, "SELECT * FROM wines") + let rows = try Row.fetchCursor(db, "SELECT * FROM wine") while let row = try rows.next() { let name: String = row["name"] let color: Color = row["color"] @@ -795,7 +796,7 @@ try dbQueue.read { db in } let rows = try dbQueue.read { db in - try Row.fetchAll(db, "SELECT * FROM players") + try Row.fetchAll(db, "SELECT * FROM player") } ``` @@ -803,11 +804,11 @@ Arguments are optional arrays or dictionaries that fill the positional `?` and c ```swift let rows = try Row.fetchAll(db, - "SELECT * FROM players WHERE name = ?", + "SELECT * FROM player WHERE name = ?", arguments: ["Arthur"]) let rows = try Row.fetchAll(db, - "SELECT * FROM players WHERE name = :name", + "SELECT * FROM player WHERE name = :name", arguments: ["name": "Arthur"]) ``` @@ -1052,7 +1053,7 @@ try dbQueue.read { db in } let playerCount = try dbQueue.read { db in - try Int.fetchOne(db, "SELECT COUNT(*) FROM players")! + try Int.fetchOne(db, "SELECT COUNT(*) FROM player")! } ``` @@ -1061,8 +1062,8 @@ let playerCount = try dbQueue.read { db in There are many supported value types (Bool, Int, String, Date, Swift enums, etc.). See [Values](#values) for more information: ```swift -let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM players")! // Int -let urls = try URL.fetchAll(db, "SELECT url FROM links") // [URL] +let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM player")! // Int +let urls = try URL.fetchAll(db, "SELECT url FROM link") // [URL] ``` @@ -1088,14 +1089,14 @@ Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/do let url: URL = ... let verified: Bool = ... try db.execute( - "INSERT INTO links (url, verified) VALUES (?, ?)", + "INSERT INTO link (url, verified) VALUES (?, ?)", arguments: [url, verified]) ``` Values can be [extracted from rows](#column-values): ```swift -let rows = try Row.fetchCursor(db, "SELECT * FROM links") +let rows = try Row.fetchCursor(db, "SELECT * FROM link") while let row = try rows.next() { let url: URL = row["url"] let verified: Bool = row["verified"] @@ -1105,7 +1106,7 @@ while let row = try rows.next() { Values can be [directly fetched](#value-queries): ```swift -let urls = try URL.fetchAll(db, "SELECT url FROM links") // [URL] +let urls = try URL.fetchAll(db, "SELECT url FROM link") // [URL] ``` Use values in [Records](#records): @@ -1192,7 +1193,7 @@ Here is the support provided by GRDB for the various [date formats](https://www. ```swift try db.execute( - "INSERT INTO players (creationDate, ...) VALUES (?, ...)", + "INSERT INTO player (creationDate, ...) VALUES (?, ...)", arguments: [Date(), ...]) let creationDate: Date = row["creationDate"] @@ -1227,7 +1228,7 @@ components.day = 18 // Store "1973-09-18" let dbComponents = DatabaseDateComponents(components, format: .YMD) try db.execute( - "INSERT INTO players (birthDate, ...) VALUES (?, ...)", + "INSERT INTO player (birthDate, ...) VALUES (?, ...)", arguments: [dbComponents, ...]) // Read "1973-09-18" @@ -1247,7 +1248,7 @@ NSDecimalNumber deserves a longer discussion: **SQLite has no support for decimal numbers.** Given the table below, SQLite will actually store integers or doubles: ```sql -CREATE TABLE transfers ( +CREATE TABLE transfer ( amount DECIMAL(10,5) -- will store integer or double, actually ) ``` @@ -1255,9 +1256,9 @@ CREATE TABLE transfers ( This means that computations will not be exact: ```swift -try db.execute("INSERT INTO transfers (amount) VALUES (0.1)") -try db.execute("INSERT INTO transfers (amount) VALUES (0.2)") -let sum = try NSDecimalNumber.fetchOne(db, "SELECT SUM(amount) FROM transfers")! +try db.execute("INSERT INTO transfer (amount) VALUES (0.1)") +try db.execute("INSERT INTO transfer (amount) VALUES (0.2)") +let sum = try NSDecimalNumber.fetchOne(db, "SELECT SUM(amount) FROM transfer")! // Yikes! 0.3000000000000000512 print(sum) @@ -1268,14 +1269,14 @@ Don't blame SQLite or GRDB, and instead store your decimal numbers differently. A classic technique is to store *integers* instead, since SQLite performs exact computations of integers. For example, don't store Euros, but store cents instead: ```swift -// Store -let amount = NSDecimalNumber(string: "0.1") // 0.1 -let integerAmount = amount.multiplying(byPowerOf10: 2).int64Value // 100 -try db.execute("INSERT INTO transfers (amount) VALUES (?)", arguments: [integerAmount]) +// Write +let amount = NSDecimalNumber(string: "0.10") +let integerAmount = amount.multiplying(byPowerOf10: 2).int64Value +try db.execute("INSERT INTO transfer (amount) VALUES (?)", arguments: [integerAmount]) // Read -let integerAmount = try Int64.fetchOne(db, "SELECT SUM(amount) FROM transfers")! // 100 -let amount = NSDecimalNumber(value: integerAmount).multiplying(byPowerOf10: -2) // 0.1 +let integerAmount = try Int64.fetchOne(db, "SELECT SUM(amount) FROM transfer")! +let amount = NSDecimalNumber(value: integerAmount).multiplying(byPowerOf10: -2) // 0.10 ``` @@ -1303,11 +1304,11 @@ extension Grape : DatabaseValueConvertible { } // Store try db.execute( - "INSERT INTO wines (grape, color) VALUES (?, ?)", + "INSERT INTO wine (grape, color) VALUES (?, ?)", arguments: [Grape.merlot, Color.red]) // Read -let rows = try Row.fetchCursor(db, "SELECT * FROM wines") +let rows = try Row.fetchCursor(db, "SELECT * FROM wine") while let row = try rows.next() { let grape: Grape = row["grape"] let color: Color = row["color"] @@ -1342,8 +1343,8 @@ GRDB generally opens transactions for you, as a way to enforce its [concurrency ```swift // BEGIN TRANSACTION -// INSERT INTO credits ... -// INSERT INTO debits ... +// INSERT INTO credit ... +// INSERT INTO debit ... // COMMIT try dbQueue.write { db in try Credit(destinationAccout, amount).insert(db) @@ -1351,8 +1352,8 @@ try dbQueue.write { db in } // BEGIN TRANSACTION -// INSERT INTO credits ... -// INSERT INTO debits ... +// INSERT INTO credit ... +// INSERT INTO debit ... // COMMIT try dbPool.write { db in try Credit(destinationAccout, amount).insert(db) @@ -1368,15 +1369,15 @@ Yet you may need to exactly control when transactions take place: `DatabaseQueue.inDatabase()` and `DatabasePool.writeWithoutTransaction()` execute your database statements outside of any transaction: ```swift -// INSERT INTO credits ... -// INSERT INTO debits ... +// INSERT INTO credit ... +// INSERT INTO debit ... try dbQueue.inDatabase { db in try Credit(destinationAccout, amount).insert(db) try Debit(sourceAccount, amount).insert(db) } -// INSERT INTO credits ... -// INSERT INTO debits ... +// INSERT INTO credit ... +// INSERT INTO debit ... try dbPool.writeWithoutTransaction { db in try Credit(destinationAccout, amount).insert(db) try Debit(sourceAccount, amount).insert(db) @@ -1400,8 +1401,8 @@ To open explicit transactions, use one of the `Database.inTransaction`, `Databas ```swift // BEGIN TRANSACTION -// INSERT INTO credits ... -// INSERT INTO debits ... +// INSERT INTO credit ... +// INSERT INTO debit ... // COMMIT try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction try db.inTransaction { @@ -1412,8 +1413,8 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction } // BEGIN TRANSACTION -// INSERT INTO credits ... -// INSERT INTO debits ... +// INSERT INTO credit ... +// INSERT INTO debit ... // COMMIT try dbQueue.inTransaction { db in // or dbPool.writeInTransaction try Credit(destinationAccout, amount).insert(db) @@ -1565,10 +1566,10 @@ There are two kinds of prepared statements: **select statements**, and **update ```swift try dbQueue.write { db in - let updateSQL = "INSERT INTO players (name, score) VALUES (:name, :score)" + let updateSQL = "INSERT INTO player (name, score) VALUES (:name, :score)" let updateStatement = try db.makeUpdateStatement(updateSQL) - let selectSQL = "SELECT * FROM players WHERE name = ?" + let selectSQL = "SELECT * FROM player WHERE name = ?" let selectStatement = try db.makeSelectStatement(selectSQL) } ``` @@ -1631,8 +1632,8 @@ Should a cached prepared statement throw an error, don't reuse it (it is a progr A custom SQL function or aggregate extends SQLite: ```sql -SELECT reverse(name) FROM players; -- custom function -SELECT maxLength(name) FROM players; -- custom aggregate +SELECT reverse(name) FROM player; -- custom function +SELECT maxLength(name) FROM player; -- custom aggregate ``` - [Custom SQL Functions](#custom-sql-functions) @@ -1705,7 +1706,7 @@ try dbQueue.read { db in **Use custom functions in the [query interface](#the-query-interface):** ```swift -// SELECT reverseString("name") FROM players +// SELECT reverseString("name") FROM player Player.select(reverseString.apply(nameColumn)) ``` @@ -1763,7 +1764,7 @@ dbQueue.add(function: maxLength) // Or dbPool.add(function: ...) try dbQueue.read { db in // Some Int - try Int.fetchOne(db, "SELECT maxLength(name) FROM players")! + try Int.fetchOne(db, "SELECT maxLength(name) FROM player")! } ``` @@ -1777,7 +1778,7 @@ SQLite has the opportunity to perform additional optimizations when aggregates a **Use custom aggregates in the [query interface](#the-query-interface):** ```swift -// SELECT maxLength("name") FROM players +// SELECT maxLength("name") FROM player Int.fetchOne(db, Player.select(maxLength.apply(nameColumn))) // Int? ``` @@ -1789,22 +1790,22 @@ GRDB comes with a set of schema introspection methods: ```swift try dbQueue.read { db in // Bool, true if the table exists - try db.tableExists("players") + try db.tableExists("player") // [ColumnInfo], the columns in the table - try db.columns(in: "players") + try db.columns(in: "player") // PrimaryKeyInfo - try db.primaryKey("players") + try db.primaryKey("player") // [ForeignKeyInfo], the foreign keys defined on the table - try db.foreignKeys(on: "players") + try db.foreignKeys(on: "player") // [IndexInfo], the indexes defined on the table - try db.indexes(on: "players") + try db.indexes(on: "player") // Bool, true if column(s) is a unique key - try db.table("players", hasUniqueKey: ["email"]) + try db.table("player", hasUniqueKey: ["email"]) } // Bool, true if argument is the name of an internal SQLite table @@ -2094,7 +2095,7 @@ try player.updateChanges(db) // does nothing if score has not changed For batch updates, execute an [SQL query](#executing-updates): ```swift -try db.execute("UPDATE players SET synchronized = 1") +try db.execute("UPDATE player SET synchronized = 1") ``` @@ -2157,7 +2158,7 @@ Details follow: ```swift struct Place { ... } try dbQueue.read { db in - let rows = try Row.fetchAll(db, "SELECT * FROM places") + let rows = try Row.fetchAll(db, "SELECT * FROM place") let places: [Place] = rows.map { row in return Place( id: row["id"], @@ -2175,7 +2176,7 @@ Details follow: ```swift struct Place: FetchableRecord { ... } try dbQueue.read { db in - let places = try Place.fetchAll(db, "SELECT * FROM places") + let places = try Place.fetchAll(db, "SELECT * FROM place") } ``` @@ -2185,7 +2186,7 @@ Details follow: ```swift struct Place: TableRecord { ... } - // SELECT * FROM places ORDER BY title + // SELECT * FROM place ORDER BY title let request = Place.order(Column("title")) ``` @@ -2295,14 +2296,14 @@ The `databaseTableName` type property is the name of a database table. `database ```swift extension Place : TableRecord { - static let databaseTableName = "places" + static let databaseTableName = "place" } ``` Adopting types can be fetched without SQL, using the [query interface](#the-query-interface): ```swift -// SELECT * FROM places WHERE name = 'Paris' +// SELECT * FROM place WHERE name = 'Paris' let paris = try Place.filter(nameColumn == "Paris").fetchOne(db) ``` @@ -2319,14 +2320,14 @@ try Country.fetchAll(db, keys: ["FR", "US"]) // [Country] When the table has no explicit primary key, GRDB uses the [hidden "rowid" column](#the-implicit-rowid-primary-key): ```swift -// SELECT * FROM documents WHERE rowid = 1 +// SELECT * FROM document WHERE rowid = 1 try Document.fetchOne(db, key: 1) // Document? ``` For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary: ```swift -// SELECT * FROM citizenships WHERE playerID = 1 AND countryISOCode = 'FR' +// SELECT * FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Citizenship? ``` @@ -2519,7 +2520,7 @@ struct Player: Codable { // Adopt Record protocols... extension Player: FetchableRecord, PersistableRecord { - static let databaseTableName = "players" + static let databaseTableName = "player" } // ...and you can save and fetch players: @@ -2534,7 +2535,7 @@ GRDB support for Codable works well with "flat" records, whose stored properties ```swift // Can't take profit from Codable code generation: struct Place: FetchableRecord, PersistableRecord, Codable { - static let databaseTableName = "places" + static let databaseTableName = "place" var title: String var coordinate: CLLocationCoordinate2D // <- Not a simple value! @@ -2566,7 +2567,7 @@ struct Place: Codable { // Free database support! extension Place: FetchableRecord, PersistableRecord { - static let databaseTableName = "places" + static let databaseTableName = "place" } ``` @@ -2584,7 +2585,7 @@ struct Place: Codable { } extension Place: FetchableRecord, MutablePersistableRecord { - static let databaseTableName = "places" + static let databaseTableName = "place" mutating func didInsert(with rowID: Int64, for column: String?) { // Update id after insertion @@ -2624,7 +2625,7 @@ class Place: Record { /// The table name override class var databaseTableName: String { - return "places" + return "place" } /// The table columns @@ -2747,36 +2748,36 @@ The [five different policies](https://www.sqlite.org/lang_conflict.html) are: ab - At the table level ```swift - // CREATE TABLE players ( + // CREATE TABLE player ( // id INTEGER PRIMARY KEY AUTOINCREMENT, // email TEXT UNIQUE ON CONFLICT REPLACE // ) - try db.create(table: "players") { t in + try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("email", .text).unique(onConflict: .replace) // <-- } // Despite the unique index on email, both inserts succeed. // The second insert replaces the first row: - try db.execute("INSERT INTO players (email) VALUES (?)", arguments: ["arthur@example.com"]) - try db.execute("INSERT INTO players (email) VALUES (?)", arguments: ["arthur@example.com"]) + try db.execute("INSERT INTO player (email) VALUES (?)", arguments: ["arthur@example.com"]) + try db.execute("INSERT INTO player (email) VALUES (?)", arguments: ["arthur@example.com"]) ``` - At the query level: ```swift - // CREATE TABLE players ( + // CREATE TABLE player ( // id INTEGER PRIMARY KEY AUTOINCREMENT, // email TEXT UNIQUE // ) - try db.create(table: "players") { t in + try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("email", .text).unique() } // Again, despite the unique index on email, both inserts succeed. - try db.execute("INSERT OR REPLACE INTO players (email) VALUES (?)", arguments: ["arthur@example.com"]) - try db.execute("INSERT OR REPLACE INTO players (email) VALUES (?)", arguments: ["arthur@example.com"]) + try db.execute("INSERT OR REPLACE INTO player (email) VALUES (?)", arguments: ["arthur@example.com"]) + try db.execute("INSERT OR REPLACE INTO player (email) VALUES (?)", arguments: ["arthur@example.com"]) ``` When you want to handle conflicts at the query level, specify a custom `persistenceConflictPolicy` in your type that adopts the MutablePersistableRecord or PersistableRecord protocol. It will alter the INSERT and UPDATE queries run by the `insert`, `update` and `save` [persistence methods](#persistence-methods): @@ -2798,7 +2799,7 @@ struct Player : MutablePersistableRecord { update: .replace) } -// INSERT OR REPLACE INTO players (...) VALUES (...) +// INSERT OR REPLACE INTO player (...) VALUES (...) try player.insert(db) ``` @@ -2816,13 +2817,13 @@ try player.insert(db) ```swift // No explicit primary key -try db.create(table: "events") { t in +try db.create(table: "event") { t in t.column("message", .text) t.column("date", .datetime) } // No way to define an explicit primary key -try db.create(virtualTable: "books", using: FTS4()) { t in +try db.create(virtualTable: "book", using: FTS4()) { t in t.column("title") t.column("author") t.column("body") @@ -2834,10 +2835,10 @@ The implicit primary key is stored in the hidden column `rowid`. Hidden means th Some GRDB methods will automatically use this hidden column when a table has no explicit primary key: ```swift -// SELECT * FROM events WHERE rowid = 1 +// SELECT * FROM event WHERE rowid = 1 let event = try Event.fetchOne(db, key: 1) -// DELETE FROM books WHERE rowid = 1 +// DELETE FROM book WHERE rowid = 1 try Book.deleteOne(db, key: 1) ``` @@ -2868,7 +2869,7 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu GRDB will then select the `rowid` column by default: ```swift - // SELECT *, rowid FROM events + // SELECT *, rowid FROM event let events = try Event.fetchAll(db) ``` @@ -2933,7 +2934,7 @@ We will show below how to declare a record type for the following database table ```swift try dbQueue.write { db in - try db.create(table: "places") { t in + try db.create(table: "place") { t in t.autoIncrementedPrimaryKey("id") t.column("title", .text).notNull() t.column("favorite", .boolean).notNull().defaults(to: false) @@ -2976,7 +2977,7 @@ struct Place: Codable { // SQL generation extension Place: TableRecord { /// The table name - static let databaseTableName = "places" + static let databaseTableName = "place" } // Fetching methods @@ -3009,7 +3010,7 @@ struct Place { // SQL generation extension Place: TableRecord { /// The table name - static let databaseTableName = "places" + static let databaseTableName = "place" /// The table columns enum Columns: String, ColumnExpression { @@ -3072,7 +3073,7 @@ class Place: Record { /// The table name override class var databaseTableName: String { - return "places" + return "place" } /// The table columns @@ -3188,13 +3189,13 @@ let count = try request.fetchCount(db) // Int ³ See [SQL queries](#fetch-queries): ```swift -let player = try Player.fetchOne("SELECT * FROM players WHERE id = ?", arguments: [1]) // Player? +let player = try Player.fetchOne("SELECT * FROM player WHERE id = ?", arguments: [1]) // Player? ``` ⁴ See [Prepared Statements](#prepared-statements): ```swift -let statement = try db.makeSelectStatement("SELECT * FROM players WHERE id = ?") +let statement = try db.makeSelectStatement("SELECT * FROM player WHERE id = ?") let player = try Player.fetchOne(statement, arguments: [1]) // Player? ``` @@ -3207,7 +3208,7 @@ The Query Interface ```swift try dbQueue.write { db in // Update database schema - try db.create(table: "wines") { t in ... } + try db.create(table: "wine") { t in ... } // Fetch records let wines = try Wine.filter(origin == "Burgundy").order(price).fetchAll(db) @@ -3227,11 +3228,11 @@ Please bear in mind that the query interface can not generate all possible SQL q ```swift try dbQueue.write { db in // Update database schema (with SQL) - try db.execute("CREATE TABLE wines (...)") + try db.execute("CREATE TABLE wine (...)") // Fetch records (with SQL) let wines = try Wine.fetchAll(db, - "SELECT * FROM wines WHERE origin = ? ORDER BY price", + "SELECT * FROM wine WHERE origin = ? ORDER BY price", arguments: ["Burgundy"]) // Count (with an SQL snippet) @@ -3240,7 +3241,7 @@ try dbQueue.write { db in .fetchCount(db) // Delete (with SQL) - try db.execute("DELETE FROM wines WHERE corked") + try db.execute("DELETE FROM wine WHERE corked") } ``` @@ -3257,6 +3258,7 @@ So don't miss the [SQL API](#sqlite-api). - [Fetching Aggregated Values](#fetching-aggregated-values) - [Delete Requests](#delete-requests) - [Custom Requests](#custom-requests) +- [Associations and Joins](Documentation/AssociationsBasics.md) ## Database Schema @@ -3272,14 +3274,14 @@ Once granted with a [database connection](#database-connections), you can setup ### Create Tables ```swift -// CREATE TABLE places ( +// CREATE TABLE place ( // id INTEGER PRIMARY KEY AUTOINCREMENT, // title TEXT, // favorite BOOLEAN NOT NULL DEFAULT 0, // latitude DOUBLE NOT NULL, // longitude DOUBLE NOT NULL // ) -try db.create(table: "places") { t in +try db.create(table: "place") { t in t.autoIncrementedPrimaryKey("id") t.column("title", .text) t.column("favorite", .boolean).notNull().defaults(to: false) @@ -3290,13 +3292,7 @@ try db.create(table: "places") { t in The `create(table:)` method covers nearly all SQLite table creation features. For virtual tables, see [Full-Text Search](#full-text-search), or use raw SQL. -SQLite has many reference documents about table creation: - -- [CREATE TABLE](https://www.sqlite.org/lang_createtable.html) -- [Datatypes In SQLite Version 3](https://www.sqlite.org/datatype3.html) -- [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html) -- [ON CONFLICT](https://www.sqlite.org/lang_conflict.html) -- [The WITHOUT ROWID Optimization](https://www.sqlite.org/withoutrowid.html) +SQLite itself has many reference documents about table creation: [CREATE TABLE](https://www.sqlite.org/lang_createtable.html), [Datatypes In SQLite Version 3](https://www.sqlite.org/datatype3.html), [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html), [ON CONFLICT](https://www.sqlite.org/lang_conflict.html), [The WITHOUT ROWID Optimization](https://www.sqlite.org/withoutrowid.html). **Configure table creation**: @@ -3308,6 +3304,8 @@ try db.create(table: "example") { t in ... } try db.create(table: "example", temporary: true, ifNotExists: true) { t in ``` +> :bulb: **Tip**: when you create a database table, prefer giving it a name that is singular and camel-cased, such as `place`, `country`, or `postalAddress`. This is the prefered convention for database table names in GRDB. Other names such as `places` or `postal_address` are also valid, but you may have to perform extra configuration steps. + **Add regular columns** with their name and eventual type (text, integer, double, numeric, boolean, blob, date and datetime) - see [SQLite data types](https://www.sqlite.org/datatype3.html): ```swift @@ -3343,8 +3341,8 @@ Use an individual column as **primary**, **unique**, or **foreign key**. When de // email TEXT UNIQUE, t.column("email", .text).unique() - // countryCode TEXT REFERENCES countries(code) ON DELETE CASCADE, - t.column("countryCode", .text).references("countries", onDelete: .cascade) + // countryCode TEXT REFERENCES country(code) ON DELETE CASCADE, + t.column("countryCode", .text).references("country", onDelete: .cascade) ``` > :bulb: **Tip**: when you need an integer primary key that automatically generates unique values, it is highly recommended that you use the `autoIncrementedPrimaryKey` method. @@ -3394,10 +3392,10 @@ SQLite lets you rename tables, and add columns to existing tables: ```swift // ALTER TABLE referers RENAME TO referrers -try db.rename(table: "referers", to: "referrers") +try db.rename(table: "referer", to: "referrer") -// ALTER TABLE players ADD COLUMN url TEXT -try db.alter(table: "players") { t in +// ALTER TABLE player ADD COLUMN url TEXT +try db.alter(table: "player") { t in t.add(column: "url", .text) } ``` @@ -3468,7 +3466,7 @@ You can now build requests with the following methods: `all`, `none`, `select`, - `all()`, `none()`: the requests for all rows, or no row. ```swift - // SELECT * FROM players + // SELECT * FROM player Player.all() ``` @@ -3477,50 +3475,50 @@ You can now build requests with the following methods: `all`, `none`, `select`, - `select(expression, ...)` defines the selected columns. ```swift - // SELECT id, name FROM players + // SELECT id, name FROM player Player.select(idColumn, nameColumn) - // SELECT MAX(score) AS maxScore FROM players + // SELECT MAX(score) AS maxScore FROM player Player.select(max(scoreColumn).aliased("maxScore")) ``` - `distinct()` performs uniquing. ```swift - // SELECT DISTINCT name FROM players + // SELECT DISTINCT name FROM player Player.select(nameColumn).distinct() ``` - `filter(expression)` applies conditions. ```swift - // SELECT * FROM players WHERE id IN (1, 2, 3) + // SELECT * FROM player WHERE id IN (1, 2, 3) Player.filter([1,2,3].contains(idColumn)) - // SELECT * FROM players WHERE (name IS NOT NULL) AND (height > 1.75) + // SELECT * FROM player WHERE (name IS NOT NULL) AND (height > 1.75) Player.filter(nameColumn != nil && heightColumn > 1.75) ``` - `filter(key:)` and `filter(keys:)` apply conditions on primary keys and unique keys: ```swift - // SELECT * FROM players WHERE id = 1 + // SELECT * FROM player WHERE id = 1 Player.filter(key: 1) - // SELECT * FROM countries WHERE isoCode IN ('FR', 'US') + // SELECT * FROM country WHERE isoCode IN ('FR', 'US') Country.filter(keys: ["FR", "US"]) - // SELECT * FROM citizenships WHERE playerID = 1 AND countryISOCode = 'FR' + // SELECT * FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' Citizenship.filter(key: ["playerID": 1, "countryISOCode": "FR"]) - // SELECT * FROM players WHERE email = 'arthur@example.com' + // SELECT * FROM player WHERE email = 'arthur@example.com' Player.filter(key: ["email": "arthur@example.com"]) ``` - `matching(pattern)` performs [full-text search](#full-text-search). ```swift - // SELECT * FROM documents WHERE documents MATCH 'sqlite database' + // SELECT * FROM document WHERE document MATCH 'sqlite database' let pattern = FTS3Pattern(matchingAllTokensIn: "SQLite database") Document.matching(pattern) ``` @@ -3530,7 +3528,7 @@ You can now build requests with the following methods: `all`, `none`, `select`, - `group(expression, ...)` groups rows. ```swift - // SELECT name, MAX(score) FROM players GROUP BY name + // SELECT name, MAX(score) FROM player GROUP BY name Player .select(nameColumn, max(scoreColumn)) .group(nameColumn) @@ -3539,7 +3537,7 @@ You can now build requests with the following methods: `all`, `none`, `select`, - `having(expression)` applies conditions on grouped rows. ```swift - // SELECT team, MAX(score) FROM players GROUP BY team HAVING MIN(score) >= 1000 + // SELECT team, MAX(score) FROM player GROUP BY team HAVING MIN(score) >= 1000 Player .select(teamColumn, max(scoreColumn)) .group(teamColumn) @@ -3549,55 +3547,55 @@ You can now build requests with the following methods: `all`, `none`, `select`, - `order(ordering, ...)` sorts. ```swift - // SELECT * FROM players ORDER BY name + // SELECT * FROM player ORDER BY name Player.order(nameColumn) - // SELECT * FROM players ORDER BY score DESC, name + // SELECT * FROM player ORDER BY score DESC, name Player.order(scoreColumn.desc, nameColumn) ``` Each `order` call clears any previous ordering: ```swift - // SELECT * FROM players ORDER BY name + // SELECT * FROM player ORDER BY name Player.order(scoreColumn).order(nameColumn) ``` - `reversed()` reverses the eventual orderings. ```swift - // SELECT * FROM players ORDER BY score ASC, name DESC + // SELECT * FROM player ORDER BY score ASC, name DESC Player.order(scoreColumn.desc, nameColumn).reversed() ``` If no ordering was already specified, this method has no effect: ```swift - // SELECT * FROM players + // SELECT * FROM player Player.all().reversed() ``` - `limit(limit, offset: offset)` limits and pages results. ```swift - // SELECT * FROM players LIMIT 5 + // SELECT * FROM player LIMIT 5 Player.limit(5) - // SELECT * FROM players LIMIT 5 OFFSET 10 + // SELECT * FROM player LIMIT 5 OFFSET 10 Player.limit(5, offset: 10) ``` You can refine requests by chaining those methods: ```swift -// SELECT * FROM players WHERE (email IS NOT NULL) ORDER BY name +// SELECT * FROM player WHERE (email IS NOT NULL) ORDER BY name Player.order(nameColumn).filter(emailColumn != nil) ``` The `select`, `order`, `group`, and `limit` methods ignore and replace previously applied selection, orderings, grouping, and limits. On the opposite, `filter`, `matching`, and `having` methods extend the query: ```swift -Player // SELECT * FROM players +Player // SELECT * FROM player .filter(nameColumn != nil) // WHERE (name IS NOT NULL) .filter(emailColumn != nil) // AND (email IS NOT NULL) .order(nameColumn) // - ignored - @@ -3611,7 +3609,7 @@ Player // SELECT * FROM players Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html): ```swift -// SELECT DATE(creationDate), COUNT(*) FROM players WHERE name = 'Arthur' GROUP BY date(creationDate) +// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) Player .select(sql: "DATE(creationDate), COUNT(*)") .filter(sql: "name = ?", arguments: ["Arthur"]) @@ -3624,7 +3622,7 @@ Player By default, query interface requests select all columns: ```swift -// SELECT * FROM players +// SELECT * FROM player let request = Player.all() ``` @@ -3633,10 +3631,10 @@ let request = Player.all() To specify the selection of a specific request, use the `select` method: ```swift -// SELECT id, name FROM players +// SELECT id, name FROM player let request = Player.select(Column("id"), Column("name")) -// SELECT *, rowid FROM players +// SELECT *, rowid FROM player let request = Player.select(AllColumns(), Column.rowID) ``` @@ -3644,19 +3642,19 @@ To specify the default selection for all requests built from a type, define the ```swift struct RestrictedPlayer : TableRecord { - static let databaseTableName = "players" + static let databaseTableName = "player" static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")] } struct ExtendedPlayer : TableRecord { - static let databaseTableName = "players" + static let databaseTableName = "player" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] } -// SELECT id, name FROM players +// SELECT id, name FROM player let request = RestrictedPlayer.all() -// SELECT *, rowid FROM players +// SELECT *, rowid FROM player let request = ExtendedPlayer.all() ``` @@ -3675,16 +3673,16 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Comparison operators are based on the Swift operators `==`, `!=`, `===`, `!==`, `<`, `<=`, `>`, `>=`: ```swift - // SELECT * FROM players WHERE (name = 'Arthur') + // SELECT * FROM player WHERE (name = 'Arthur') Player.filter(nameColumn == "Arthur") - // SELECT * FROM players WHERE (name IS NULL) + // SELECT * FROM player WHERE (name IS NULL) Player.filter(nameColumn == nil) - // SELECT * FROM players WHERE (score IS 1000) + // SELECT * FROM player WHERE (score IS 1000) Player.filter(scoreColumn === 1000) - // SELECT * FROM rectangles WHERE width < height + // SELECT * FROM rectangle WHERE width < height Rectangle.filter(widthColumn < heightColumn) ``` @@ -3695,7 +3693,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: SQLite arithmetic operators are derived from their Swift equivalent: ```swift - // SELECT ((temperature * 1.8) + 32) AS farenheit FROM players + // SELECT ((temperature * 1.8) + 32) AS farenheit FROM planet Planet.select((temperatureColumn * 1.8 + 32).aliased("farenheit")) ``` @@ -3706,14 +3704,14 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: The SQL logical operators are derived from the Swift `&&`, `||` and `!`: ```swift - // SELECT * FROM players WHERE ((NOT verified) OR (score < 1000)) + // SELECT * FROM player WHERE ((NOT verified) OR (score < 1000)) Player.filter(!verifiedColumn || scoreColumn < 1000) ``` When you want to join a sequence of expressions with `AND` or `OR` operators, use `joined(operator:)`: ```swift - // SELECT * FROM players WHERE (verified AND (score >= 1000) AND (name IS NOT NULL)) + // SELECT * FROM player WHERE (verified AND (score >= 1000) AND (name IS NOT NULL)) let conditions = [ verifiedColumn, scoreColumn >= 1000, @@ -3724,10 +3722,10 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: When the sequence is empty, `joined(operator: .and)` returns true, and `joined(operator: .or)` returns false: ```swift - // SELECT * FROM players WHERE 1 + // SELECT * FROM player WHERE 1 Player.filter([].joined(operator: .and)) - // SELECT * FROM players WHERE 0 + // SELECT * FROM player WHERE 0 Player.filter([].joined(operator: .or)) ``` @@ -3736,22 +3734,22 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: To check inclusion in a Swift sequence (array, set, range…), call the `contains` method: ```swift - // SELECT * FROM players WHERE id IN (1, 2, 3) + // SELECT * FROM player WHERE id IN (1, 2, 3) Player.filter([1, 2, 3].contains(idColumn)) - // SELECT * FROM players WHERE id NOT IN (1, 2, 3) + // SELECT * FROM player WHERE id NOT IN (1, 2, 3) Player.filter(![1, 2, 3].contains(idColumn)) - // SELECT * FROM players WHERE score BETWEEN 0 AND 1000 + // SELECT * FROM player WHERE score BETWEEN 0 AND 1000 Player.filter((0...1000).contains(scoreColumn)) - // SELECT * FROM players WHERE (score >= 0) AND (score < 1000) + // SELECT * FROM player WHERE (score >= 0) AND (score < 1000) Player.filter((0..<1000).contains(scoreColumn)) - // SELECT * FROM players WHERE initial BETWEEN 'A' AND 'N' + // SELECT * FROM player WHERE initial BETWEEN 'A' AND 'N' Player.filter(("A"..."N").contains(initialColumn)) - // SELECT * FROM players WHERE (initial >= 'A') AND (initial < 'N') + // SELECT * FROM player WHERE (initial >= 'A') AND (initial < 'N') Player.filter(("A"..<"N").contains(initialColumn)) ``` @@ -3762,7 +3760,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: The SQLite LIKE operator is available as the `like` method: ```swift - // SELECT * FROM players WHERE (email LIKE '%@example.com') + // SELECT * FROM player WHERE (email LIKE '%@example.com') Player.filter(emailColumn.like("%@example.com")) ``` @@ -3777,10 +3775,10 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ```swift let pattern = FTS3Pattern(matchingAllTokensIn: "SQLite database") - // SELECT * FROM documents WHERE documents MATCH 'sqlite database' + // SELECT * FROM document WHERE document MATCH 'sqlite database' Document.matching(pattern) - // SELECT * FROM documents WHERE content MATCH 'sqlite database' + // SELECT * FROM document WHERE content MATCH 'sqlite database' Document.filter(contentColumn.match(pattern)) ``` @@ -3789,7 +3787,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ```swift let pattern = FTS5Pattern(matchingAllTokensIn: "SQLite database") - // SELECT * FROM documents WHERE documents MATCH 'sqlite database' + // SELECT * FROM document WHERE document MATCH 'sqlite database' Document.matching(pattern) ``` @@ -3801,13 +3799,13 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Those are based on the `abs`, `average`, `count`, `length`, `max`, `min` and `sum` Swift functions: ```swift - // SELECT MIN(score), MAX(score) FROM players + // SELECT MIN(score), MAX(score) FROM player Player.select(min(scoreColumn), max(scoreColumn)) - // SELECT COUNT(name) FROM players + // SELECT COUNT(name) FROM player Player.select(count(nameColumn)) - // SELECT COUNT(DISTINCT name) FROM players + // SELECT COUNT(DISTINCT name) FROM player Player.select(count(distinct: nameColumn)) ``` @@ -3816,10 +3814,10 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Use the Swift `??` operator: ```swift - // SELECT IFNULL(name, 'Anonymous') FROM players + // SELECT IFNULL(name, 'Anonymous') FROM player Player.select(nameColumn ?? "Anonymous") - // SELECT IFNULL(name, email) FROM players + // SELECT IFNULL(name, email) FROM player Player.select(nameColumn ?? emailColumn) ``` @@ -3852,7 +3850,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ```swift let f = DatabaseFunction("f", ...) - // SELECT f(name) FROM players + // SELECT f(name) FROM player Player.select(f.apply(nameColumn)) ``` @@ -3910,60 +3908,60 @@ request.rx **Fetching records according to their primary key** is a very common task. It has a shortcut which accepts any single-column primary key: ```swift -// SELECT * FROM players WHERE id = 1 +// SELECT * FROM player WHERE id = 1 try Player.fetchOne(db, key: 1) // Player? -// SELECT * FROM players WHERE id IN (1, 2, 3) +// SELECT * FROM player WHERE id IN (1, 2, 3) try Player.fetchAll(db, keys: [1, 2, 3]) // [Player] -// SELECT * FROM players WHERE isoCode = 'FR' +// SELECT * FROM player WHERE isoCode = 'FR' try Country.fetchOne(db, key: "FR") // Country? -// SELECT * FROM countries WHERE isoCode IN ('FR', 'US') +// SELECT * FROM country WHERE isoCode IN ('FR', 'US') try Country.fetchAll(db, keys: ["FR", "US"]) // [Country] ``` When the table has no explicit primary key, GRDB uses the [hidden "rowid" column](#the-implicit-rowid-primary-key): ```swift -// SELECT * FROM documents WHERE rowid = 1 +// SELECT * FROM document WHERE rowid = 1 try Document.fetchOne(db, key: 1) // Document? ``` For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary: ```swift -// SELECT * FROM citizenships WHERE playerID = 1 AND countryISOCode = 'FR' +// SELECT * FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Citizenship? -// SELECT * FROM players WHERE email = 'arthur@example.com' +// SELECT * FROM player WHERE email = 'arthur@example.com' try Player.fetchOne(db, key: ["email": "arthur@example.com"]) // Player? ``` **When you want to build a request and plan to fetch from it later**, use the `filter(key:)` and `filter(keys:)` methods: ```swift -// SELECT * FROM players WHERE id = 1 +// SELECT * FROM player WHERE id = 1 let request = Player.filter(key: 1) let player = try request.fetchOne(db) // Player? -// SELECT * FROM players WHERE id IN (1, 2, 3) +// SELECT * FROM player WHERE id IN (1, 2, 3) let request = Player.filter(keys: [1, 2, 3]) let players = try request.fetchAll(db) // [Player] -// SELECT * FROM players WHERE isoCode = 'FR' +// SELECT * FROM player WHERE isoCode = 'FR' let request = Country.filter(key: "FR") let country = try request.fetchOne(db) // Country? -// SELECT * FROM countries WHERE isoCode IN ('FR', 'US') +// SELECT * FROM country WHERE isoCode IN ('FR', 'US') let request = Country.filter(keys: ["FR", "US"]) let countries = try request.fetchAll(db) // [Country] -// SELECT * FROM citizenships WHERE playerID = 1 AND countryISOCode = 'FR' +// SELECT * FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' let request = Citizenship.filter(key: ["playerID": 1, "countryISOCode": "FR"]) let citizenship = request.fetchOne(db) // Citizenship? -// SELECT * FROM players WHERE email = 'arthur@example.com' +// SELECT * FROM player WHERE email = 'arthur@example.com' let request = Player.filter(key: ["email": "arthur@example.com"]) let player = try request.fetchOne(db) // Player? ``` @@ -3984,16 +3982,16 @@ Player.filter(key: 1).rx **Requests can count.** The `fetchCount()` method returns the number of rows that would be returned by a fetch request: ```swift -// SELECT COUNT(*) FROM players +// SELECT COUNT(*) FROM player let count = try Player.fetchCount(db) // Int -// SELECT COUNT(*) FROM players WHERE email IS NOT NULL +// SELECT COUNT(*) FROM player WHERE email IS NOT NULL let count = try Player.filter(emailColumn != nil).fetchCount(db) -// SELECT COUNT(DISTINCT name) FROM players +// SELECT COUNT(DISTINCT name) FROM player let count = try Player.select(nameColumn).distinct().fetchCount(db) -// SELECT COUNT(*) FROM (SELECT DISTINCT name, score FROM players) +// SELECT COUNT(*) FROM (SELECT DISTINCT name, score FROM player) let count = try Player.select(nameColumn, scoreColumn).distinct().fetchCount(db) ``` @@ -4016,7 +4014,7 @@ let maxScore = row[1] as Int? **Requests can delete records**, with the `deleteAll()` method: ```swift -// DELETE FROM players WHERE email IS NULL +// DELETE FROM player WHERE email IS NULL let request = Player.filter(emailColumn == nil) try request.deleteAll(db) ``` @@ -4026,33 +4024,33 @@ try request.deleteAll(db) **Deleting records according to their primary key** is also quite common. It has a shortcut which accepts any single-column primary key: ```swift -// DELETE FROM players WHERE id = 1 +// DELETE FROM player WHERE id = 1 try Player.deleteOne(db, key: 1) -// DELETE FROM players WHERE id IN (1, 2, 3) +// DELETE FROM player WHERE id IN (1, 2, 3) try Player.deleteAll(db, keys: [1, 2, 3]) -// DELETE FROM players WHERE isoCode = 'FR' +// DELETE FROM player WHERE isoCode = 'FR' try Country.deleteOne(db, key: "FR") -// DELETE FROM countries WHERE isoCode IN ('FR', 'US') +// DELETE FROM country WHERE isoCode IN ('FR', 'US') try Country.deleteAll(db, keys: ["FR", "US"]) ``` When the table has no explicit primary key, GRDB uses the [hidden "rowid" column](#the-implicit-rowid-primary-key): ```swift -// DELETE FROM documents WHERE rowid = 1 +// DELETE FROM document WHERE rowid = 1 try Document.deleteOne(db, key: 1) ``` For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary: ```swift -// DELETE FROM citizenships WHERE playerID = 1 AND countryISOCode = 'FR' +// DELETE FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' try Citizenship.deleteOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) -// DELETE FROM players WHERE email = 'arthur@example.com' +// DELETE FROM player WHERE email = 'arthur@example.com' Player.deleteOne(db, key: ["email": "arthur@example.com"]) ``` @@ -4203,7 +4201,7 @@ let request = Player.all() extension Player { static func filter(color: Color) -> SQLRequest { let request = SQLRequest( - "SELECT * FROM players WHERE color = ?" + "SELECT * FROM player WHERE color = ?" arguments: [color]) } } @@ -4245,7 +4243,7 @@ For example: ```swift let playerRequest = SQLRequest( - "SELECT * FROM players WHERE color = ?" + "SELECT * FROM player WHERE color = ?" arguments: [color]) try request.fetchAll(db) // [Player] ``` @@ -4280,22 +4278,22 @@ Inside each migration, you typically [define and update your database tables](#d ```swift var migrator = DatabaseMigrator() -// v1 database +// 1st migration migrator.registerMigration("v1") { db in - try db.create(table: "players") { t in ... } - try db.create(table: "books") { t in ... } + try db.create(table: "author") { t in ... } + try db.create(table: "book") { t in ... } try db.create(index: ...) } -// v2 database +// 2nd migration migrator.registerMigration("v2") { db in - try db.alter(table: "players") { t in ... } + try db.alter(table: "author") { t in ... } } // Migrations for future versions will be inserted here: // -// // v3 database -// migrator.registerMigration("v3") { db in +// // 3rd migration +// migrator.registerMigration("...") { db in // ... // } ``` @@ -4341,15 +4339,15 @@ SQLite does not support many schema changes, and won't let you drop a table colu Yet any kind of schema change is still possible. The SQLite documentation explains in detail how to do so: https://www.sqlite.org/lang_altertable.html#otheralter. This technique requires the temporary disabling of foreign key checks, and is supported by the `registerMigrationWithDeferredForeignKeyCheck` function: ```swift -// Add a NOT NULL constraint on players.name: +// Add a NOT NULL constraint on player.name: migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - try db.create(table: "new_players") { t in + try db.create(table: "new_player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() } - try db.execute("INSERT INTO new_players SELECT * FROM players") - try db.drop(table: "players") - try db.rename(table: "new_players", to: "players") + try db.execute("INSERT INTO new_player SELECT * FROM player") + try db.drop(table: "player") + try db.rename(table: "new_player", to: "player") } ``` @@ -4362,7 +4360,7 @@ While your migration code runs with disabled foreign key checks, those are re-en ```swift // Create full-text tables -try db.create(virtualTable: "books", using: FTS4()) { t in // or FTS3(), or FTS5() +try db.create(virtualTable: "book", using: FTS4()) { t in // or FTS3(), or FTS5() t.column("author") t.column("title") t.column("body") @@ -4371,7 +4369,7 @@ try db.create(virtualTable: "books", using: FTS4()) { t in // or FTS3(), or FTS5 // Populate full-text table with records or SQL try Book(...).insert(db) try db.execute( - "INSERT INTO books (author, title, body) VALUES (?, ?, ?)", + "INSERT INTO book (author, title, body) VALUES (?, ?, ?)", arguments: [...]) // Build search patterns @@ -4380,7 +4378,7 @@ let pattern = FTS3Pattern(matchingPhrase: "Moby-Dick") // Search with the query interface or SQL let books = try Book.matching(pattern).fetchAll(db) let books = try Book.fetchAll(db, - "SELECT * FROM books WHERE books MATCH ?", + "SELECT * FROM book WHERE book MATCH ?", arguments: [pattern]) ``` @@ -4453,13 +4451,13 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do Create tables with the `create(virtualTable:using:)` method: ```swift -// CREATE VIRTUAL TABLE documents USING fts3(content) -try db.create(virtualTable: "documents", using: FTS3()) { t in +// CREATE VIRTUAL TABLE document USING fts3(content) +try db.create(virtualTable: "document", using: FTS3()) { t in t.column("content") } -// CREATE VIRTUAL TABLE documents USING fts4(content) -try db.create(virtualTable: "documents", using: FTS4()) { t in +// CREATE VIRTUAL TABLE document USING fts4(content) +try db.create(virtualTable: "document", using: FTS4()) { t in t.column("content") } ``` @@ -4469,13 +4467,13 @@ try db.create(virtualTable: "documents", using: FTS4()) { t in You can specify a [tokenizer](#fts3-and-fts4-tokenizers): ```swift -// CREATE VIRTUAL TABLE books USING fts4( +// CREATE VIRTUAL TABLE book USING fts4( // tokenize=porter, // author, // title, // body // ) -try db.create(virtualTable: "books", using: FTS4()) { t in +try db.create(virtualTable: "book", using: FTS4()) { t in t.tokenizer = .porter t.column("author") t.column("title") @@ -4486,7 +4484,7 @@ try db.create(virtualTable: "books", using: FTS4()) { t in FTS4 supports [options](https://www.sqlite.org/fts3.html#fts4_options): ```swift -// CREATE VIRTUAL TABLE books USING fts4( +// CREATE VIRTUAL TABLE book USING fts4( // content, // uuid, // content="", @@ -4496,7 +4494,7 @@ FTS4 supports [options](https://www.sqlite.org/fts3.html#fts4_options): // notindexed=uuid, // languageid=lid // ) -try db.create(virtualTable: "documents", using: FTS4()) { t in +try db.create(virtualTable: "document", using: FTS4()) { t in t.content = "" t.compress = "zip" t.uncompress = "unzip" @@ -4520,7 +4518,7 @@ See [SQLite documentation](https://www.sqlite.org/fts3.html) for more informatio SQLite ships with three built-in FTS3/4 tokenizers: `simple`, `porter` and `unicode61` that use different algorithms to match queries with indexed content: ```swift -try db.create(virtualTable: "books", using: FTS4()) { t in +try db.create(virtualTable: "book", using: FTS4()) { t in // Pick one: t.tokenizer = .simple // default t.tokenizer = .porter @@ -4545,7 +4543,7 @@ See below some examples of matches: - **simple** ```swift - try db.create(virtualTable: "books", using: FTS4()) { t in + try db.create(virtualTable: "book", using: FTS4()) { t in t.tokenizer = .simple // default } ``` @@ -4559,7 +4557,7 @@ See below some examples of matches: - **porter** ```swift - try db.create(virtualTable: "books", using: FTS4()) { t in + try db.create(virtualTable: "book", using: FTS4()) { t in t.tokenizer = .porter } ``` @@ -4571,7 +4569,7 @@ See below some examples of matches: - **unicode61** ```swift - try db.create(virtualTable: "books", using: FTS4()) { t in + try db.create(virtualTable: "book", using: FTS4()) { t in t.tokenizer = .unicode61() t.tokenizer = .unicode61(removeDiacritics: false) } @@ -4641,7 +4639,7 @@ FTS3Pattern are regular [values](#values). You can use them as query [arguments] ```swift let documents = try Document.fetchAll(db, - "SELECT * FROM documents WHERE content MATCH ?", + "SELECT * FROM document WHERE content MATCH ?", arguments: [pattern]) ``` @@ -4665,8 +4663,8 @@ To use FTS5, you'll need a [custom SQLite build](Documentation/CustomSQLiteBuild Create FTS5 tables with the `create(virtualTable:using:)` method: ```swift -// CREATE VIRTUAL TABLE documents USING fts5(content) -try db.create(virtualTable: "documents", using: FTS5()) { t in +// CREATE VIRTUAL TABLE document USING fts5(content) +try db.create(virtualTable: "document", using: FTS5()) { t in t.column("content") } ``` @@ -4676,13 +4674,13 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in You can specify a [tokenizer](#fts5-tokenizers): ```swift -// CREATE VIRTUAL TABLE books USING fts5( +// CREATE VIRTUAL TABLE book USING fts5( // tokenize='porter', // author, // title, // body // ) -try db.create(virtualTable: "books", using: FTS5()) { t in +try db.create(virtualTable: "book", using: FTS5()) { t in t.tokenizer = .porter() t.column("author") t.column("title") @@ -4693,7 +4691,7 @@ try db.create(virtualTable: "books", using: FTS5()) { t in FTS5 supports [options](https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization): ```swift -// CREATE VIRTUAL TABLE books USING fts5( +// CREATE VIRTUAL TABLE book USING fts5( // content, // uuid UNINDEXED, // content='table', @@ -4702,7 +4700,7 @@ FTS5 supports [options](https://www.sqlite.org/fts5.html#fts5_table_creation_and // columnsize=0, // detail=column // ) -try db.create(virtualTable: "documents", using: FTS5()) { t in +try db.create(virtualTable: "document", using: FTS5()) { t in t.column("content") t.column("uuid").notIndexed() t.content = "table" @@ -4725,7 +4723,7 @@ See [SQLite documentation](https://www.sqlite.org/fts5.html) for more informatio SQLite ships with three built-in FTS5 tokenizers: `ascii`, `porter` and `unicode61` that use different algorithms to match queries with indexed content. ```swift -try db.create(virtualTable: "books", using: FTS5()) { t in +try db.create(virtualTable: "book", using: FTS5()) { t in // Pick one: t.tokenizer = .unicode61() // default t.tokenizer = .unicode61(...) @@ -4751,7 +4749,7 @@ See below some examples of matches: - **unicode61** ```swift - try db.create(virtualTable: "books", using: FTS5()) { t in + try db.create(virtualTable: "book", using: FTS5()) { t in t.tokenizer = .unicode61() t.tokenizer = .unicode61(removeDiacritics: false) } @@ -4766,7 +4764,7 @@ See below some examples of matches: - **ascii** ```swift - try db.create(virtualTable: "books", using: FTS5()) { t in + try db.create(virtualTable: "book", using: FTS5()) { t in t.tokenizer = .ascii } ``` @@ -4780,7 +4778,7 @@ See below some examples of matches: - **porter** ```swift - try db.create(virtualTable: "books", using: FTS5()) { t in + try db.create(virtualTable: "book", using: FTS5()) { t in t.tokenizer = .porter() // porter wrapping unicode61 (the default) t.tokenizer = .porter(.ascii) // porter wrapping ascii t.tokenizer = .porter(.unicode61(removeDiacritics: false)) // porter wrapping unicode61 without diacritics stripping @@ -4824,11 +4822,11 @@ The `Database.makeFTS5Pattern(rawPattern:forTable:)` method validates your raw p ```swift // OK: FTS5Pattern -try db.makeFTS5Pattern(rawPattern: "sqlite", forTable: "books") +try db.makeFTS5Pattern(rawPattern: "sqlite", forTable: "book") // DatabaseError: syntax error near \"AND\" -try db.makeFTS5Pattern(rawPattern: "AND", forTable: "books") +try db.makeFTS5Pattern(rawPattern: "AND", forTable: "book") // DatabaseError: no such column: missing -try db.makeFTS5Pattern(rawPattern: "missing: sqlite", forTable: "books") +try db.makeFTS5Pattern(rawPattern: "missing: sqlite", forTable: "book") ``` The FTS5Pattern initializers don't throw. They build a valid pattern from any string, **including strings provided by users of your application**. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application: @@ -4856,7 +4854,7 @@ FTS5Pattern are regular [values](#values). You can use them as query [arguments] ```swift let documents = try Document.fetchAll(db, - "SELECT * FROM documents WHERE documents MATCH ?", + "SELECT * FROM document WHERE document MATCH ?", arguments: [pattern]) ``` @@ -4874,7 +4872,7 @@ let documents = try Document.matching(pattern).fetchAll(db) ```swift // SQL let documents = try Document.fetchAll(db, - "SELECT * FROM documents WHERE documents MATCH ? ORDER BY rank", + "SELECT * FROM document WHERE document MATCH ? ORDER BY rank", arguments: [pattern]) // Query Interface @@ -4896,7 +4894,7 @@ The two tables must be kept up-to-date, so that the full-text index matches the ```swift // A regular table -try db.create(table: "books") { t in +try db.create(table: "book") { t in t.column("author", .text) t.column("title", .text) t.column("content", .text) @@ -4904,8 +4902,8 @@ try db.create(table: "books") { t in } // A full-text table synchronized with the regular table -try db.create(virtualTable: "books_ft", using: FTS4()) { t in // or FTS5() - t.synchronize(withTable: "books") +try db.create(virtualTable: "book_ft", using: FTS4()) { t in // or FTS5() + t.synchronize(withTable: "book") t.column("author") t.column("title") t.column("content") @@ -4931,26 +4929,26 @@ To drop those triggers, use the `dropFTS4SynchronizationTriggers` or `dropFTS5Sy ```swift // Create tables -try db.create(table: "books") { t in +try db.create(table: "book") { t in ... } -try db.create(virtualTable: "books_ft", using: FTS4()) { t in - t.synchronize(withTable: "books") +try db.create(virtualTable: "book_ft", using: FTS4()) { t in + t.synchronize(withTable: "book") ... } // Drop full-text table -try db.drop(table: "books_ft") -try db.dropFTS4SynchronizationTriggers(forTable: "books_ft") +try db.drop(table: "book_ft") +try db.dropFTS4SynchronizationTriggers(forTable: "book_ft") ``` > :warning: **Warning**: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers **twice**: once with the name of the deleted full-text table, and once with the name of the content table: > > ```swift > // Drop full-text table -> try db.drop(table: "books_ft") -> try db.dropFTS4SynchronizationTriggers(forTable: "books_ft") -> try db.dropFTS4SynchronizationTriggers(forTable: "books") // Support for GRDB <= 2.3.1 +> try db.drop(table: "book_ft") +> try db.dropFTS4SynchronizationTriggers(forTable: "book_ft") +> try db.dropFTS4SynchronizationTriggers(forTable: "book") // Support for GRDB <= 2.3.1 > ``` @@ -4965,7 +4963,7 @@ That is because SQLite will throw an error when you try to perform a full-text s ```swift // SQLite error 1: unable to use function MATCH in the requested context -// SELECT * FROM books WHERE books MATCH '...' +// SELECT * FROM book WHERE book MATCH '...' let books = Book.matching(pattern).fetchAll(db) ``` @@ -4973,11 +4971,11 @@ The solution is to perform a joined request, using raw SQL: ```swift let sql = """ - SELECT books.* - FROM books - JOIN books_ft ON - books_ft.rowid = books.rowid AND - books_ft MATCH ? + SELECT book.* + FROM book + JOIN book_ft + ON book_ft.rowid = book.rowid + AND book_ft MATCH ? """ let books = Book.fetchAll(db, sql, arguments: [pattern]) ``` @@ -5017,18 +5015,18 @@ In this chapter, we will focus on the extraction of information from complex row ```sql -- How to consume the left, middle, and right parts of those rows? -SELECT players.*, teams.*, MAX(rounds.score) AS maxScore -FROM players -LEFT JOIN teams ON ... -LEFT JOIN rounds ON ... +SELECT player.*, team.*, MAX(round.score) AS maxScore +FROM player +LEFT JOIN team ON ... +LEFT JOIN round ON ... GROUP BY ... ``` -We will not talk about *building* joined queries. +We will not talk about *generating* joined queries, which is covered in [Associations](Documentation/AssociationsBasics.md). **So what are we talking about?** -It is difficult to consume rows fetched from complex joined queries, because they often contain several columns with the same name: `id` from table `players`, `id` from table `teams`, etc. +It is difficult to consume rows fetched from complex joined queries, because they often contain several columns with the same name: `id` from table `player`, `id` from table `team`, etc. When such ambiguity happens, GRDB row accessors always favor the leftmost matching column. This means that `row["id"]` would give a player id, whithout any obvious way to access the team id. @@ -5036,10 +5034,10 @@ A classical technique to avoid this ambiguity is to give each column a unique na ```sql -- A classical technique -SELECT players.id AS players_id, players.name AS players_name, teams.id AS teams_id, teams.name AS teams_name, teams.color AS teams_color, MAX(rounds.score) AS maxScore -FROM players -LEFT JOIN teams ON ... -LEFT JOIN rounds ON ... +SELECT player.id AS player_id, player.name AS player_name, team.id AS team_id, team.name AS team_name, team.color AS team_color, MAX(round.score) AS maxScore +FROM player +LEFT JOIN team ON ... +LEFT JOIN round ON ... GROUP BY ... ``` @@ -5047,11 +5045,11 @@ This technique works pretty well, but it has three drawbacks: 1. The selection becomes hard to read and understand. 2. Such queries are difficult to write by hand. -3. The mangled names are a *very* bad fit for [FetchableRecord] types that expect specific column names. After all, if the `Team` record type can read `SELECT * FROM teams ...`, it should be able to read `SELECT ..., teams.*, ...` as well. +3. The mangled names are a *very* bad fit for [FetchableRecord] types that expect specific column names. After all, if the `Team` record type can read `SELECT * FROM team ...`, it should be able to read `SELECT ..., team.*, ...` as well. We thus need another technique. **Below we'll see how to split rows into slices, and preserve column names.** -`SELECT players.*, teams.*, MAX(rounds.score) AS maxScore FROM ...` will be splitted into three slices: one that contains player's columns, one that contains team's columns, and a remaining slice that contains remaining column(s). The Player record type will be able to read the first slice, which contains the colums expected by the `Player.init(row:)` initializer. In the same way, the Team record type could read the second slice. +`SELECT player.*, team.*, MAX(round.score) AS maxScore FROM ...` will be splitted into three slices: one that contains player's columns, one that contains team's columns, and a remaining slice that contains remaining column(s). The Player record type will be able to read the first slice, which contains the colums expected by the `Player.init(row:)` initializer. In the same way, the Team record type could read the second slice. Unlike the name-mangling technique, splitting rows keeps SQL legible, accepts your hand-crafted SQL queries, and plays as nicely as possible with your existing [record types](#records). @@ -5072,30 +5070,30 @@ At the very beginning, there is an SQL query: ```swift try dbQueue.read { db in let sql = """ - SELECT players.*, teams.*, MAX(rounds.score) AS maxScore - FROM players - LEFT JOIN teams ON ... - LEFT JOIN rounds ON ... + SELECT player.*, team.*, MAX(round.score) AS maxScore + FROM player + LEFT JOIN team ON ... + LEFT JOIN round ON ... GROUP BY ... """ ``` -We need an adapter that extracts players' columns, in a slice that has as many columns as there are columns in the players table. That's [RangeRowAdapter](#rangerowadapter): +We need an adapter that extracts player columns, in a slice that has as many columns as there are columns in the player table. That's [RangeRowAdapter](#rangerowadapter): ```swift - // SELECT players.*, teams.*, ... - // <-------> - let playersWidth = try db.columns(in: "players").count - let playerAdapter = RangeRowAdapter(0 ..< playersWidth) + // SELECT player.*, team.*, ... + // <------> + let playerWidth = try db.columns(in: "player").count + let playerAdapter = RangeRowAdapter(0 ..< playerWidth) ``` -We also need an adapter that extracts teams' columns: +We also need an adapter that extracts team columns: ```swift - // SELECT players.*, teams.*, ... - // <-----> - let teamsWidth = try db.columns(in: "teams").count - let teamAdapter = RangeRowAdapter(playersWidth ..< (playersWidth + teamsWidth)) + // SELECT player.*, team.*, ... + // <----> + let teamWidth = try db.columns(in: "team").count + let teamAdapter = RangeRowAdapter(playerWidth ..< (playerWidth + teamWidth)) ``` We merge those two adapters in a single [ScopeAdapter](#scopeadapter) that will allow us to access both sliced rows: @@ -5187,23 +5185,23 @@ extension PlayerInfo { static func fetchAll(_ db: Database) throws -> [PlayerInfo] { ``` -To acknowledge that both Player and Team records may customize their selection of the "players" and "teams" columns, we'll write our SQL in a slightly different way: +To acknowledge that both Player and Team records may customize their selection of the "player" and "team" columns, we'll write our SQL in a slightly different way: ```swift // Let Player and Team customize their selection: let sql = """ SELECT - \(Player.selectionSQL()), -- instead of players.* - \(Team.selectionSQL()), -- instead of teams.* - MAX(rounds.score) AS maxScore - FROM players - LEFT JOIN teams ON ... - LEFT JOIN rounds ON ... + \(Player.selectionSQL()), -- instead of player.* + \(Team.selectionSQL()), -- instead of team.* + MAX(round.score) AS maxScore + FROM player + LEFT JOIN team ON ... + LEFT JOIN round ON ... GROUP BY ... """ ``` -`Player.selectionSQL()` will output `players.*`, unless Player defines a [customized selection](#columns-selected-by-a-request). +`Player.selectionSQL()` will output `player.*`, unless Player defines a [customized selection](#columns-selected-by-a-request). > :point_up: **Note**: you may also use SQL table aliases: > @@ -5213,14 +5211,14 @@ To acknowledge that both Player and Team records may customize their selection o > \(Player.selectionSQL(alias: "p")), > \(Team.selectionSQL(alias: "t")), > MAX(r.score) AS maxScore -> FROM players p -> LEFT JOIN teams t ON ... -> LEFT JOIN rounds r ON ... +> FROM player p +> LEFT JOIN team t ON ... +> LEFT JOIN round r ON ... > GROUP BY ... > """ > ``` -Now is the time to build adapters (taking in account the customized selection of both players and teams). We use the `splittingRowAdapters` global function, which builds row adapters of desired widths: +Now is the time to build adapters (taking in account the customized selection of both player and team). We use the `splittingRowAdapters` global function, which builds row adapters of desired widths: ```swift let adapters = try splittingRowAdapters(columnCounts: [ @@ -5232,7 +5230,7 @@ Now is the time to build adapters (taking in account the customized selection of Scopes.team: adapters[1]]) ``` -> :point_up: **Note**: `splittingRowAdapters` returns as many adapters as necessary to fully split a row. In the example above, it returns *three* adapters: one for players, one for teams, and one for the remaining columns. +> :point_up: **Note**: `splittingRowAdapters` returns as many adapters as necessary to fully split a row. In the example above, it returns *three* adapters: one for player, one for team, and one for the remaining columns. And finally, we can fetch player infos: @@ -5298,10 +5296,10 @@ extension PlayerInfo { SELECT \(Player.selectionSQL()), \(Team.selectionSQL()), - MAX(rounds.score) AS maxScore - FROM players - LEFT JOIN teams ON ... - LEFT JOIN rounds ON ... + MAX(round.score) AS maxScore + FROM player + LEFT JOIN team ON ... + LEFT JOIN round ON ... GROUP BY ... """ return SQLRequest(sql).adapted { db in @@ -5348,12 +5346,12 @@ You can consume complex joined queries with Codable records as well. As a demons ```swift struct Player: Decodable, FetchableRecord, TableRecord { - static let databaseTableName = "players" + static let databaseTableName = "player" var id: Int64 var name: String } struct Team: Decodable, FetchableRecord, TableRecord { - static let databaseTableName = "teams" + static let databaseTableName = "team" var id: Int64 var name: String var color: Color @@ -5371,10 +5369,10 @@ extension PlayerInfo { SELECT \(Player.selectionSQL()), \(Team.selectionSQL()), - MAX(rounds.score) AS maxScore - FROM players - LEFT JOIN teams ON ... - LEFT JOIN rounds ON ... + MAX(round.score) AS maxScore + FROM player + LEFT JOIN team ON ... + LEFT JOIN round ON ... GROUP BY ... """ return SQLRequest(sql).adapted { db in @@ -5619,18 +5617,18 @@ See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e63 **Transaction observers can avoid being notified of database changes they are not interested in.** -The filtering happens in the `observes(eventsOfKind:)` method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the "players" database table: +The filtering happens in the `observes(eventsOfKind:)` method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the "player" database table: ```swift class PlayerObserver: TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - // Only observe changes to the "players" table. - return eventKind.tableName == "players" + // Only observe changes to the "player" table. + return eventKind.tableName == "player" } func databaseDidChange(with event: DatabaseEvent) { // This method is only called for changes that happen to - // the "players" table. + // the "player" table. } } ``` @@ -5640,14 +5638,14 @@ Generally speaking, the `observes(eventsOfKind:)` method can distinguish inserti ```swift class PlayerScoreObserver: TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - // Only observe changes to the "score" column of the "players" table. + // Only observe changes to the "score" column of the "player" table. switch eventKind { case .insert(let tableName): - return tableName == "players" + return tableName == "player" case .delete(let tableName): - return tableName == "players" + return tableName == "player" case .update(let tableName, let columnNames): - return tableName == "players" && columnNames.contains("score") + return tableName == "player" && columnNames.contains("score") } } } @@ -5713,14 +5711,14 @@ Finally, an observer may ignore all database changes until the end of the curren ```swift class PlayerObserver: TransactionObserver { - var playersTableWasModified = false + var playerTableWasModified = false func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return eventKind.tableName == "players" + return eventKind.tableName == "player" } func databaseDidChange(with event: DatabaseEvent) { - playersTableWasModified = true + playerTableWasModified = true // It is pointless to keep on tracking further changes: stopObservingDatabaseChangesUntilNextTransaction() @@ -5794,21 +5792,21 @@ let controller = FetchedRecordsController( // Using SQL, and eventual arguments: let controller = FetchedRecordsController( dbQueue, - sql: "SELECT * FROM players ORDER BY name WHERE countryIsoCode = ?", + sql: "SELECT * FROM player ORDER BY name WHERE countryIsoCode = ?", arguments: ["FR"]) ``` The fetch request can involve several database tables. The fetched records controller will only track changes in the columns and tables used by the fetch request. ```swift -let controller = FetchedRecordsController( +let controller = FetchedRecordsController( dbQueue, sql: """ - SELECT players.name, COUNT(books.id) AS bookCount - FROM players - LEFT JOIN books ON books.authorId = players.id - GROUP BY players.id - ORDER BY players.name + SELECT author.name, COUNT(book.id) AS bookCount + FROM author + LEFT JOIN book ON book.authorId = author.id + GROUP BY author.id + ORDER BY author.name """) ``` @@ -6268,7 +6266,7 @@ Considering that a local database is not some JSON loaded from a remote server, ```swift do { try db.execute( - "INSERT INTO pets (masterId, name) VALUES (?, ?)", + "INSERT INTO pet (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"]) } catch let error as DatabaseError { // The SQLite error code: 19 (SQLITE_CONSTRAINT) @@ -6281,11 +6279,11 @@ do { error.message // The eventual erroneous SQL query - // "INSERT INTO pets (masterId, name) VALUES (?, ?)" + // "INSERT INTO pet (masterId, name) VALUES (?, ?)" error.sql // Full error description: - // "SQLite error 19 with statement `INSERT INTO pets (masterId, name) + // "SQLite error 19 with statement `INSERT INTO pet (masterId, name) // VALUES (?, ?)` arguments [1, "Bobby"]: FOREIGN KEY constraint failed"" error.description } @@ -6385,11 +6383,11 @@ They uncover programmer errors, false assumptions, and prevent misuses. Here are - **The database can't guarantee that the code does what it says:** ```swift - // fatal error: table players has no unique index on column email + // fatal error: table player has no unique index on column email try Player.deleteOne(db, key: ["email": "arthur@example.com"]) ``` - Solution: add a unique index to the players.email column, or use the `deleteAll` method to make it clear that you may delete more than one row: + Solution: add a unique index to the player.email column, or use the `deleteAll` method to make it clear that you may delete more than one row: ```swift try Player.filter(Column("email") == "arthur@example.com").deleteAll(db) @@ -6523,7 +6521,7 @@ GRDB comes with five extra collations that leverage unicode-aware comparisons ba A collation can be applied to a table column. All comparisons involving this column will then automatically trigger the comparison function: ```swift -try db.create(table: "players") { t in +try db.create(table: "player") { t in // Guarantees case-insensitive email unicity t.column("email", .text).unique().collate(.nocase) @@ -6542,7 +6540,7 @@ If you can't or don't want to define the comparison behavior of a column (see wa ```swift let collation = DatabaseCollation.localizedCaseInsensitiveCompare let players = try Player.fetchAll(db, - "SELECT * FROM players ORDER BY name COLLATE \(collation.name))") + "SELECT * FROM player ORDER BY name COLLATE \(collation.name))") let players = try Player.order(nameColumn.collating(collation)).fetchAll(db) ``` @@ -7080,10 +7078,10 @@ Obviously, no code is faster than any code. **Don't fetch columns you don't use** ```swift -// SELECT * FROM players +// SELECT * FROM player try Player.fetchAll(db) -// SELECT id, name FROM players +// SELECT id, name FROM player try Player.select(idColumn, nameColumn).fetchAll(db) ``` @@ -7143,10 +7141,10 @@ Consider a simple use case: your store application has to display a list of auth The following code is inefficient. It is an example of the [N+1 problem](http://stackoverflow.com/questions/97197/what-is-the-n1-selects-issue), because it performs one query to load the authors, and then N queries, as many as there are authors. This turns very inefficient as the number of authors grows: ```swift -// SELECT * FROM authors +// SELECT * FROM author let authors = try Author.fetchAll(db) for author in authors { - // SELECT COUNT(*) FROM books WHERE authorId = ... + // SELECT COUNT(*) FROM book WHERE authorId = ... author.bookCount = try Book.filter(authorIdColumn == author.id).fetchCount(db) } ``` @@ -7155,10 +7153,10 @@ Instead, perform *a single query*: ```swift let sql = """ - SELECT authors.*, COUNT(books.id) AS bookCount - FROM authors - LEFT JOIN books ON books.authorId = authors.id - GROUP BY authors.id + SELECT author.*, COUNT(book.id) AS bookCount + FROM author + LEFT JOIN book ON book.authorId = author.id + GROUP BY author.id """ let authors = try Author.fetchAll(db, sql) ``` @@ -7209,7 +7207,7 @@ For example, when fetching values, prefer loading columns by index: let players = try Player.fetchAll(db) // Column indexes -// SELECT id, name, email FROM players +// SELECT id, name, email FROM player let request = Player.select(idColumn, nameColumn, emailColumn) let rows = try Row.fetchCursor(db, request) while let row = try rows.next() { @@ -7230,7 +7228,7 @@ for player in players { } // Prepared statement -let insertStatement = db.prepareStatement("INSERT INTO players (name, email) VALUES (?, ?)") +let insertStatement = db.prepareStatement("INSERT INTO player (name, email) VALUES (?, ?)") for player in players { // Only use the unsafe arguments setter if you are sure that you provide // all statement arguments. A mistake can store unexpected values in @@ -7315,7 +7313,7 @@ try dbQueue.read { db in let sqlRequest = try SQLRequest(db, request: request) print(sqlRequest.sql) - // Prints SELECT * FROM wines WHERE origin = ? ORDER BY price + // Prints SELECT * FROM wine WHERE origin = ? ORDER BY price print(sqlRequest.arguments) // Prints ["Burgundy"] } @@ -7333,7 +7331,7 @@ try dbQueue.read { db in .filter(Column("origin") == "Burgundy") .order(Column("price") .fetchAll(db) - // Prints SELECT * FROM wines WHERE origin = 'Burgundy' ORDER BY price + // Prints SELECT * FROM wine WHERE origin = 'Burgundy' ORDER BY price } ``` diff --git a/TODO.md b/TODO.md index f5c6fbcd4..f44c41784 100644 --- a/TODO.md +++ b/TODO.md @@ -27,6 +27,9 @@ GRDB 3.0 - sync - ? - [ ] filter(rowid:), filter(rowids:) +- [ ] Fix matchingRowIds +- [ ] Simplify Range extensions for Swift 4.1 +- [ ] https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/6 - [ ] hide ScopeAdapter(base, scopes), because base.addingScopes has a better implementation Not sure diff --git a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift new file mode 100644 index 000000000..dc2815443 --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift @@ -0,0 +1,111 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct Team: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "teams" + var id: Int64 + var name: String +} + +private struct Player: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "players" + static let team = Player.belongsTo(Team.self) + var id: Int64 + var teamId: Int64? + var name: String +} + +private struct PlayerWithRequiredTeam: Decodable, FetchableRecord { + var player: Player + var team: Team + static let team = Player.team.forKey(CodingKeys.team) +} + +private struct PlayerWithOptionalTeam: Decodable, FetchableRecord { + var player: Player + var team: Team? + static let team = Player.team.forKey(CodingKeys.team) +} + +/// Test support for Decodable records +class AssociationBelongsToDecodableRecordTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "teams") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "players") { t in + t.column("id", .integer).primaryKey() + t.column("teamId", .integer).references("teams") + t.column("name", .text) + } + + try Team(id: 1, name: "Reds").insert(db) + try Player(id: 1, teamId: 1, name: "Arthur").insert(db) + try Player(id: 2, teamId: nil, name: "Barbara").insert(db) + } + } + + func testIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(required: PlayerWithRequiredTeam.team) + .asRequest(of: PlayerWithRequiredTeam.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].team.id, 1) + XCTAssertEqual(records[0].team.name, "Reds") + } + + func testIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(optional: PlayerWithOptionalTeam.team) + .asRequest(of: PlayerWithOptionalTeam.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].team!.id, 1) + XCTAssertEqual(records[0].team!.name, "Reds") + XCTAssertEqual(records[1].player.id, 2) + XCTAssertNil(records[1].player.teamId) + XCTAssertEqual(records[1].player.name, "Barbara") + XCTAssertNil(records[1].team) + } + + func testJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(required: Player.team) + let players = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(players.count, 1) + XCTAssertEqual(players[0].id, 1) + XCTAssertEqual(players[0].teamId, 1) + XCTAssertEqual(players[0].name, "Arthur") + } + + func testJoiningsOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(optional: Player.team) + let players = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(players.count, 2) + XCTAssertEqual(players[0].id, 1) + XCTAssertEqual(players[0].teamId, 1) + XCTAssertEqual(players[0].name, "Arthur") + XCTAssertEqual(players[1].id, 2) + XCTAssertNil(players[1].teamId) + XCTAssertEqual(players[1].name, "Barbara") + } +} diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift new file mode 100644 index 000000000..db5411021 --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -0,0 +1,120 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct Team: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "teams" + var id: Int64 + var name: String +} + +private struct Player: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "players" + static let teamScope = "team" + static let team = Player.belongsTo(Team.self, key: teamScope) + var id: Int64 + var teamId: Int64? + var name: String +} + +private struct PlayerWithRequiredTeam: FetchableRecord { + var player: Player + var team: Team + + init(row: Row) { + player = Player(row: row) + team = row[Player.teamScope] + } +} + +private struct PlayerWithOptionalTeam: FetchableRecord { + var player: Player + var team: Team? + + init(row: Row) { + player = Player(row: row) + team = row[Player.teamScope] + } +} + +/// Test support for FetchableRecord records +class AssociationBelongsToFetchableRecordTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "teams") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "players") { t in + t.column("id", .integer).primaryKey() + t.column("teamId", .integer).references("teams") + t.column("name", .text) + } + + try Team(id: 1, name: "Reds").insert(db) + try Player(id: 1, teamId: 1, name: "Arthur").insert(db) + try Player(id: 2, teamId: nil, name: "Barbara").insert(db) + } + } + + func testIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(required: Player.team) + .asRequest(of: PlayerWithRequiredTeam.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].team.id, 1) + XCTAssertEqual(records[0].team.name, "Reds") + } + + func testIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(optional: Player.team) + .asRequest(of: PlayerWithOptionalTeam.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].team!.id, 1) + XCTAssertEqual(records[0].team!.name, "Reds") + XCTAssertEqual(records[1].player.id, 2) + XCTAssertNil(records[1].player.teamId) + XCTAssertEqual(records[1].player.name, "Barbara") + XCTAssertNil(records[1].team) + } + + func testJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(required: Player.team) + let players = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(players.count, 1) + XCTAssertEqual(players[0].id, 1) + XCTAssertEqual(players[0].teamId, 1) + XCTAssertEqual(players[0].name, "Arthur") + } + + func testJoiningsOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(optional: Player.team) + let players = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(players.count, 2) + XCTAssertEqual(players[0].id, 1) + XCTAssertEqual(players[0].teamId, 1) + XCTAssertEqual(players[0].name, "Arthur") + XCTAssertEqual(players[1].id, 2) + XCTAssertNil(players[1].teamId) + XCTAssertEqual(players[1].name, "Barbara") + } +} diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift new file mode 100644 index 000000000..5f23e36a6 --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift @@ -0,0 +1,131 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct Team: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "teams" + var id: Int64 + var name: String +} + +private struct Player: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "players" + static let defaultTeam = belongsTo(Team.self) + static let customTeam = belongsTo(Team.self, key: "customTeam") + var id: Int64 + var teamId: Int64? + var name: String +} + +/// Test row scopes +class AssociationBelongsToRowScopeTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "teams") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "players") { t in + t.column("id", .integer).primaryKey() + t.column("teamId", .integer).references("teams") + t.column("name", .text) + } + + try Team(id: 1, name: "Reds").insert(db) + try Player(id: 1, teamId: 1, name: "Arthur").insert(db) + try Player(id: 2, teamId: nil, name: "Barbara").insert(db) + } + } + + func testDefaultScopeIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.including(required: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["teams"]) + XCTAssertEqual(rows[0].scopes["teams"]!, ["id":1, "name":"Reds"]) + } + + func testDefaultScopeIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.including(optional: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["teams"]) + XCTAssertEqual(rows[0].scopes["teams"]!, ["id":1, "name":"Reds"]) + XCTAssertEqual(rows[1].unscoped, ["id":2, "teamId":nil, "name":"Barbara"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["teams"]) + XCTAssertEqual(rows[1].scopes["teams"]!, ["id":nil, "name":nil]) + } + + func testDefaultScopeJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(required: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } + + func testDefaultScopeJoiningOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(optional: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + XCTAssertEqual(rows[1].unscoped, ["id":2, "teamId":nil, "name":"Barbara"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } + + func testCustomScopeIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.including(required: Player.customTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customTeam"]) + XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"]) + } + + func testCustomScopeIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.including(optional: Player.customTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customTeam"]) + XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"]) + XCTAssertEqual(rows[1].unscoped, ["id":2, "teamId":nil, "name":"Barbara"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customTeam"]) + XCTAssertEqual(rows[1].scopes["customTeam"]!, ["id":nil, "name":nil]) + } + + func testCustomScopeJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(required: Player.customTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } + + func testCustomScopeJoiningOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(optional: Player.customTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + XCTAssertEqual(rows[1].unscoped, ["id":2, "teamId":nil, "name":"Barbara"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } +} diff --git a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift new file mode 100644 index 000000000..4bf1c848f --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift @@ -0,0 +1,406 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B +private struct A : TableRecord { + static let databaseTableName = "a" + static let b = belongsTo(B.self) + static let restrictedB = belongsTo(RestrictedB.self) + static let extendedB = belongsTo(ExtendedB.self) +} + +private struct B : TableRecord { + static let a = hasOne(A.self) + static let databaseTableName = "b" +} + +private struct RestrictedB : TableRecord { + static let databaseTableName = "b" + static let databaseSelection: [SQLSelectable] = [Column("name")] +} + +private struct ExtendedB : TableRecord { + static let databaseTableName = "b" + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] +} + +/// Test SQL generation +class AssociationBelongsToSQLDerivationTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + } + } + } + + func testDefaultSelection() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + try assertEqualSQL(db, A.including(required: A.restrictedB), """ + SELECT "a".*, "b"."name" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + try assertEqualSQL(db, A.including(required: A.extendedB), """ + SELECT "a".*, "b".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + } + } + + func testCustomSelection() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let request = A.including(required: A.b + .select(Column("name"))) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + } + do { + let request = A.including(required: A.b + .select( + AllColumns(), + Column.rowID)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + } + do { + let aAlias = TableAlias() + let request = A + .aliased(aAlias) + .including(required: A.b + .select( + Column("name"), + (Column("id") + aAlias[Column("id")]).aliased("foo"))) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name", ("b"."id" + "a"."id") AS "foo" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + } + } + } + + func testFilteredAssociationImpactsJoinOnClause() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let request = A.including(required: A.b.filter(Column("name") != nil)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."name" IS NOT NULL)) + """) + } + do { + let request = A.including(required: A.b.filter(key: 1)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."id" = 1)) + """) + } + do { + let request = A.including(required: A.b.filter(keys: [1, 2, 3])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."id" IN (1, 2, 3))) + """) + } + do { + let request = A.including(required: A.b.filter(key: ["id": 1])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."id" = 1)) + """) + } + do { + let request = A.including(required: A.b.filter(keys: [["id": 1], ["id": 2]])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND (("b"."id" = 1) OR ("b"."id" = 2))) + """) + } + do { + let bAlias = TableAlias(name: "customB") + let request = A.including(required: A.b + .aliased(bAlias) + .filter(sql: "customB.name = ?", arguments: ["foo"])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "customB".* \ + FROM "a" \ + JOIN "b" "customB" ON (("customB"."id" = "a"."bid") AND (customB.name = 'foo')) + """) + } + } + } + + func testFilterAssociationInWhereClause() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let bAlias = TableAlias() + let request = A + .including(required: A.b.aliased(bAlias)) + .filter(bAlias[Column("name")] != nil) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + WHERE ("b"."name" IS NOT NULL) + """) + } + } + + func testAssociationOrderBubbleUp() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let aBase = A.all().aliased(TableAlias(name: "a")) + let abBase = A.b.aliased(TableAlias(name: "ab")) + let abaBase = B.a.aliased(TableAlias(name: "aba")) + + let aTransforms = [ + { (r: QueryInterfaceRequest) in return r }, + { (r: QueryInterfaceRequest) in return r.order(Column("id")) }, + { (r: QueryInterfaceRequest) in return r.order(Column("id")).reversed() }, + ] + let abTransforms = [ + { (r: BelongsToAssociation) in return r }, + { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) }, + { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) }, + { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() }, + { (r: BelongsToAssociation) in return r.reversed() }, + ] + let abaTransforms = [ + { (r: HasOneAssociation) in return r }, + { (r: HasOneAssociation) in return r.order(Column("id")) }, + { (r: HasOneAssociation) in return r.order(Column("id")).reversed() }, + ] + + var sqls: [String] = [] + for aTransform in aTransforms { + for abTransform in abTransforms { + for abaTransform in abaTransforms { + let request = aTransform(aBase) + .including(required: abTransform(abBase) + .including(required: abaTransform(abaBase))) + let sqlRequest = try SQLRequest(db, request: request) + sqls.append(sqlRequest.sql) + } + } + } + + let prefix = """ + SELECT "a".*, "ab".*, "aba".* \ + FROM "a" \ + JOIN "b" "ab" ON ("ab"."id" = "a"."bid") \ + JOIN "a" "aba" ON ("aba"."bid" = "ab"."id") + """ + let orderClauses = sqls.map { sql -> String in + let prefixEndIndex = sql.index(sql.startIndex, offsetBy: prefix.count) + return String(sql.suffix(from: prefixEndIndex)) + } + XCTAssertEqual(orderClauses, [ + // a: { (r: QueryInterfaceRequest) in return r }, + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + "", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"name\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + "", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"aba\".\"id\"", + + + // a: { (r: QueryInterfaceRequest) in return r.order(Column("id")) }, + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"aba\".\"id\"", + + + // a: { (r: QueryInterfaceRequest) in return r.order(Column("id")).reversed() } + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", + ]) + } + } + + // TODO: Test if and only if we really want to build an association from any request +// func testAssociationFromRequest() throws { +// let dbQueue = try makeDatabaseQueue() +// try dbQueue.inDatabase { db in +// do { +// let bRequest = B +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.belongsTo(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b".* \ +// FROM "a" \ +// JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// do { +// let bRequest = RestrictedB +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.belongsTo(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b"."name" \ +// FROM "a" \ +// JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// do { +// let bRequest = ExtendedB +// .select([Column("name")]) +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.belongsTo(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b"."name" \ +// FROM "a" \ +// JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// } +// } +} diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift new file mode 100644 index 000000000..3e781f56c --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -0,0 +1,771 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +/// Test SQL generation +class AssociationBelongsToSQLTests: GRDBTestCase { + + func testSingleColumnNoForeignKeyNoPrimaryKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentId"] = 1 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer) + } + try db.create(table: "children") { t in + t.column("parentId", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."rowid" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."rowid" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."rowid" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."rowid" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"rowid\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + } + } + + func testSingleColumnNoForeignKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentId"] = 1 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parentId", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + } + } + + func testSingleColumnSingleForeignKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentId"] = 1 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parentId", .integer).references("parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + } + } + + func testSingleColumnSeveralForeignKeys() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parent1Id"] = 1 + container["parent2Id"] = 2 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parent1Id", .integer).references("parents") + t.column("parent2Id", .integer).references("parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1Id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1Id")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2Id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 2)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2Id")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 2)") + } + } + } + + func testCompoundColumnNoForeignKeyNoPrimaryKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentA"] = 1 + container["parentB"] = 2 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + } + } + + func testCompoundColumnNoForeignKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentA"] = 1 + container["parentB"] = 2 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children\".\"parentB\")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children\".\"parentB\")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + } + } + + func testCompoundColumnSingleForeignKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentA"] = 1 + container["parentB"] = 2 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + t.foreignKey(["parentA", "parentB"], references: "parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + } + } + + func testCompoundColumnSeveralForeignKeys() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parent1A"] = 1 + container["parent1B"] = 2 + container["parent2A"] = 3 + container["parent2B"] = 4 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parent1A", .integer) + t.column("parent1B", .integer) + t.column("parent2A", .integer) + t.column("parent2B", .integer) + t.foreignKey(["parent1A", "parent1B"], references: "parents") + t.foreignKey(["parent2A", "parent2B"], references: "parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1A"), Column("parent1B")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2A"), Column("parent2B")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 3) AND (\"b\" = 4))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 3) AND (\"b\" = 4))") + } + } + } + + func testForeignKeyDefinitionFromColumn() { + // This test pass if code compiles + struct Parent : TableRecord { + static let databaseTableName = "parents" + enum Columns { + static let id = Column("id") + } + } + + struct Child : TableRecord { + static let databaseTableName = "children" + enum Columns { + static let parentId = Column("parentId") + } + enum ForeignKeys { + static let parent1 = ForeignKey([Columns.parentId]) + static let parent2 = ForeignKey([Columns.parentId], to: [Parent.Columns.id]) + } + static let parent1 = belongsTo(Parent.self, using: ForeignKeys.parent1) + static let parent2 = belongsTo(Parent.self, using: ForeignKeys.parent2) + } + } +} diff --git a/Tests/GRDBTests/AssociationChainRowScopesTests.swift b/Tests/GRDBTests/AssociationChainRowScopesTests.swift new file mode 100644 index 000000000..a05e58cdb --- /dev/null +++ b/Tests/GRDBTests/AssociationChainRowScopesTests.swift @@ -0,0 +1,694 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B <- C -> D +private struct A: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "a" + static let defaultB = belongsTo(B.self) + var id: Int64 + var bid: Int64? + var name: String +} + +private struct B: Codable, FetchableRecord, PersistableRecord { + static let defaultC = hasOne(C.self) + static let databaseTableName = "b" + var id: Int64 + var name: String +} + +private struct C: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "c" + static let defaultD = belongsTo(D.self) + var id: Int64 + var bid: Int64? + var did: Int64? + var name: String +} + +private struct D: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "d" + var id: Int64 + var name: String +} + +/// Test row scopes +class AssociationChainRowScopesTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("name", .text) + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + t.column("name", .text) + } + + try B(id: 1, name: "b1").insert(db) + try B(id: 2, name: "b2").insert(db) + try A(id: 1, bid: 1, name: "a1").insert(db) + try A(id: 2, bid: 2, name: "a2").insert(db) + try A(id: 3, bid: nil, name: "a3").insert(db) + try D(id: 1, name: "d1").insert(db) + try C(id: 1, bid: 1, did: 1, name: "c1").insert(db) + try C(id: 2, bid: 1, did: nil, name: "c2").insert(db) + } + } + + func testChainOfTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.defaultB.including(required: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + } + do { + let request = A.including(required: A.defaultB.including(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!.unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + do { + // TODO: chainOptionalRequired +// let request = A.including(optional: A.defaultB.including(required: B.defaultC)).order(sql: "a.id, b.id, c.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = A.including(optional: A.defaultB.including(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!.unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":3, "bid":nil, "name":"a3"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!.unscoped, ["id":nil, "name":nil]) + XCTAssertEqual(Set(rows[3].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[3].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + do { + let request = B.including(required: B.defaultC.including(required: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = B.including(required: B.defaultC.including(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!.unscoped, ["id":2, "bid":1, "did":nil, "name":"c2"]) + XCTAssertEqual(Set(rows[1].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + } + do { + // TODO: chainOptionalRequired +// let request = B.including(optional: B.defaultC.including(required: C.defaultD)).order(sql: "b.id, c.id, d.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = B.including(optional: B.defaultC.including(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!.unscoped, ["id":2, "bid":1, "did":nil, "name":"c2"]) + XCTAssertEqual(Set(rows[1].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!.unscoped, ["id":nil, "bid":nil, "did":nil, "name":nil]) + XCTAssertEqual(Set(rows[2].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + } + } + + func testChainOfTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.defaultB.joining(required: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes["b"]!.scopes.names.isEmpty) + } + do { + let request = A.including(required: A.defaultB.joining(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes["b"]!.scopes.names.isEmpty) + } + do { + // TODO: chainOptionalRequired +// let request = A.including(optional: A.defaultB.joining(required: B.defaultC)).order(sql: "a.id, b.id, c.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = A.including(optional: A.defaultB.joining(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":3, "bid":nil, "name":"a3"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":nil, "name":nil]) + XCTAssertTrue(rows[3].scopes["b"]!.scopes.names.isEmpty) + } + do { + let request = B.including(required: B.defaultC.joining(required: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["c"]!.scopes.names.isEmpty) + } + do { + let request = B.including(required: B.defaultC.joining(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["c"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + XCTAssertTrue(rows[1].scopes["c"]!.scopes.names.isEmpty) + } + do { + // TODO: chainOptionalRequired +// let request = B.including(optional: B.defaultC.joining(required: C.defaultD)).order(sql: "b.id, c.id, d.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = B.including(optional: B.defaultC.joining(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["c"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + XCTAssertTrue(rows[1].scopes["c"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + XCTAssertTrue(rows[2].scopes["c"]!.scopes.names.isEmpty) + } + } + + func testChainOfTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.defaultB.including(required: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + } + do { + let request = A.joining(required: A.defaultB.including(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[2].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + do { + // TODO: chainOptionalRequired +// let request = A.joining(optional: A.defaultB.including(required: B.defaultC)).order(sql: "a.id, b.id, c.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = A.joining(optional: A.defaultB.including(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[2].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":3, "bid":nil, "name":"a3"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[3].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[3].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + do { + let request = B.joining(required: B.defaultC.including(required: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = B.joining(required: B.defaultC.including(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + } + do { + // TODO: chainOptionalRequired +// let request = B.joining(optional: B.defaultC.including(required: C.defaultD)).order(sql: "b.id, c.id, d.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = B.joining(optional: B.defaultC.including(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[2].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + } + } + + func testChainOfTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.defaultB.joining(required: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = A.joining(required: A.defaultB.joining(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2], ["id":2, "bid":2, "name":"a2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + } + do { + // TODO: chainOptionalRequired +// let request = A.joining(optional: A.defaultB.joining(required: B.defaultC)).order(sql: "a.id, b.id, c.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = A.joining(optional: A.defaultB.joining(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2], ["id":2, "bid":2, "name":"a2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3], ["id":3, "bid":nil, "name":"a3"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.defaultC.joining(required: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.defaultC.joining(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + // TODO: chainOptionalRequired +// let request = B.joining(optional: B.defaultC.joining(required: C.defaultD)).order(sql: "b.id, c.id, d.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = B.joining(optional: B.defaultC.joining(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2], ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + } + } + + func testChainOfThreeIncludingIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.including(required: A.defaultB.including(required: B.defaultC.including(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + + func testChainOfThreeIncludingIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.including(required: A.defaultB.including(required: B.defaultC.joining(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"], ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes["c"]!.scopes.names.isEmpty) + } + + func testChainOfThreeIncludingJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.including(required: A.defaultB.joining(required: B.defaultC.including(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + + func testChainOfThreeIncludingJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.including(required: A.defaultB.joining(required: B.defaultC.joining(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes.names.isEmpty) + } + + func testChainOfThreeJoiningIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.joining(required: A.defaultB.including(required: B.defaultC.including(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + + func testChainOfThreeJoiningIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.joining(required: A.defaultB.including(required: B.defaultC.joining(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"], ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes["c"]!.scopes.names.isEmpty) + } + + func testChainOfThreeJoiningJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.joining(required: A.defaultB.joining(required: B.defaultC.including(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + + func testChainOfThreeJoiningJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.joining(required: A.defaultB.joining(required: B.defaultC.joining(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } +} diff --git a/Tests/GRDBTests/AssociationChainSQLTests.swift b/Tests/GRDBTests/AssociationChainSQLTests.swift new file mode 100644 index 000000000..f604ace52 --- /dev/null +++ b/Tests/GRDBTests/AssociationChainSQLTests.swift @@ -0,0 +1,557 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B <- C -> D +private struct A: TableRecord { + static let databaseTableName = "a" + static let b = belongsTo(B.self) +} + +private struct B: TableRecord { + static let c = hasOne(C.self) + static let databaseTableName = "b" +} + +private struct C: TableRecord { + static let databaseTableName = "c" + static let b = belongsTo(B.self) + static let d = belongsTo(D.self) +} + +private struct D: TableRecord { + static let databaseTableName = "d" +} + +/// Test SQL generation +class AssociationChainSQLTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + } + } + } + + func testChainOfTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c)), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c)), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c)), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c)), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(required: B.c.including(required: C.d)), """ + SELECT "b".*, "c".*, "d".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, B.including(required: B.c.including(optional: C.d)), """ + SELECT "b".*, "c".*, "d".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, B.including(optional: B.c.including(required: C.d)), "TODO") + try assertEqualSQL(db, B.including(optional: B.c.including(optional: C.d)), """ + SELECT "b".*, "c".*, "d".* \ + FROM "b" \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c)), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c)), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c)), "") + try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c)), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(required: B.c.joining(required: C.d)), """ + SELECT "b".*, "c".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, B.including(required: B.c.joining(optional: C.d)), """ + SELECT "b".*, "c".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, B.including(optional: B.c.joining(required: C.d)), "TODO") + try assertEqualSQL(db, B.including(optional: B.c.joining(optional: C.d)), """ + SELECT "b".*, "c".* \ + FROM "b" \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c)), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c)), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c)), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c)), """ + SELECT "a".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(required: B.c.including(required: C.d)), """ + SELECT "b".*, "d".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, B.joining(required: B.c.including(optional: C.d)), """ + SELECT "b".*, "d".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, B.joining(optional: B.c.including(required: C.d)), "TODO") + try assertEqualSQL(db, B.joining(optional: B.c.including(optional: C.d)), """ + SELECT "b".*, "d".* \ + FROM "b" \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c)), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c)), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c)), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c)), """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(required: B.c.joining(required: C.d)), """ + SELECT "b".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, B.joining(required: B.c.joining(optional: C.d)), """ + SELECT "b".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, B.joining(optional: B.c.joining(required: C.d)), "TODO") + try assertEqualSQL(db, B.joining(optional: B.c.joining(optional: C.d)), """ + SELECT "b".* \ + FROM "b" \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeIncludingIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c.including(required: C.d))), """ + SELECT "a".*, "b".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c.including(required: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c.including(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "c".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeIncludingIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c.joining(required: C.d))), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c.joining(required: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c.joining(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeIncludingJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c.including(required: C.d))), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c.including(required: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c.including(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeIncludingJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c.joining(required: C.d))), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c.joining(required: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c.joining(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeJoiningIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c.including(required: C.d))), """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c.including(optional: C.d))), """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c.including(required: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c.including(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeJoiningIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c.joining(required: C.d))), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c.joining(optional: C.d))), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c.joining(required: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c.joining(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeJoiningJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c.including(required: C.d))), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c.including(optional: C.d))), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c.including(required: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c.including(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeJoiningJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c.joining(required: C.d))), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c.joining(optional: C.d))), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c.joining(optional: C.d))), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c.joining(required: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c.joining(optional: C.d))), "TODO) +// try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c.joining(optional: C.d))), """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } +} diff --git a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift new file mode 100644 index 000000000..d15bbd908 --- /dev/null +++ b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift @@ -0,0 +1,406 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A <- B +private struct A : TableRecord { + static let databaseTableName = "a" + static let b = hasOne(B.self) + static let restrictedB = hasOne(RestrictedB.self) + static let extendedB = hasOne(ExtendedB.self) +} + +private struct B : TableRecord { + static let a = belongsTo(A.self) + static let databaseTableName = "b" +} + +private struct RestrictedB : TableRecord { + static let databaseTableName = "b" + static let databaseSelection: [SQLSelectable] = [Column("name")] +} + +private struct ExtendedB : TableRecord { + static let databaseTableName = "b" + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] +} + +/// Test SQL generation +class AssociationHasOneSQLDerivationTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("aid", .integer).references("a") + t.column("name", .text) + } + } + } + + func testDefaultSelection() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + try assertEqualSQL(db, A.including(required: A.restrictedB), """ + SELECT "a".*, "b"."name" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + try assertEqualSQL(db, A.including(required: A.extendedB), """ + SELECT "a".*, "b".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + } + } + + func testCustomSelection() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let request = A.including(required: A.b + .select(Column("name"))) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + } + do { + let request = A.including(required: A.b + .select( + AllColumns(), + Column.rowID)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + } + do { + let aAlias = TableAlias() + let request = A + .aliased(aAlias) + .including(required: A.b + .select( + Column("name"), + (Column("id") + aAlias[Column("id")]).aliased("foo"))) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name", ("b"."id" + "a"."id") AS "foo" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + } + } + } + + func testFilteredAssociationImpactsJoinOnClause() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let request = A.including(required: A.b.filter(Column("name") != nil)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL)) + """) + } + do { + let request = A.including(required: A.b.filter(key: 1)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."id" = 1)) + """) + } + do { + let request = A.including(required: A.b.filter(keys: [1, 2, 3])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."id" IN (1, 2, 3))) + """) + } + do { + let request = A.including(required: A.b.filter(key: ["id": 1])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."id" = 1)) + """) + } + do { + let request = A.including(required: A.b.filter(keys: [["id": 1], ["id": 2]])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND (("b"."id" = 1) OR ("b"."id" = 2))) + """) + } + do { + let bAlias = TableAlias(name: "customB") + let request = A.including(required: A.b + .aliased(bAlias) + .filter(sql: "customB.name = ?", arguments: ["foo"])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "customB".* \ + FROM "a" \ + JOIN "b" "customB" ON (("customB"."aid" = "a"."id") AND (customB.name = 'foo')) + """) + } + } + } + + func testFilterAssociationInWhereClause() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let bAlias = TableAlias() + let request = A + .including(required: A.b.aliased(bAlias)) + .filter(bAlias[Column("name")] != nil) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") \ + WHERE ("b"."name" IS NOT NULL) + """) + } + } + + func testAssociationOrderBubbleUp() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let aBase = A.all().aliased(TableAlias(name: "a")) + let abBase = A.b.aliased(TableAlias(name: "ab")) + let abaBase = B.a.aliased(TableAlias(name: "aba")) + + let aTransforms = [ + { (r: QueryInterfaceRequest) in return r }, + { (r: QueryInterfaceRequest) in return r.order(Column("id")) }, + { (r: QueryInterfaceRequest) in return r.order(Column("id")).reversed() }, + ] + let abTransforms = [ + { (r: HasOneAssociation) in return r }, + { (r: HasOneAssociation) in return r.order(Column("name"), Column("id").desc) }, + { (r: HasOneAssociation) in return r.order(Column("name")).order(Column("id").desc) }, + { (r: HasOneAssociation) in return r.order(Column("name")).reversed() }, + { (r: HasOneAssociation) in return r.reversed() }, + ] + let abaTransforms = [ + { (r: BelongsToAssociation) in return r }, + { (r: BelongsToAssociation) in return r.order(Column("id")) }, + { (r: BelongsToAssociation) in return r.order(Column("id")).reversed() }, + ] + + var sqls: [String] = [] + for aTransform in aTransforms { + for abTransform in abTransforms { + for abaTransform in abaTransforms { + let request = aTransform(aBase) + .including(required: abTransform(abBase) + .including(required: abaTransform(abaBase))) + let sqlRequest = try SQLRequest(db, request: request) + sqls.append(sqlRequest.sql) + } + } + } + + let prefix = """ + SELECT "a".*, "ab".*, "aba".* \ + FROM "a" \ + JOIN "b" "ab" ON ("ab"."aid" = "a"."id") \ + JOIN "a" "aba" ON ("aba"."id" = "ab"."aid") + """ + let orderClauses = sqls.map { sql -> String in + let prefixEndIndex = sql.index(sql.startIndex, offsetBy: prefix.count) + return String(sql.suffix(from: prefixEndIndex)) + } + XCTAssertEqual(orderClauses, [ + // a: { (r: QueryInterfaceRequest) in return r }, + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + "", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"name\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + "", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"aba\".\"id\"", + + + // a: { (r: QueryInterfaceRequest) in return r.order(Column("id")) }, + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"aba\".\"id\"", + + + // a: { (r: QueryInterfaceRequest) in return r.order(Column("id")).reversed() } + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", + ]) + } + } + + // TODO: Test if and only if we really want to build an association from any request +// func testAssociationFromRequest() throws { +// let dbQueue = try makeDatabaseQueue() +// try dbQueue.inDatabase { db in +// do { +// let bRequest = B +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.hasOne(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b".* \ +// FROM "a" \ +// JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// do { +// let bRequest = RestrictedB +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.hasOne(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b"."name" \ +// FROM "a" \ +// JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// do { +// let bRequest = ExtendedB +// .select([Column("name")]) +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.hasOne(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b"."name" \ +// FROM "a" \ +// JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// } +// } +} diff --git a/Tests/GRDBTests/AssociationHasOneSQLTests.swift b/Tests/GRDBTests/AssociationHasOneSQLTests.swift new file mode 100644 index 000000000..182502be4 --- /dev/null +++ b/Tests/GRDBTests/AssociationHasOneSQLTests.swift @@ -0,0 +1,769 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +/// Test SQL generation +class AssociationHasOneSQLTests: GRDBTestCase { + + func testSingleColumnNoForeignKeyNoPrimaryKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + container["rowid"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer) + } + try db.create(table: "children") { t in + t.column("parentId", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."rowid") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."rowid") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."rowid") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."rowid") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 2)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + } + } + + func testSingleColumnNoForeignKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parentId", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + } + } + + func testSingleColumnSingleForeignKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parentId", .integer).references("parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + } + } + + func testSingleColumnSeveralForeignKeys() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parent1Id", .integer).references("parents") + t.column("parent2Id", .integer).references("parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1Id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent1Id\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1Id")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent1Id\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2Id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent2Id\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2Id")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent2Id\" = 1)") + } + } + } + + func testCompoundColumnNoForeignKeyNoPrimaryKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["a"] = 1 + container["b"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + } + } + + func testCompoundColumnNoForeignKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["a"] = 1 + container["b"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + } + } + + func testCompoundColumnSingleForeignKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["a"] = 1 + container["b"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + t.foreignKey(["parentA", "parentB"], references: "parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + } + } + + func testCompoundColumnSeveralForeignKeys() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["a"] = 1 + container["b"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parent1A", .integer) + t.column("parent1B", .integer) + t.column("parent2A", .integer) + t.column("parent2B", .integer) + t.foreignKey(["parent1A", "parent1B"], references: "parents") + t.foreignKey(["parent2A", "parent2B"], references: "parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parent1A\" = 1) AND (\"parent1B\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parent1A\" = 1) AND (\"parent1B\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2A"), Column("parent2B")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parent2A\" = 1) AND (\"parent2B\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parent2A\" = 1) AND (\"parent2B\" = 2))") + } + } + } + + func testForeignKeyDefinitionFromColumn() { + // This test pass if code compiles + struct Parent : TableRecord { + static let databaseTableName = "parents" + enum Columns { + static let id = Column("id") + } + static let child1 = hasOne(Child.self, using: Child.ForeignKeys.parent1) + static let child2 = hasOne(Child.self, using: Child.ForeignKeys.parent2) + } + + struct Child : TableRecord { + static let databaseTableName = "children" + enum Columns { + static let parentId = Column("parentId") + } + enum ForeignKeys { + static let parent1 = ForeignKey([Columns.parentId]) + static let parent2 = ForeignKey([Columns.parentId], to: [Parent.Columns.id]) + } + } + } +} diff --git a/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift new file mode 100644 index 000000000..4795ac7e0 --- /dev/null +++ b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift @@ -0,0 +1,237 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B +// A -> D +private struct A: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "a" + static let b = belongsTo(B.self) + static let d = belongsTo(D.self) + var id: Int64 + var bid: Int64? + var did: Int64? + var name: String +} + +private struct B: Codable, FetchableRecord, PersistableRecord { + static let a = hasOne(A.self) + static let databaseTableName = "b" + var id: Int64 + var name: String +} + +private struct D: Codable, FetchableRecord, PersistableRecord { + static let a = hasOne(A.self) + static let databaseTableName = "d" + var id: Int64 + var name: String +} + +private struct AWithRequiredBD: Decodable, FetchableRecord { + var a: A + var b: B + var d: D + static let b = A.b.forKey(CodingKeys.b) + static let d = A.d.forKey(CodingKeys.d) +} + +private struct AWithOptionalBD: Decodable, FetchableRecord { + var a: A + var b: B? + var d: D? + static let b = A.b.forKey(CodingKeys.b) + static let d = A.d.forKey(CodingKeys.d) +} + +/// Test support for Decodable records +class AssociationParallelDecodableRecordTests: GRDBTestCase { + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + t.column("name", .text) + } + + try B(id: 1, name: "b1").insert(db) + try B(id: 2, name: "b2").insert(db) + try B(id: 3, name: "b3").insert(db) + try D(id: 1, name: "d1").insert(db) + try A(id: 1, bid: 1, did: 1, name: "a1").insert(db) + try A(id: 2, bid: 1, did: nil, name: "a2").insert(db) + try A(id: 3, bid: 2, did: 1, name: "a3").insert(db) + try A(id: 4, bid: 2, did: nil, name: "a4").insert(db) + try A(id: 5, bid: nil, did: 1, name: "a5").insert(db) + try A(id: 6, bid: nil, did: nil, name: "a6").insert(db) + } + } + + func testParallelTwoIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = A + .including(required: AWithRequiredBD.b) + .including(required: AWithRequiredBD.d) + .order(sql: "a.id, b.id, d.id") + .asRequest(of: AWithRequiredBD.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + + XCTAssertEqual(records.count, 2) + + XCTAssertEqual(records[0].a.id, 1) + XCTAssertEqual(records[0].a.bid, 1) + XCTAssertEqual(records[0].a.did, 1) + XCTAssertEqual(records[0].a.name, "a1") + XCTAssertEqual(records[0].b.id, 1) + XCTAssertEqual(records[0].b.name, "b1") + XCTAssertEqual(records[0].d.id, 1) + XCTAssertEqual(records[0].d.name, "d1") + + XCTAssertEqual(records[1].a.id, 3) + XCTAssertEqual(records[1].a.bid, 2) + XCTAssertEqual(records[1].a.did, 1) + XCTAssertEqual(records[1].a.name, "a3") + XCTAssertEqual(records[1].b.id, 2) + XCTAssertEqual(records[1].b.name, "b2") + XCTAssertEqual(records[1].d.id, 1) + XCTAssertEqual(records[1].d.name, "d1") + } + + func testParallelTwoIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = A + .including(optional: AWithOptionalBD.b) + .including(optional: AWithOptionalBD.d) + .order(sql: "a.id, b.id, d.id") + .asRequest(of: AWithOptionalBD.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + + XCTAssertEqual(records.count, 6) + + XCTAssertEqual(records[0].a.id, 1) + XCTAssertEqual(records[0].a.bid, 1) + XCTAssertEqual(records[0].a.did, 1) + XCTAssertEqual(records[0].a.name, "a1") + XCTAssertEqual(records[0].b!.id, 1) + XCTAssertEqual(records[0].b!.name, "b1") + XCTAssertEqual(records[0].d!.id, 1) + XCTAssertEqual(records[0].d!.name, "d1") + + XCTAssertEqual(records[1].a.id, 2) + XCTAssertEqual(records[1].a.bid, 1) + XCTAssertEqual(records[1].a.did, nil) + XCTAssertEqual(records[1].a.name, "a2") + XCTAssertEqual(records[1].b!.id, 1) + XCTAssertEqual(records[1].b!.name, "b1") + XCTAssertNil(records[1].d) + + XCTAssertEqual(records[2].a.id, 3) + XCTAssertEqual(records[2].a.bid, 2) + XCTAssertEqual(records[2].a.did, 1) + XCTAssertEqual(records[2].a.name, "a3") + XCTAssertEqual(records[2].b!.id, 2) + XCTAssertEqual(records[2].b!.name, "b2") + XCTAssertEqual(records[2].d!.id, 1) + XCTAssertEqual(records[2].d!.name, "d1") + + XCTAssertEqual(records[3].a.id, 4) + XCTAssertEqual(records[3].a.bid, 2) + XCTAssertEqual(records[3].a.did, nil) + XCTAssertEqual(records[3].a.name, "a4") + XCTAssertEqual(records[3].b!.id, 2) + XCTAssertEqual(records[3].b!.name, "b2") + XCTAssertNil(records[3].d) + + XCTAssertEqual(records[4].a.id, 5) + XCTAssertEqual(records[4].a.bid, nil) + XCTAssertEqual(records[4].a.did, 1) + XCTAssertEqual(records[4].a.name, "a5") + XCTAssertNil(records[4].b) + XCTAssertEqual(records[4].d!.id, 1) + XCTAssertEqual(records[4].d!.name, "d1") + + XCTAssertEqual(records[5].a.id, 6) + XCTAssertEqual(records[5].a.bid, nil) + XCTAssertEqual(records[5].a.did, nil) + XCTAssertEqual(records[5].a.name, "a6") + XCTAssertNil(records[5].b) + XCTAssertNil(records[5].d) + } + + func testParallelTwoJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = A + .joining(required: A.b) + .joining(required: A.d) + .order(sql: "a.id, b.id, d.id") + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + + XCTAssertEqual(records.count, 2) + + XCTAssertEqual(records[0].id, 1) + XCTAssertEqual(records[0].bid, 1) + XCTAssertEqual(records[0].did, 1) + XCTAssertEqual(records[0].name, "a1") + + XCTAssertEqual(records[1].id, 3) + XCTAssertEqual(records[1].bid, 2) + XCTAssertEqual(records[1].did, 1) + XCTAssertEqual(records[1].name, "a3") + } + + func testParallelTwoJoiningOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = A + .joining(optional: A.b) + .joining(optional: A.d) + .order(sql: "a.id, b.id, d.id") + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + + XCTAssertEqual(records.count, 6) + + XCTAssertEqual(records[0].id, 1) + XCTAssertEqual(records[0].bid, 1) + XCTAssertEqual(records[0].did, 1) + XCTAssertEqual(records[0].name, "a1") + + XCTAssertEqual(records[1].id, 2) + XCTAssertEqual(records[1].bid, 1) + XCTAssertEqual(records[1].did, nil) + XCTAssertEqual(records[1].name, "a2") + + XCTAssertEqual(records[2].id, 3) + XCTAssertEqual(records[2].bid, 2) + XCTAssertEqual(records[2].did, 1) + XCTAssertEqual(records[2].name, "a3") + + XCTAssertEqual(records[3].id, 4) + XCTAssertEqual(records[3].bid, 2) + XCTAssertEqual(records[3].did, nil) + XCTAssertEqual(records[3].name, "a4") + + XCTAssertEqual(records[4].id, 5) + XCTAssertEqual(records[4].bid, nil) + XCTAssertEqual(records[4].did, 1) + XCTAssertEqual(records[4].name, "a5") + + XCTAssertEqual(records[5].id, 6) + XCTAssertEqual(records[5].bid, nil) + XCTAssertEqual(records[5].did, nil) + XCTAssertEqual(records[5].name, "a6") + } +} + diff --git a/Tests/GRDBTests/AssociationParallelRowScopesTests.swift b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift new file mode 100644 index 000000000..f833518a5 --- /dev/null +++ b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift @@ -0,0 +1,1400 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B <- C +// A -> D +private struct A: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "a" + static let defaultB = belongsTo(B.self) + static let defaultD = belongsTo(D.self) + static let customB = belongsTo(B.self, key: "customB") + static let customD = belongsTo(D.self, key: "customD") + var id: Int64 + var bid: Int64? + var did: Int64? + var name: String +} + +private struct B: Codable, FetchableRecord, PersistableRecord { + static let defaultA = hasOne(A.self) + static let defaultC = hasOne(C.self) + static let customA = hasOne(A.self, key: "customA") + static let customC = hasOne(C.self, key: "customC") + static let databaseTableName = "b" + var id: Int64 + var name: String +} + +private struct C: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "c" + var id: Int64 + var bid: Int64? + var name: String +} + +private struct D: Codable, FetchableRecord, PersistableRecord { + static let defaultA = hasOne(A.self) + static let customA = hasOne(A.self, key: "customA") + static let databaseTableName = "d" + var id: Int64 + var name: String +} + +/// Test row scopes +class AssociationParallelRowScopesTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + t.column("name", .text) + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("name", .text) + } + + try B(id: 1, name: "b1").insert(db) + try B(id: 2, name: "b2").insert(db) + try B(id: 3, name: "b3").insert(db) + try D(id: 1, name: "d1").insert(db) + try A(id: 1, bid: 1, did: 1, name: "a1").insert(db) + try A(id: 2, bid: 1, did: nil, name: "a2").insert(db) + try A(id: 3, bid: 2, did: 1, name: "a3").insert(db) + try A(id: 4, bid: 2, did: nil, name: "a4").insert(db) + try A(id: 5, bid: nil, did: 1, name: "a5").insert(db) + try A(id: 6, bid: nil, did: nil, name: "a6").insert(db) + try C(id: 1, bid: 1, name: "c1").insert(db) + } + } + + func testDefaultScopeParallelTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.including(required: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) + } + do { + let request = A.including(optional: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.including(optional: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[4].scopes["b"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[4].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[5].scopes["b"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[5].scopes["d"]!, ["id":nil, "name":nil]) + } + do { + let request = B.including(required: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.including(required: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + } + do { + let request = B.including(optional: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.including(optional: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[4].scopes["a"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + XCTAssertEqual(rows[4].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + } + } + + func testDefaultScopeParallelTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) + } + do { + let request = A.including(required: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) + } + do { + let request = A.including(optional: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":nil, "name":nil]) + } + do { + let request = A.including(optional: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["b"]) + XCTAssertEqual(rows[4].scopes["b"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["b"]) + XCTAssertEqual(rows[5].scopes["b"]!, ["id":nil, "name":nil]) + } + do { + let request = B.including(required: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + } + do { + let request = B.including(required: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) + XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) + XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + } + do { + let request = B.including(optional: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + } + do { + let request = B.including(optional: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) + XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) + XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["a"]) + XCTAssertEqual(rows[4].scopes["a"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + } + + func testDefaultScopeParallelTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.joining(required: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["d"]) + XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) + } + do { + let request = A.joining(optional: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.joining(optional: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["d"]) + XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["d"]) + XCTAssertEqual(rows[4].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["d"]) + XCTAssertEqual(rows[5].scopes["d"]!, ["id":nil, "name":nil]) + } + do { + let request = B.joining(required: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.joining(required: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["c"]) + XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + } + do { + let request = B.joining(optional: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.joining(optional: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["c"]) + XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["c"]) + XCTAssertEqual(rows[4].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + } + } + + func testDefaultScopeParallelTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = A.joining(required: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = A.joining(optional: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + } + do { + let request = A.joining(optional: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertTrue(rows[4].scopes.names.isEmpty) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertTrue(rows[5].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = B.joining(optional: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = B.joining(optional: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertTrue(rows[4].scopes.names.isEmpty) + } + } + + func testCustomScopeParallelTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.including(required: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) + } + do { + let request = A.including(optional: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.including(optional: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[4].scopes["customB"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[4].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[5].scopes["customB"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[5].scopes["customD"]!, ["id":nil, "name":nil]) + } + do { + let request = B.including(required: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.including(required: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + } + do { + let request = B.including(optional: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.including(optional: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[4].scopes["customA"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + XCTAssertEqual(rows[4].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + } + } + + func testCustomScopeParallelTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) + } + do { + let request = A.including(required: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) + XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) + } + do { + let request = A.including(optional: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":nil, "name":nil]) + } + do { + let request = A.including(optional: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) + XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customB"]) + XCTAssertEqual(rows[4].scopes["customB"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["customB"]) + XCTAssertEqual(rows[5].scopes["customB"]!, ["id":nil, "name":nil]) + } + do { + let request = B.including(required: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + } + do { + let request = B.including(required: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) + XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) + XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + } + do { + let request = B.including(optional: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + } + do { + let request = B.including(optional: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) + XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) + XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customA"]) + XCTAssertEqual(rows[4].scopes["customA"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + } + + func testCustomScopeParallelTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.joining(required: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customD"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customD"]) + XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) + } + do { + let request = A.joining(optional: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customD"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.joining(optional: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customD"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customD"]) + XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customD"]) + XCTAssertEqual(rows[4].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["customD"]) + XCTAssertEqual(rows[5].scopes["customD"]!, ["id":nil, "name":nil]) + } + do { + let request = B.joining(required: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.joining(required: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customC"]) + XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customC"]) + XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + } + do { + let request = B.joining(optional: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.joining(optional: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customC"]) + XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customC"]) + XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customC"]) + XCTAssertEqual(rows[4].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + } + } + + func testCustomScopeParallelTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = A.joining(required: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = A.joining(optional: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + } + do { + let request = A.joining(optional: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertTrue(rows[4].scopes.names.isEmpty) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertTrue(rows[5].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = B.joining(optional: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = B.joining(optional: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertTrue(rows[4].scopes.names.isEmpty) + } + } +} + diff --git a/Tests/GRDBTests/AssociationParallelSQLTests.swift b/Tests/GRDBTests/AssociationParallelSQLTests.swift new file mode 100644 index 000000000..db57c3f06 --- /dev/null +++ b/Tests/GRDBTests/AssociationParallelSQLTests.swift @@ -0,0 +1,272 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B <- C +// A -> D +private struct A: TableRecord { + static let databaseTableName = "a" + static let b = belongsTo(B.self) + static let d = belongsTo(D.self) +} + +private struct B: TableRecord { + static let a = hasOne(A.self) + static let c = hasOne(C.self) + static let databaseTableName = "b" +} + +private struct C: TableRecord { + static let databaseTableName = "c" + static let b = belongsTo(B.self) +} + +private struct D: TableRecord { + static let a = hasOne(A.self) + static let databaseTableName = "d" +} + +/// Test SQL generation +class AssociationParallelSQLTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + } + } + } + + func testParallelTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b).including(required: A.d), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(required: A.b).including(optional: A.d), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(optional: A.b).including(required: A.d), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(optional: A.b).including(optional: A.d), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, B.including(required: B.a).including(required: B.c), """ + SELECT "b".*, "a".*, "c".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(required: B.a).including(optional: B.c), """ + SELECT "b".*, "a".*, "c".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).including(required: B.c), """ + SELECT "b".*, "a".*, "c".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).including(optional: B.c), """ + SELECT "b".*, "a".*, "c".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + } + } + + func testParallelTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b).joining(required: A.d), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(required: A.b).joining(optional: A.d), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(optional: A.b).joining(required: A.d), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(optional: A.b).joining(optional: A.d), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, B.including(required: B.a).joining(required: B.c), """ + SELECT "b".*, "a".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(required: B.a).joining(optional: B.c), """ + SELECT "b".*, "a".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).joining(required: B.c), """ + SELECT "b".*, "a".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).joining(optional: B.c), """ + SELECT "b".*, "a".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + } + } + + func testParallelTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b).including(required: A.d), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b).including(optional: A.d), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(optional: A.b).including(required: A.d), """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(optional: A.b).including(optional: A.d), """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, B.joining(required: B.a).including(required: B.c), """ + SELECT "b".*, "c".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(required: B.a).including(optional: B.c), """ + SELECT "b".*, "c".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(optional: B.a).including(required: B.c), """ + SELECT "b".*, "c".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(optional: B.a).including(optional: B.c), """ + SELECT "b".*, "c".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + } + } + + func testParallelTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b).joining(required: A.d), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b).joining(optional: A.d), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(optional: A.b).joining(required: A.d), """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(optional: A.b).joining(optional: A.d), """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, B.joining(required: B.a).joining(required: B.c), """ + SELECT "b".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(required: B.a).joining(optional: B.c), """ + SELECT "b".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(optional: B.a).joining(required: B.c), """ + SELECT "b".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(optional: B.a).joining(optional: B.c), """ + SELECT "b".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + } + } +} diff --git a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift new file mode 100644 index 000000000..6e1f1f8b9 --- /dev/null +++ b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift @@ -0,0 +1,244 @@ +import XCTest +#if GRDBCIPHER + @testable import GRDBCipher +#elseif GRDBCUSTOMSQLITE + @testable import GRDBCustomSQLite +#else + @testable import GRDB +#endif + +// a -> b* -> c +// -> d* +// -> c* +private struct A: TableRecord, FetchableRecord, Decodable { + static let databaseTableName = "a" + static let b = hasOne(B.self) + static let c = hasOne(C.self) + var id: Int64 +} +private struct B: TableRecord, FetchableRecord, Decodable { + static let databaseTableName = "b" + static let c = hasOne(C.self) + static let d = hasOne(D.self) + var id: Int64 + var aid: Int64 +} +private struct C: TableRecord, FetchableRecord, Decodable { + static let databaseTableName = "c" + var id: Int64 + var aid: Int64? + var bid: Int64? +} +private struct D: TableRecord, FetchableRecord, Decodable { + static let databaseTableName = "d" + var id: Int64 + var bid: Int64 +} + +class AssociationRowScopeSearchTests: GRDBTestCase { + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + // 1. Prepare data + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("aid", .integer).references("a") + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("aid", .integer).references("a") + t.column("bid", .integer).references("b") + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + } + try db.execute("INSERT INTO a (id) VALUES (1)") + try db.execute("INSERT INTO b (id, aid) VALUES (2, 1)") + try db.execute("INSERT INTO c (id, aid, bid) VALUES (3, NULL, 2)") + try db.execute("INSERT INTO c (id, aid, bid) VALUES (4, 1, NULL)") + try db.execute("INSERT INTO d (id, bid) VALUES (5, 2)") + } + } + + private let testedRequest = A + .including(required: A.b + .including(required: B.c) + .including(required: B.d) + ) + .including(required: A.c) + + func testTestedRequest() throws { + // Assert that we fetch the expected nested scopes before we start testing breadth-first lookup + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let rows = try testedRequest.asRequest(of: Row.self).fetchAll(db) + + XCTAssertEqual(rows.count, 1) + let row = rows[0] + + XCTAssertEqual(row.unscoped, ["id": 1]) + XCTAssertEqual(row.scopes["b"]!.unscoped, ["id": 2, "aid": 1]) + XCTAssertEqual(row.scopes["b"]!.scopes["c"]!, ["id": 3, "aid": nil, "bid": 2]) + XCTAssertEqual(row.scopes["b"]!.scopes["d"]!, ["id": 5, "bid": 2]) + XCTAssertEqual(row.scopes["c"]!, ["id": 4, "aid": 1, "bid": nil]) + } + } + + func testBreadthFirstScopeLookup() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let row = try testedRequest.asRequest(of: Row.self).fetchOne(db)! + XCTAssertEqual(row.scopesTree["b"]!.unscoped, ["id": 2, "aid": 1]) + XCTAssertEqual(row.scopesTree["c"]!, ["id": 4, "aid": 1, "bid": nil]) + XCTAssertEqual(row.scopesTree["d"]!, ["id": 5, "bid": 2]) + } + } + + func testFetchableRecordDecoding() throws { + struct Record: FetchableRecord { + var a: A + var b: B + var c: C + var d: D + init(row: Row) { + a = A(row: row) + b = row["b"] + c = row["c"] + d = row["d"] + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = try testedRequest.asRequest(of: Record.self).fetchOne(db)! + XCTAssertEqual(record.a.id, 1) + XCTAssertEqual(record.b.id, 2) + XCTAssertEqual(record.b.aid, 1) + XCTAssertEqual(record.c.id, 4) + XCTAssertEqual(record.c.aid, 1) + XCTAssertNil(record.c.bid) + XCTAssertEqual(record.d.id, 5) + XCTAssertEqual(record.d.bid, 2) + } + } + + func testFlatDecodableRecordDecoding() throws { + struct Record: FetchableRecord, Decodable { + var a: A + var b: B + var c: C + var d: D + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = try testedRequest.asRequest(of: Record.self).fetchOne(db)! + XCTAssertEqual(record.a.id, 1) + XCTAssertEqual(record.b.id, 2) + XCTAssertEqual(record.b.aid, 1) + XCTAssertEqual(record.c.id, 4) + XCTAssertEqual(record.c.aid, 1) + XCTAssertNil(record.c.bid) + XCTAssertEqual(record.d.id, 5) + XCTAssertEqual(record.d.bid, 2) + } + } + + func testNestedDecodableRecordDecoding() throws { + struct NestedB: Decodable { + var b: B + var c: C + var d: D + } + struct Record: FetchableRecord, Decodable { + var a: A + var b: NestedB + var c: C + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = try testedRequest.asRequest(of: Record.self).fetchOne(db)! + XCTAssertEqual(record.a.id, 1) + XCTAssertEqual(record.b.b.id, 2) + XCTAssertEqual(record.b.b.aid, 1) + XCTAssertEqual(record.b.c.id, 3) + XCTAssertNil(record.b.c.aid) + XCTAssertEqual(record.b.c.bid, 2) + XCTAssertEqual(record.b.d.id, 5) + XCTAssertEqual(record.b.d.bid, 2) + XCTAssertEqual(record.c.id, 4) + XCTAssertEqual(record.c.aid, 1) + XCTAssertNil(record.c.bid) + } + } + + func testDecodableWithCustomRowDecoding() throws { + struct CustomA: FetchableRecord, Decodable { + var id: Int64 + var custom: Bool? + init(row: Row) { + id = row["id"] + custom = true + } + } + struct CustomB: FetchableRecord, Decodable { + var id: Int64 + var aid: Int64 + var custom: Bool? + init(row: Row) { + id = row["id"] + aid = row["aid"] + custom = true + } + } + struct CustomC: FetchableRecord, Decodable { + var id: Int64 + var aid: Int64? + var bid: Int64? + var custom: Bool? + init(row: Row) { + id = row["id"] + aid = row["aid"] + bid = row["bid"] + custom = true + } + } + struct CustomD: FetchableRecord, Decodable { + var id: Int64 + var bid: Int64 + var custom: Bool? + init(row: Row) { + id = row["id"] + bid = row["bid"] + custom = true + } + } + struct Record: FetchableRecord, Decodable { + var a: CustomA + var b: CustomB + var c: CustomC + var d: CustomD + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = try testedRequest.asRequest(of: Record.self).fetchOne(db)! + XCTAssertEqual(record.a.id, 1) + XCTAssertEqual(record.a.custom, true) + XCTAssertEqual(record.b.id, 2) + XCTAssertEqual(record.b.aid, 1) + XCTAssertEqual(record.b.custom, true) + XCTAssertEqual(record.c.id, 4) + XCTAssertEqual(record.c.aid, 1) + XCTAssertNil(record.c.bid) + XCTAssertEqual(record.c.custom, true) + XCTAssertEqual(record.d.id, 5) + XCTAssertEqual(record.d.bid, 2) + XCTAssertEqual(record.d.custom, true) + } + } +} diff --git a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift new file mode 100644 index 000000000..c3d3041bf --- /dev/null +++ b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift @@ -0,0 +1,340 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> A +// A -> B1 +// A -> B2 +private struct A : TableRecord { + static let databaseTableName = "a" + static let parent = belongsTo(A.self) + static let child = hasOne(A.self) + static let b1 = belongsTo(B.self, key: "b1", using: ForeignKey(["bid1"])) + static let b2 = belongsTo(B.self, key: "b2", using: ForeignKey(["bid2"])) +} +private struct B : TableRecord { + static let databaseTableName = "b" + static let a1 = hasOne(A.self, key: "a1", using: ForeignKey(["bid1"])) + static let a2 = hasOne(A.self, key: "a1", using: ForeignKey(["bid2"])) +} + +/// Tests for table name conflicts, recursive associations, +/// user-defined table aliases, and expressions that involve several tables. +class AssociationTableAliasTestsSQLTests : GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid1", .integer).references("b") + t.column("bid2", .integer).references("b") + t.column("parentId", .integer).references("a") + t.column("name", .text) + } + } + } + + func testTableAliasBasics() throws { + // A table reference qualifies all unqualified selectables, expressions, and orderings + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let alias = TableAlias() + let name = Column("name") + let condition = name != nil && alias[name] == "foo" + + let expectedSQL = """ + SELECT "name" \ + FROM "a" \ + WHERE (("id" = 1) AND (("name" IS NOT NULL) AND ("name" = 'foo'))) \ + GROUP BY "name" \ + HAVING "name" \ + ORDER BY "name" + """ + + do { + let request = A + .aliased(alias) + .select(name) + .filter(key: 1) + .filter(condition) + .group(name) + .having(name) + .order(name) + try assertEqualSQL(db, request, expectedSQL) + } + do { + let request = A + .select(name) + .filter(key: 1) + .filter(condition) + .group(name) + .having(name) + .order(name) + .aliased(alias) + try assertEqualSQL(db, request, expectedSQL) + } + } + do { + let alias = TableAlias(name: "customA") + let name = Column("name") + let condition = name != nil && alias[name] == "foo" + + let expectedSQL = """ + SELECT "customA"."name" \ + FROM "a" "customA" \ + WHERE (("customA"."id" = 1) AND (("customA"."name" IS NOT NULL) AND ("customA"."name" = 'foo'))) \ + GROUP BY "customA"."name" \ + HAVING "customA"."name" \ + ORDER BY "customA"."name" + """ + + do { + let request = A + .aliased(alias) + .select(name) + .filter(key: 1) + .filter(condition) + .group(name) + .having(name) + .order(name) + try assertEqualSQL(db, request, expectedSQL) + } + do { + let request = A + .select(name) + .filter(key: 1) + .filter(condition) + .group(name) + .having(name) + .order(name) + .aliased(alias) + try assertEqualSQL(db, request, expectedSQL) + } + } + } + } + + func testRecursiveRelationDepth1() throws { + // A.include(A.parent) + // A.include(A.child) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.parent), """ + SELECT "a1".*, "a2".* \ + FROM "a" "a1" \ + JOIN "a" "a2" ON ("a2"."id" = "a1"."parentId") + """) + try assertEqualSQL(db, A.including(required: A.child), """ + SELECT "a1".*, "a2".* \ + FROM "a" "a1" \ + JOIN "a" "a2" ON ("a2"."parentId" = "a1"."id") + """) + } + } + + func testRecursiveRelationDepth2() throws { + // A.include(B1).include(A) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = A + .including(required: A.b1 + .including(required: B.a2)) + try assertEqualSQL(db, request, """ + SELECT "a1".*, "b".*, "a2".* \ + FROM "a" "a1" \ + JOIN "b" ON ("b"."id" = "a1"."bid1") \ + JOIN "a" "a2" ON ("a2"."bid2" = "b"."id") + """) + } + } + + func testMultipleForeignKeys() throws { + // A + // .include(B1) + // .include(B2) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = A + .including(required: A.b1) + .including(required: A.b2) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b1".*, "b2".* \ + FROM "a" \ + JOIN "b" "b1" ON ("b1"."id" = "a"."bid1") \ + JOIN "b" "b2" ON ("b2"."id" = "a"."bid2") + """) + } + } + + func testRecursiveThroughMultipleForeignKeys() throws { + // A + // .include(B1.include(A)) + // .include(B2.include(A)) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = A + .including(required: A.b1 + .including(required: B.a2)) + .including(required: A.b2 + .including(required: B.a1)) + try assertEqualSQL(db, request, """ + SELECT "a1".*, "b1".*, "a2".*, "b2".*, "a3".* \ + FROM "a" "a1" \ + JOIN "b" "b1" ON ("b1"."id" = "a1"."bid1") \ + JOIN "a" "a2" ON ("a2"."bid2" = "b1"."id") \ + JOIN "b" "b2" ON ("b2"."id" = "a1"."bid2") \ + JOIN "a" "a3" ON ("a3"."bid1" = "b2"."id") + """) + } + } + + func testUserDefinedAlias() throws { + // A + // .aliased("customA") + // .include(B1.aliased("customB")) + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let aAlias1 = TableAlias(name: "customA1") // On TableMapping and QueryInterfaceRequest + let bAlias = TableAlias(name: "customB") // On BelongsToAssociation + let aAlias2 = TableAlias(name: "customA2") // On HasOneAssociation + + let expectedSQL = """ + SELECT "customA1".*, "customB".*, "customA2".* \ + FROM "a" "customA1" \ + JOIN "b" "customB" ON ("customB"."id" = "customA1"."bid1") \ + JOIN "a" "customA2" ON ("customA2"."bid2" = "customB"."id") + """ + + do { + // Alias first + let request = A + .aliased(aAlias1) + .including(required: A.b1 + .aliased(bAlias) + .including(required: B.a2 + .aliased(aAlias2))) + try assertEqualSQL(db, request, expectedSQL) + } + + do { + // Alias last + let request = A + .including(required: A.b1 + .including(required: B.a2 + .aliased(aAlias2)) + .aliased(bAlias)) + .aliased(aAlias1) + try assertEqualSQL(db, request, expectedSQL) + } + } + } + + func testUserInducedNameConflict() throws { + // A.include(B1.aliased("a")) + // A.aliased("b").include(B1) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let bAlias = TableAlias(name: A.databaseTableName.lowercased()) + let request = A.including(required: A.b1.aliased(bAlias)) + try assertEqualSQL(db, request, """ + SELECT "a1".*, "a".* \ + FROM "a" "a1" \ + JOIN "b" "a" ON ("a"."id" = "a1"."bid1") + """) + } + do { + let bAlias = TableAlias(name: A.databaseTableName.uppercased()) + let request = A.including(required: A.b1.aliased(bAlias)) + try assertEqualSQL(db, request, """ + SELECT "a1".*, "A".* \ + FROM "a" "a1" \ + JOIN "b" "A" ON ("A"."id" = "a1"."bid1") + """) + } + do { + let aAlias = TableAlias(name: B.databaseTableName.lowercased()) + let request = A.aliased(aAlias).including(required: A.b1) + try assertEqualSQL(db, request, """ + SELECT "b".*, "b1".* \ + FROM "a" "b" \ + JOIN "b" "b1" ON ("b1"."id" = "b"."bid1") + """) + } + do { + let aAlias = TableAlias(name: B.databaseTableName.uppercased()) + let request = A.aliased(aAlias).including(required: A.b1) + try assertEqualSQL(db, request, """ + SELECT "B".*, "b1".* \ + FROM "a" "B" \ + JOIN "b" "b1" ON ("b1"."id" = "B"."bid1") + """) + } + } + } + + func testCrossTableExpressions() throws { + // A + // .include(B1.include(A)) + // .include(B2.include(A)) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let rootA = TableAlias() + let A1 = TableAlias() + let A2 = TableAlias() + let name = Column("name") + + let condition = name != nil && rootA[name] > A1[name] && A2[name] == "foo" + + let expectedSQL = """ + SELECT "a1".*, "b1".*, "a2".*, "b2".*, "a3".* \ + FROM "a" "a1" \ + JOIN "b" "b1" ON ("b1"."id" = "a1"."bid1") \ + JOIN "a" "a2" ON ("a2"."bid2" = "b1"."id") \ + JOIN "b" "b2" ON ("b2"."id" = "a1"."bid2") \ + JOIN "a" "a3" ON ("a3"."bid1" = "b2"."id") \ + WHERE ((("a1"."name" IS NOT NULL) AND ("a1"."name" > "a3"."name")) AND ("a2"."name" = 'foo')) + """ + + do { + // Filter first + let request = A + .filter(condition) + .aliased(rootA) + .including(required: A.b1 + .including(required: B.a2.aliased(A2))) + .including(required: A.b2 + .including(required: B.a1.aliased(A1))) + try assertEqualSQL(db, request, expectedSQL) + } + + do { + // Filter last + let request = A + .aliased(rootA) + .including(required: A.b1 + .including(required: B.a2.aliased(A2))) + .including(required: A.b2 + .including(required: B.a1.aliased(A1))) + .filter(condition) + try assertEqualSQL(db, request, expectedSQL) + } + } + } +} diff --git a/Tests/GRDBTests/ColumnExpressionTests.swift b/Tests/GRDBTests/ColumnExpressionTests.swift index 5c6625171..dae9e253e 100644 --- a/Tests/GRDBTests/ColumnExpressionTests.swift +++ b/Tests/GRDBTests/ColumnExpressionTests.swift @@ -71,8 +71,9 @@ class ColumnExpressionTests: GRDBTestCase { // Test FTS3 match expression let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo")) - var arguments: StatementArguments? = nil - XCTAssertEqual(expression.expressionSQL(&arguments), "(\"name\" MATCH 'foo')") + let literal = expression.literal + XCTAssertEqual(literal.sql, "(\"name\" MATCH ?)") + XCTAssertEqual(literal.arguments, ["foo"]) } } @@ -132,8 +133,9 @@ class ColumnExpressionTests: GRDBTestCase { // Test FTS3 match expression let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo")) - var arguments: StatementArguments? = nil - XCTAssertEqual(expression.expressionSQL(&arguments), "(\"name\" MATCH 'foo')") + let literal = expression.literal + XCTAssertEqual(literal.sql, "(\"name\" MATCH ?)") + XCTAssertEqual(literal.arguments, ["foo"]) } } } diff --git a/Tests/GRDBTests/CursorTests.swift b/Tests/GRDBTests/CursorTests.swift index f73f99419..c69411c3b 100644 --- a/Tests/GRDBTests/CursorTests.swift +++ b/Tests/GRDBTests/CursorTests.swift @@ -78,21 +78,12 @@ class CursorTests: GRDBTestCase { } } - #if swift(>=4.1) func testCompactMap() { let cursor = AnyCursor(["1", "foo", "2"]).compactMap { Int($0) } XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertTrue(try cursor.next() == nil) // end } - #else - func testFlatMapOfOptional() { - let cursor = AnyCursor(["1", "foo", "2"]).flatMap { Int($0) } - XCTAssertEqual(try cursor.next()!, 1) - XCTAssertEqual(try cursor.next()!, 2) - XCTAssertTrue(try cursor.next() == nil) // end - } - #endif func testForEach() throws { let cursor = AnyCursor([1, 2]) diff --git a/Tests/GRDBTests/DatabaseAggregateTests.swift b/Tests/GRDBTests/DatabaseAggregateTests.swift index faf882210..bf466b528 100644 --- a/Tests/GRDBTests/DatabaseAggregateTests.swift +++ b/Tests/GRDBTests/DatabaseAggregateTests.swift @@ -295,11 +295,7 @@ class DatabaseAggregateTests: GRDBTestCase { struct Aggregate : DatabaseAggregate { var result: DatabaseValueConvertible? mutating func step(_ dbValues: [DatabaseValue]) { - #if swift(>=4.1) let ints = dbValues.compactMap { Int.fromDatabaseValue($0) } - #else - let ints = dbValues.flatMap { Int.fromDatabaseValue($0) } - #endif result = ints.reduce(0, +) } func finalize() -> DatabaseValueConvertible? { diff --git a/Tests/GRDBTests/DatabaseFunctionTests.swift b/Tests/GRDBTests/DatabaseFunctionTests.swift index 4fd02a4b7..60ae195bb 100644 --- a/Tests/GRDBTests/DatabaseFunctionTests.swift +++ b/Tests/GRDBTests/DatabaseFunctionTests.swift @@ -250,11 +250,7 @@ class DatabaseFunctionTests: GRDBTestCase { func testFunctionOfTwoArguments() throws { let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 2) { dbValues in - #if swift(>=4.1) let ints = dbValues.compactMap { Int.fromDatabaseValue($0) } - #else - let ints = dbValues.flatMap { Int.fromDatabaseValue($0) } - #endif return ints.reduce(0, +) } dbQueue.add(function: fn) diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index bf56708d7..4edded5e1 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -410,6 +410,41 @@ class DatabaseRegionTests : GRDBTestCase { } } + func testDatabaseRegionOfJoinedRequests() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE a (id INTEGER PRIMARY KEY, name TEXT)") + try db.execute("CREATE TABLE b (id INTEGER PRIMARY KEY, name TEXT, aid INTEGER REFERENCES a(id))") + try db.execute("CREATE TABLE c (id INTEGER PRIMARY KEY, name TEXT, aid INTEGER REFERENCES a(id))") + struct A: TableRecord { + static let databaseTableName = "a" + static let b = hasOne(B.self) + static let c = hasMany(C.self) + } + struct B: TableRecord { + static let databaseTableName = "b" + static let a = belongsTo(A.self) + } + struct C: TableRecord { + static let databaseTableName = "c" + } + do { + let request = A.filter(key: 1) + .including(optional: A.b.filter(key: 2)) + .including(optional: A.c.filter(keys: [1, 2, 3])) + // This test will fail when we are able to improve regions of joined requestt + try XCTAssertEqual(request.fetchedRegion(db).description, "a(id,name)[1],b(aid,id,name),c(aid,id,name)") + } + do { + let request = B.filter(key: 1) + .including(optional: B.a.filter(key: 2) + .including(optional: A.c.filter(keys: [1, 2, 3]))) + // This test will fail when we are able to improve regions of joined requestt + try XCTAssertEqual(request.fetchedRegion(db).description, "a(id,name),b(aid,id,name)[1],c(aid,id,name)") + } + } + } + func testDatabaseRegionOfDerivedRequests() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index b06954417..f2c8e18e0 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -31,11 +31,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { dbWriter.add(collation: collation) customFunction = DatabaseFunction("avgOf", pure: true) { dbValues in - #if swift(>=4.1) let sum = dbValues.compactMap { Int.fromDatabaseValue($0) }.reduce(0, +) - #else - let sum = dbValues.flatMap { Int.fromDatabaseValue($0) }.reduce(0, +) - #endif return Double(sum) / Double(dbValues.count) } dbWriter.add(function: self.customFunction) diff --git a/Tests/GRDBTests/SQLExpressionLiteralTests.swift b/Tests/GRDBTests/SQLExpressionLiteralTests.swift index 2b00e44c6..fff8c41fa 100644 --- a/Tests/GRDBTests/SQLExpressionLiteralTests.swift +++ b/Tests/GRDBTests/SQLExpressionLiteralTests.swift @@ -12,10 +12,10 @@ class SQLExpressionLiteralTests: GRDBTestCase { func testWithArguments() { let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 - var arguments: StatementArguments? = StatementArguments() - let sql = expression.expressionSQL(&arguments) + var context = SQLGenerationContext.literalGenerationContext(withArguments: true) + let sql = expression.expressionSQL(&context) XCTAssertEqual(sql, "((\"foo\" = ? COLLATE NOCASE) AND (\"baz\" >= ?))") - let values = arguments!.values + let values = context.arguments!.values XCTAssertEqual(values.count, 2) XCTAssertEqual(values[0], "'fooéı👨👨🏿🇫🇷🇨🇮'".databaseValue) XCTAssertEqual(values[1], 1.databaseValue) @@ -23,8 +23,9 @@ class SQLExpressionLiteralTests: GRDBTestCase { func testWithoutArguments() { let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 - var arguments: StatementArguments? = nil - let sql = expression.expressionSQL(&arguments) + var context = SQLGenerationContext.literalGenerationContext(withArguments: false) + let sql = expression.expressionSQL(&context) + XCTAssertNil(context.arguments) XCTAssertEqual(sql, "((\"foo\" = '''fooéı👨👨🏿🇫🇷🇨🇮''' COLLATE NOCASE) AND (\"baz\" >= 1))") } }