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/CHANGELOG.md b/CHANGELOG.md index ca07325a2..041f1ebd7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,59 @@ Release Notes ============= -## Next Version +## 3.0.0 -- Improved parsing of dates and date components ([#334](https://github.com/groue/GRDB.swift/pull/334) by @sobri909) +GRDB 3 is a release focused on **modernization**, **safety**, and **associations between record types**. + +It comes with new features, but also a few breaking changes, and a set of updated good practices. The [GRDB 2 Migration Guide](Documentation/GRDB2MigrationGuide.md) will help you upgrading your applications. + + +### New + +- Associations and Joins ([#319](https://github.com/groue/GRDB.swift/pull/319)). +- Enhancements to logical operators ([#336](https://github.com/groue/GRDB.swift/pull/336)). +- Foster auto-incremented primary keys ([#337](https://github.com/groue/GRDB.swift/pull/337)). +- ColumnExpression Protocol ([#340](https://github.com/groue/GRDB.swift/pull/340)). +- Improved parsing of dates and date components ([#334](https://github.com/groue/GRDB.swift/pull/334) by @sobri909). +- Common API for requests and associations derivation ([#347](https://github.com/groue/GRDB.swift/pull/347)). +- `DatabaseMigrator.appliedMigrations(in:)` returns the set of applied migrations identifiers in a database ([#321](https://github.com/groue/GRDB.swift/pull/321)). +- `Database.isSQLiteInternalTable(_:)` returns whether a table name is an internal SQLite table ([#321](https://github.com/groue/GRDB.swift/pull/321)). +- `Database.isGRDBInternalTable(_:)` returns whether a table name is an internal GRDB table ([#321](https://github.com/groue/GRDB.swift/pull/321)). +- Upgrade custom SQLite builds to [v3.23.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)). +- Improve Row descriptions ([#331](https://github.com/groue/GRDB.swift/pull/331)). +- Request derivation protocols ([#329](https://github.com/groue/GRDB.swift/pull/329)). +- Preliminary Linux support for the main framework ([#354](https://github.com/groue/GRDB.swift/pull/354)). +- Automatic table name generation ([#355](https://github.com/groue/GRDB.swift/pull/355)). +- Delayed Request Ordering ([#365](https://github.com/groue/GRDB.swift/pull/365)). + + +### Breaking Changes + +- Swift 4.1 is now required. +- iOS 8 sunsetting: GRDB 3 is only tested on iOS 9+, due to a limitation in Xcode 9.3. Code that targets older versions of SQLite and iOS is still there, but is not supported. +- The Record protocols have been renamed: `RowConvertible` to `FetchableRecord`, `Persistable` to `PersistableRecord`, and `TableMapping` to `TableRecord` ([#314](https://github.com/groue/GRDB.swift/pull/314)). +- Implicit transaction in DatabasePool.write and DatabaseQueue.write ([#332](https://github.com/groue/GRDB.swift/pull/332)). +- `Request` and `TypedRequest` protocols have been merged into `FetchRequest` ([#311](https://github.com/groue/GRDB.swift/pull/311), [#328](https://github.com/groue/GRDB.swift/pull/328), [#348](https://github.com/groue/GRDB.swift/pull/348)). +- Reversing unordered requests has no effect ([#342](https://github.com/groue/GRDB.swift/pull/342)). +- The `IteratorCursor` type has been removed. Use `AnyCursor` instead ([#312](https://github.com/groue/GRDB.swift/pull/312)). +- Row scopes collection, breadth-first scope search ([#335](https://github.com/groue/GRDB.swift/pull/335)). +- Expressions are no longer PATs ([#330](https://github.com/groue/GRDB.swift/pull/330)). +- Deprecated APIs have been removed. + + +### Documentation Diff + +- [Associations](Documentation/AssociationsBasics.md): Discover the major GRDB 3 feature +- [Database Queues](README.md#database-queues): focus on the `read` and `write` methods. +- [Database Pools](README.md#database-pools): focus on the `read` and `write` methods. +- [Transactions and Savepoints](README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature. +- [ScopeAdapter](README.md#scopeadapter): do you use row adapters? If so, have a look. +- [TableRecord Protocol](README.md#tablerecord-protocol): updated for the new automatic generation of database table name. +- [Examples of Record Definitions](README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass). +- [SQL Operators](README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`. +- [Custom Requests](README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter. +- [Customized Decoding of Database Rows](README.md#customized-decoding-of-database-rows): learn how to escape the ready-made `FetchableRecord` protocol when it does not fit your needs. +- [Migrations](README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests). ## 2.10.0 diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index 4ae785152..22548585a 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -21,11 +21,9 @@ 56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; }; 56B036111E8D9EBE003B6DA4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */; }; 56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; }; - 56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Person.swift */; }; - 56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */; }; - 56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */; }; - 56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */; }; - 56B036251E8D9F4C003B6DA4 /* SimplePersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */; }; + 56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; }; + 56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; }; + 56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */; }; 56B0365E1E8D9FB1003B6DA4 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; }; 56B0365F1E8D9FB1003B6DA4 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; /* End PBXBuildFile section */ @@ -195,11 +193,9 @@ 56B036101E8D9EBE003B6DA4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 56B036121E8D9EBE003B6DA4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = ""; }; - 56B0361A1E8D9F38003B6DA4 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = ""; }; - 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DemoViewController.swift; sourceTree = ""; }; - 56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = ""; }; - 56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonsViewController.swift; sourceTree = ""; }; - 56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimplePersonsViewController.swift; sourceTree = ""; }; + 56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = ""; }; + 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = ""; }; + 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = ""; }; 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../GRDB.xcodeproj; sourceTree = ""; }; /* End PBXFileReference section */ @@ -270,8 +266,9 @@ children = ( 56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */, 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */, - 56B0361A1E8D9F38003B6DA4 /* Person.swift */, - 56B0361D1E8D9F3D003B6DA4 /* Controllers */, + 56B0361A1E8D9F38003B6DA4 /* Player.swift */, + 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */, + 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */, 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */, 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */, 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */, @@ -280,17 +277,6 @@ path = GRDBDemoiOS; sourceTree = ""; }; - 56B0361D1E8D9F3D003B6DA4 /* Controllers */ = { - isa = PBXGroup; - children = ( - 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */, - 56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */, - 56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */, - 56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */, - ); - name = Controllers; - sourceTree = ""; - }; 56B036271E8D9F79003B6DA4 /* Products */ = { isa = PBXGroup; children = ( @@ -524,13 +510,11 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */, + 56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */, 56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */, 56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */, - 56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */, - 56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */, - 56B036251E8D9F4C003B6DA4 /* SimplePersonsViewController.swift in Sources */, - 56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */, + 56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */, + 56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -770,7 +754,6 @@ GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 4.0; VALIDATE_PRODUCT = YES; diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index aa51dbb34..dd39c279e 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -25,14 +25,14 @@ struct AppDatabase { static var migrator: DatabaseMigrator { var migrator = DatabaseMigrator() - migrator.registerMigration("createPersons") { db in + migrator.registerMigration("createPlayer") { db in // Create a table // See https://github.com/groue/GRDB.swift#create-tables - try db.create(table: "persons") { t in + try db.create(table: "player") { t in // An integer primary key auto-generates unique IDs t.column("id", .integer).primaryKey() - // Sort person names in a localized case insensitive fashion by default + // Sort player names in a localized case insensitive fashion by default // See https://github.com/groue/GRDB.swift/#unicode t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare) @@ -41,12 +41,13 @@ struct AppDatabase { } migrator.registerMigration("fixtures") { db in - // Populate the persons table with random data + // Populate the players table with random data for _ in 0..<8 { - try Person(name: Person.randomName(), score: Person.randomScore()).insert(db) + var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore()) + try player.insert(db) } } - + // // Migrations for future application versions will be inserted here: // migrator.registerMigration(...) { db in // ... @@ -55,3 +56,4 @@ struct AppDatabase { return migrator } } + diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift index 068caa82a..eaa484e98 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift @@ -18,7 +18,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent("db.sqlite") dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path) - + // Be a nice iOS citizen, and don't consume too much memory // See https://github.com/groue/GRDB.swift/#memory-management dbQueue.setupMemoryManagement(in: application) diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Assets.xcassets/AppIcon.appiconset/Contents.json b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Assets.xcassets/AppIcon.appiconset/Contents.json index b51e72289..397149f3e 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -1,15 +1,5 @@ { "images" : [ - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "3x" - }, { "idiom" : "iphone", "size" : "29x29", @@ -42,16 +32,6 @@ "filename" : "Icon-60@3x.png", "scale" : "3x" }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "2x" - }, { "idiom" : "ipad", "size" : "29x29", diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard index 12b3c428d..c74e6a1c6 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard @@ -1,69 +1,19 @@ - - + + + + + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + @@ -72,13 +22,14 @@ - + - + + @@ -94,13 +45,14 @@ - + - + + @@ -124,12 +76,12 @@ - + - + @@ -146,79 +98,14 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + @@ -227,49 +114,49 @@ - + - + - + - + - + - - + + - + - + @@ -291,20 +178,23 @@ - + + + + + - + - + - - + diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/DemoViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/DemoViewController.swift deleted file mode 100644 index 88bff6034..000000000 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/DemoViewController.swift +++ /dev/null @@ -1,10 +0,0 @@ -import UIKit - -class DemoViewController: UITableViewController { - - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(true) - navigationController?.isToolbarHidden = true - navigationItem.backBarButtonItem = UIBarButtonItem(title: "Demo", style: .plain, target: nil, action: nil) - } -} diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Icon.sketch b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Icon.sketch deleted file mode 100644 index f2138aaa9..000000000 Binary files a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Icon.sketch and /dev/null differ diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Info.plist b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Info.plist index 16a522b47..6905cc67b 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Info.plist +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Info.plist @@ -4,8 +4,6 @@ CFBundleDevelopmentRegion en - CFBundleDisplayName - GRDB Demo CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier @@ -18,6 +16,8 @@ APPL CFBundleShortVersionString 1.0 + CFBundleSignature + ???? CFBundleVersion 1 LSRequiresIPhoneOS @@ -33,6 +33,8 @@ UISupportedInterfaceOrientations UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonsViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonsViewController.swift deleted file mode 100644 index d927417fa..000000000 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonsViewController.swift +++ /dev/null @@ -1,234 +0,0 @@ -import UIKit -import GRDB - -class PersonsViewController: UITableViewController { - var personsController: FetchedRecordsController! - - override func viewDidLoad() { - super.viewDidLoad() - - navigationItem.rightBarButtonItems = [ - UIBarButtonItem(barButtonSystemItem: .add, target: self, action: .addPerson), - editButtonItem - ] - - personsController = try! FetchedRecordsController(dbQueue, request: personsSortedByScore) - personsController.trackChanges( - willChange: { [unowned self] _ in - self.tableView.beginUpdates() - }, - onChange: { [unowned self] (controller, record, change) in - switch change { - case .insertion(let indexPath): - self.tableView.insertRows(at: [indexPath], with: .fade) - - case .deletion(let indexPath): - self.tableView.deleteRows(at: [indexPath], with: .fade) - - case .update(let indexPath, _): - if let cell = self.tableView.cellForRow(at: indexPath) { - self.configure(cell, at: indexPath) - } - - case .move(let indexPath, let newIndexPath, _): - // Actually move cells around for more demo effect :-) - let cell = self.tableView.cellForRow(at: indexPath) - self.tableView.moveRow(at: indexPath, to: newIndexPath) - if let cell = cell { - self.configure(cell, at: newIndexPath) - } - - // A quieter animation: - // self.tableView.deleteRows(at: [indexPath], with: .fade) - // self.tableView.insertRows(at: [newIndexPath], with: .fade) - } - }, - didChange: { [unowned self] _ in - self.tableView.endUpdates() - }) - try! personsController.performFetch() - - configureToolbar() - } - - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - navigationController?.isToolbarHidden = false - } -} - - -// MARK: - Navigation - -extension PersonsViewController : PersonEditionViewControllerDelegate { - - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - if segue.identifier == "EditPerson" { - let person = personsController.record(at: tableView.indexPathForSelectedRow!) - let controller = segue.destination as! PersonEditionViewController - controller.title = person.name - controller.person = person - controller.delegate = self // we will save person when back button is tapped - controller.cancelButtonHidden = true - controller.commitButtonHidden = true - } - else if segue.identifier == "NewPerson" { - setEditing(false, animated: true) - let navigationController = segue.destination as! UINavigationController - let controller = navigationController.viewControllers.first as! PersonEditionViewController - controller.title = "New Person" - controller.person = Person(name: "", score: 0) - } - } - - @IBAction func addPerson(_ sender: AnyObject?) { - performSegue(withIdentifier: "NewPerson", sender: sender) - } - - @IBAction func cancelPersonEdition(_ segue: UIStoryboardSegue) { - // Person creation: cancel button was tapped - } - - @IBAction func commitPersonEdition(_ segue: UIStoryboardSegue) { - // Person creation: commit button was tapped - let controller = segue.source as! PersonEditionViewController - controller.applyChanges() - let person = controller.person! - if !person.name.isEmpty { - try! dbQueue.inDatabase { db in - try person.save(db) - } - } - } - - func personEditionControllerDidComplete(_ controller: PersonEditionViewController) { - // Person edition: back button was tapped - controller.applyChanges() - let person = controller.person! - if !person.name.isEmpty { - try! dbQueue.inDatabase { db in - try person.save(db) - } - } - } -} - - -// MARK: - UITableViewDataSource - -extension PersonsViewController { - func configure(_ cell: UITableViewCell, at indexPath: IndexPath) { - let person = personsController.record(at: indexPath) - cell.textLabel?.text = person.name - cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point" - } - - override func numberOfSections(in tableView: UITableView) -> Int { - return personsController.sections.count - } - - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return personsController.sections[section].numberOfRecords - } - - override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath) - configure(cell, at: indexPath) - return cell - } - - override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { - // Delete the person - let person = personsController.record(at: indexPath) - try! dbQueue.inDatabase { db in - _ = try person.delete(db) - } - } -} - - -// MARK: - FetchedRecordsController Demo - -extension PersonsViewController { - - fileprivate func configureToolbar() { - toolbarItems = [ - UIBarButtonItem(title: "Name ⬆︎", style: .plain, target: self, action: .sortByName), - UIBarButtonItem(title: "Score ⬇︎", style: .plain, target: self, action: .sortByScore), - UIBarButtonItem(title: "Randomize", style: .plain, target: self, action: .randomizeScores), - UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), - UIBarButtonItem(title: "💣", style: .plain, target: self, action: .stressTest) - ] - } - - @IBAction func sortByName() { - setEditing(false, animated: true) - try! personsController.setRequest(personsSortedByName) - } - - @IBAction func sortByScore() { - setEditing(false, animated: true) - try! personsController.setRequest(personsSortedByScore) - } - - @IBAction func randomizeScores() { - setEditing(false, animated: true) - - try! dbQueue.inTransaction { db in - for person in try Person.fetchAll(db) { - person.score = Person.randomScore() - try person.update(db) - } - return .commit - } - } - - @IBAction func stressTest() { - setEditing(false, animated: true) - - for _ in 0..<50 { - DispatchQueue.global().async { - try! dbQueue.inTransaction { db in - if try Person.fetchCount(db) == 0 { - // Insert persons - for _ in 0..<8 { - try Person(name: Person.randomName(), score: Person.randomScore()).insert(db) - } - } else { - // Insert a person - if arc4random_uniform(2) == 0 { - let person = Person(name: Person.randomName(), score: Person.randomScore()) - try person.insert(db) - } - // Delete a person - if arc4random_uniform(2) == 0 { - if let person = try Person.order(sql: "RANDOM()").fetchOne(db) { - try person.delete(db) - } - } - // Update some persons - for person in try Person.fetchAll(db) { - if arc4random_uniform(2) == 0 { - person.score = Person.randomScore() - try person.update(db) - } - } - } - return .commit - } - } - } - } -} - -// https://medium.com/swift-programming/swift-selector-syntax-sugar-81c8a8b10df3 -private extension Selector { - static let addPerson = #selector(PersonsViewController.addPerson(_:)) - static let sortByName = #selector(PersonsViewController.sortByName) - static let sortByScore = #selector(PersonsViewController.sortByScore) - static let randomizeScores = #selector(PersonsViewController.randomizeScores) - static let stressTest = #selector(PersonsViewController.stressTest) -} - -private let personsSortedByName = Person.order(Column("name")) -private let personsSortedByScore = Person.order(Column("score").desc, Column("name")) diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift similarity index 50% rename from DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift rename to DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift index 539325d6e..600e6adbe 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift @@ -1,49 +1,28 @@ import GRDB -class Person: Record { +struct Player: Codable, FetchableRecord, MutablePersistableRecord { var id: Int64? var name: String var score: Int - - init(name: String, score: Int) { - self.name = name - self.score = score - super.init() + + enum Columns: String, ColumnExpression { + case id, name, score } - // MARK: Record overrides - - override class var databaseTableName: String { - return "persons" - } - - required init(row: Row) { - id = row["id"] - name = row["name"] - score = row["score"] - super.init(row: row) - } - - override func encode(to container: inout PersistenceContainer) { - container["id"] = id - container["name"] = name - container["score"] = score - } - - override func didInsert(with rowID: Int64, for column: String?) { + /// Update player id after successful insertion + mutating func didInsert(with rowID: Int64, for column: String?) { id = rowID } - - // MARK: Random - +} + +extension Player { private static let names = ["Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David", "Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette", "Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl", "Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole", "Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul", "Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain", "Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann", "Zazie", "Zoé"] - class func randomName() -> String { + static func randomName() -> String { return names[Int(arc4random_uniform(UInt32(names.count)))] } - class func randomScore() -> Int { + static func randomScore() -> Int { return 10 * Int(arc4random_uniform(101)) } - } diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonEditionViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift similarity index 67% rename from DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonEditionViewController.swift rename to DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift index 3711e6920..1d9f3e3af 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonEditionViewController.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift @@ -1,13 +1,12 @@ import UIKit -protocol PersonEditionViewControllerDelegate: class { - func personEditionControllerDidComplete(_ controller: PersonEditionViewController) +protocol PlayerEditionViewControllerDelegate: class { + func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController) } -class PersonEditionViewController: UITableViewController { - weak var delegate: PersonEditionViewControllerDelegate? - var person: Person! { didSet { configureView() } } - var cancelButtonHidden: Bool = false { didSet { configureView() } } +class PlayerEditionViewController: UITableViewController { + weak var delegate: PlayerEditionViewControllerDelegate? + var player: Player! { didSet { configureView() } } var commitButtonHidden: Bool = false { didSet { configureView() } } @IBOutlet fileprivate weak var cancelBarButtonItem: UIBarButtonItem! @@ -17,37 +16,27 @@ class PersonEditionViewController: UITableViewController { @IBOutlet fileprivate weak var scoreCell: UITableViewCell! @IBOutlet fileprivate weak var scoreTextField: UITextField! - func applyChanges() { - if let name = nameTextField.text, !name.isEmpty { - person.name = name - } - person.score = scoreTextField.text.flatMap { Int($0) } ?? 0 - } - override func viewDidLoad() { super.viewDidLoad() configureView() } - private func configureView() { + fileprivate func configureView() { guard isViewLoaded else { return } - nameTextField.text = person.name - if person.score == 0 && person.id == nil { + nameTextField.text = player.name + + if player.score == 0 && player.id == nil { scoreTextField.text = "" } else { - scoreTextField.text = "\(person.score)" + scoreTextField.text = "\(player.score)" } - if cancelButtonHidden { + if commitButtonHidden { navigationItem.leftBarButtonItem = nil - } else { - navigationItem.leftBarButtonItem = cancelBarButtonItem - } - - if cancelButtonHidden { navigationItem.rightBarButtonItem = nil } else { + navigationItem.leftBarButtonItem = cancelBarButtonItem navigationItem.rightBarButtonItem = commitBarButtonItem } } @@ -56,7 +45,7 @@ class PersonEditionViewController: UITableViewController { // MARK: - Navigation -extension PersonEditionViewController { +extension PlayerEditionViewController { override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { // Force keyboard to dismiss early @@ -64,12 +53,19 @@ extension PersonEditionViewController { return true } + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "Commit" { + applyChanges() + } + } + override func willMove(toParentViewController parent: UIViewController?) { super.willMove(toParentViewController: parent) if parent == nil { // Self is popping from its navigation controller - delegate?.personEditionControllerDidComplete(self) + applyChanges() + delegate?.playerEditionControllerDidComplete(self) } } @@ -78,7 +74,7 @@ extension PersonEditionViewController { // MARK: - Form -extension PersonEditionViewController: UITextFieldDelegate { +extension PlayerEditionViewController: UITextFieldDelegate { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) @@ -101,4 +97,13 @@ extension PersonEditionViewController: UITextFieldDelegate { } return false } + + private func applyChanges() { + guard var player = self.player else { + return + } + player.name = nameTextField.text ?? "" + player.score = scoreTextField.text.flatMap { Int($0) } ?? 0 + self.player = player + } } diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift new file mode 100644 index 000000000..8c4d66479 --- /dev/null +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift @@ -0,0 +1,250 @@ +import UIKit +import GRDB + +class PlayersViewController: UITableViewController { + enum PlayerOrdering { + case byName + case byScore + + var request: QueryInterfaceRequest { + switch self { + case .byName: + return Player.order(Player.Columns.name) + case .byScore: + return Player.order(Player.Columns.score.desc, Player.Columns.name) + } + } + } + + var playersController: FetchedRecordsController! + var playerOrdering: PlayerOrdering = .byScore { + didSet { + try! playersController.setRequest(playerOrdering.request) + configureNavigationItem() + } + } + + @IBOutlet weak var newPlayerButtonItem: UIBarButtonItem! + + override func viewDidLoad() { + super.viewDidLoad() + configureTableView() + configureToolbar() + configureNavigationItem() + } + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + navigationController?.isToolbarHidden = false + } +} + + +// MARK: - Navigation + +extension PlayersViewController : PlayerEditionViewControllerDelegate { + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "Edit" { + let player = playersController.record(at: tableView.indexPathForSelectedRow!) + let controller = segue.destination as! PlayerEditionViewController + controller.title = player.name + controller.player = player + controller.delegate = self // See playerEditionControllerDidComplete + controller.commitButtonHidden = true + } + else if segue.identifier == "New" { + setEditing(false, animated: true) + let navigationController = segue.destination as! UINavigationController + let controller = navigationController.viewControllers.first as! PlayerEditionViewController + controller.title = "New Player" + controller.player = Player(id: nil, name: "", score: 0) + } + } + + @IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) { + // Player creation: cancel button was tapped + } + + @IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) { + // Player creation: commit button was tapped + let controller = segue.source as! PlayerEditionViewController + try! dbQueue.write { db in + try controller.player.save(db) + } + } + + func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController) { + // Player edition: user has finished editing the player + try! dbQueue.write { db in + try controller.player.save(db) + } + } +} + + +// MARK: - UITableViewDataSource + +extension PlayersViewController { + private func configureTableView() { + playersController = try! FetchedRecordsController(dbQueue, request: playerOrdering.request) + + playersController.trackChanges( + willChange: { [unowned self] _ in + self.tableView.beginUpdates() + }, + onChange: { [unowned self] (controller, record, change) in + switch change { + case .insertion(let indexPath): + self.tableView.insertRows(at: [indexPath], with: .fade) + + case .deletion(let indexPath): + self.tableView.deleteRows(at: [indexPath], with: .fade) + + case .update(let indexPath, _): + if let cell = self.tableView.cellForRow(at: indexPath) { + self.configure(cell, at: indexPath) + } + + case .move(let indexPath, let newIndexPath, _): + // Actually move cells around for more demo effect :-) + let cell = self.tableView.cellForRow(at: indexPath) + self.tableView.moveRow(at: indexPath, to: newIndexPath) + if let cell = cell { + self.configure(cell, at: newIndexPath) + } + + // A quieter animation: + // self.tableView.deleteRows(at: [indexPath], with: .fade) + // self.tableView.insertRows(at: [newIndexPath], with: .fade) + } + }, + didChange: { [unowned self] _ in + self.tableView.endUpdates() + }) + + try! playersController.performFetch() + } + + override func numberOfSections(in tableView: UITableView) -> Int { + return playersController.sections.count + } + + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return playersController.sections[section].numberOfRecords + } + + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath) + configure(cell, at: indexPath) + return cell + } + + override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { + // Delete the player + let player = playersController.record(at: indexPath) + try! dbQueue.write { db in + _ = try player.delete(db) + } + } + + private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) { + let player = playersController.record(at: indexPath) + if player.name.isEmpty { + cell.textLabel?.text = "(anonymous)" + } else { + cell.textLabel?.text = player.name + } + cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point" + } +} + + +// MARK: - Actions + +extension PlayersViewController { + private func configureNavigationItem() { + navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem] + + switch playerOrdering { + case .byScore: + navigationItem.rightBarButtonItem = UIBarButtonItem( + title: "Score ⬇︎", + style: .plain, + target: self, action: #selector(sortByName)) + case .byName: + navigationItem.rightBarButtonItem = UIBarButtonItem( + title: "Name ⬆︎", + style: .plain, + target: self, action: #selector(sortByScore)) + } + } + + private func configureToolbar() { + toolbarItems = [ + UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)), + UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), + UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)), + UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), + UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)), + ] + } + + @IBAction func sortByName() { + setEditing(false, animated: true) + playerOrdering = .byName + } + + @IBAction func sortByScore() { + setEditing(false, animated: true) + playerOrdering = .byScore + } + + @IBAction func deletePlayers() { + setEditing(false, animated: true) + try! dbQueue.write { db in + _ = try Player.deleteAll(db) + } + } + + @IBAction func refresh() { + setEditing(false, animated: true) + refreshPlayers() + } + + @IBAction func stressTest() { + setEditing(false, animated: true) + for _ in 0..<50 { + DispatchQueue.global().async { + self.refreshPlayers() + } + } + } + + private func refreshPlayers() { + try! dbQueue.write { db in + if try Player.fetchCount(db) == 0 { + // Insert new random players + for _ in 0..<8 { + var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore()) + try player.insert(db) + } + } else { + // Insert a player + if arc4random_uniform(2) == 0 { + var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore()) + try player.insert(db) + } + // Delete a random player + if arc4random_uniform(2) == 0 { + try Player.order(sql: "RANDOM()").limit(1).deleteAll(db) + } + // Update some players + for var player in try Player.fetchAll(db) where arc4random_uniform(2) == 0 { + player.score = Player.randomScore() + try player.update(db) + } + } + } + } +} diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePersonsViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePersonsViewController.swift deleted file mode 100644 index 8cd4c0e82..000000000 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePersonsViewController.swift +++ /dev/null @@ -1,114 +0,0 @@ -import UIKit -import GRDB - -class SimplePersonsViewController: UITableViewController { - var persons: [Person]! - - override func viewDidLoad() { - super.viewDidLoad() - - navigationItem.rightBarButtonItems = [ - UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(SimplePersonsViewController.addPerson(_:))), - editButtonItem - ] - } - - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - loadPersons() - tableView.reloadData() - } - - private func loadPersons() { - persons = try! dbQueue.inDatabase { db in - try Person.order(Column("score").desc, Column("name")).fetchAll(db) - } - } -} - - -// MARK: - Navigation - -extension SimplePersonsViewController : PersonEditionViewControllerDelegate { - - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - if segue.identifier == "EditPerson" { - let person = persons[tableView.indexPathForSelectedRow!.row] - let controller = segue.destination as! PersonEditionViewController - controller.title = person.name - controller.person = person - controller.delegate = self // we will save person when back button is tapped - controller.cancelButtonHidden = true - controller.commitButtonHidden = true - } - else if segue.identifier == "NewPerson" { - setEditing(false, animated: true) - let navigationController = segue.destination as! UINavigationController - let controller = navigationController.viewControllers.first as! PersonEditionViewController - controller.title = "New Person" - controller.person = Person(name: "", score: 0) - } - } - - @IBAction func addPerson(_ sender: AnyObject?) { - performSegue(withIdentifier: "NewPerson", sender: sender) - } - - @IBAction func cancelPersonEdition(_ segue: UIStoryboardSegue) { - // Person creation: cancel button was tapped - } - - @IBAction func commitPersonEdition(_ segue: UIStoryboardSegue) { - // Person creation: commit button was tapped - let controller = segue.source as! PersonEditionViewController - controller.applyChanges() - let person = controller.person! - if !person.name.isEmpty { - try! dbQueue.inDatabase { db in - try person.save(db) - } - } - } - - func personEditionControllerDidComplete(_ controller: PersonEditionViewController) { - // Person edition: back button was tapped - controller.applyChanges() - let person = controller.person! - if !person.name.isEmpty { - try! dbQueue.inDatabase { db in - try person.save(db) - } - } - } -} - - -// MARK: - UITableViewDataSource - -extension SimplePersonsViewController { - func configure(_ cell: UITableViewCell, at indexPath: IndexPath) { - let person = persons[indexPath.row] - cell.textLabel?.text = person.name - cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point" - } - - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return persons.count - } - - override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath) - configure(cell, at: indexPath) - return cell - } - - override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { - // Delete the person - let person = persons[indexPath.row] - try! dbQueue.inDatabase { db in - _ = try person.delete(db) - } - persons.remove(at: indexPath.row) - tableView.deleteRows(at: [indexPath], with: .fade) - } -} diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md new file mode 100644 index 000000000..3dd949da6 --- /dev/null +++ b/Documentation/AssociationsBasics.md @@ -0,0 +1,1465 @@ +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] +- [DerivableRequest Protocol] +- [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, Decodable { + 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 `Book.author` association as below, with its companion property: + +```swift +struct Book: TableRecord { + static let author = belongsTo(Author.self) + var author: QueryInterfaceRequest { + return request(for: Book.author) + } + ... +} + +struct Author: TableRecord { + ... +} +``` + +The `Book.author` association will help you build [association requests]. The property lets you fetch a book's author: + +```swift +let book: Book = ... +let author = try book.author.fetchOne(db) // Author? +``` + +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/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 `Country.demographics` association as below, with its companion property: + +```swift +struct Country: TableRecord { + static let demographics = hasOne(Demographics.self) + var demographics: QueryInterfaceRequest { + return request(for: Country.demographics) + } + ... +} + +struct Demographics: TableRecord { + ... +} +``` + +The `Country.demographics` association will help you build [association requests]. The property lets you fetch a country's demographic profile: + +```swift +let country: Country = ... +let demographics = try country.demographics.fetchOne(db) // Demographics? +``` + +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/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 `Author.books` association as below, with its companion property: + +```swift +struct Author: TableRecord { + static let books = hasMany(Book.self) + var books: QueryInterfaceRequest { + return request(for: Author.books) + } +} + +struct Book: TableRecord { + ... +} +``` + +The `Author.books` association will help you build [association requests]. The property lets you fetch an author's books: + +```swift +let author: Author = ... +let books = try author.books.fetchAll(db) // [Book] +``` + +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/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/Documentation/Images/Associations2/HasOneSchema.svg) + +```swift +struct Country: TableRecord, FetchableRecord { + static let demographics = hasOne(Demographics.self) + ... +} + +struct Demographics: TableRecord, FetchableRecord { + static let country = belongsTo(Country.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/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.** + +Make them look like Swift identifiers: `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 Author record +struct Author: FetchableRecord, TableRecord { +} + +// The Book record +struct Book: FetchableRecord, TableRecord { + static let author = belongsTo(Author.self) +} + +// A pair made of a book and its author +struct BookInfo: FetchableRecord, Decodable { + 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". The name "author" is the key that helps BookInfo initialize its `author` property. For your convenience, "author" is also the default value of the `Author.databaseTableName` property (see the [TableRecord] protocol). + +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 +// Setup for customized table names + +struct Author: FetchableRecord, TableRecord { + // Customized table name + static let databaseTableName = "authors" +} + +struct Book: FetchableRecord, TableRecord { + // Customized table name + static let databaseTableName = "books" + + // Explicit association key + static let author = belongsTo(Author.self, key: "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/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 author = belongsTo(Author.self) +} + +struct Author: FetchableRecord, TableRecord { +} +``` + +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/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 demographics = hasOne(Demographics.self) +} + +struct Demographics: FetchableRecord, TableRecord { +} +``` + +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 Country: 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/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 { +} + +struct Author: FetchableRecord, TableRecord { + 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/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/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 person", or "Could not infer foreign key from book to person". + +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 query interface columns: + +```swift +struct Book: TableRecord { + enum Columns: String, ColumnExpression { + case id, title, authorId, translatorId + } + + static let authorForeignKey = ForeignKey([Columns.authorId])) + static let translatorForeignKey = ForeignKey([Columns.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] +``` + +Requests for associated records can be filtered and ordered like all [query interface requests]: + +```swift +let novels = try author + .books + .filter(Column("kind") == BookKind.novel) + .order(Column("publishDate").desc) + .fetchAll(db) +``` + +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](../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](../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](../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 b.* +// FROM book b +// JOIN person a ON a.id = b.authorId +// AND a.countryCode = 'FR' +// WHERE b.publishDate >= a.deathDate +let bookAlias = TableAlias(name: "b") +let authorAlias = TableAlias(name: "a") +let request = Book.aliased(bookAlias) + .joining(required: Book.author.aliased(authorAlias) + .filter(sql: "a.countryCode = ?", arguments: ["FR"])) + .filter(sql: "b.publishDate >= a.deathDate") +``` + +> :point_up: **Note**: avoid reusing table aliases between several tables or requests, because you will get a fatal error: +> +> ```swift +> // Fatal error: A TableAlias most not be used to refer to multiple tables +> let alias = TableAlias() +> let books = Book.aliased(alias)... +> let people = Person.aliased(alias)... +> ``` + + +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/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/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/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, key: "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](../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. + + +## DerivableRequest Protocol + +The `DerivableRequest` protocol is adopted by both [query interface requests] such as `Author.all()` and associations such as `Book.author`. It is intended for you to use as a customization point when you want to extend the built-in GRDB apis. + +For example: + +```swift +extension DerivableRequest where RowDecoder == Author { + func filter(country: String) -> Self { + return filter(Column("country") == country) + } + + func orderByFullName() -> Self { + return order( + Column("lastName").collating(.localizedCaseInsensitiveCompare), + Column("firstName").collating(.localizedCaseInsensitiveCompare)) + } +} +``` + +Thanks to DerivableRequest, both the `filter(country:)` and `orderByFullName()` methods are now available for both Author-based requests and associations: + +```swift +// French authors sorted by full name: +let request = Author.all() + .filter(country: "FR") + .orderByFullName() + +// French books, sorted by full name of author: +let request = Book.joining(required: Book.author + .filter(country: "FR") + .orderByFullName()) +``` + + +## 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 +[FetchableRecord]: ../README.md#fetchablerecord-protocols +[migration]: ../README.md#migrations +[Record]: ../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]: ../README.md#custom-requests +[DerivableRequest Protocol]: #derivablerequest-protocol +[Known Issues]: #known-issues +[Future Directions]: #future-directions +[Row Adapters]: ../README.md#row-adapters +[query interface requests]: ../README.md#requests +[TableRecord]: ../README.md#tablerecord-protocol +[association requests]: #building-requests-from-associations diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index c9f525457..144a2923b 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -3,7 +3,7 @@ Custom SQLite Builds By default, GRDB uses the version of SQLite that ships with the target operating system. -**You can build GRDB with a custom build of [SQLite 3.22.0](https://www.sqlite.org/changes.html).** +**You can build GRDB with a custom build of [SQLite 3.23.0](https://www.sqlite.org/changes.html).** A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks). @@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal ```sh cd [GRDB directory] - git checkout v2.10.0 + git checkout v3.0.0-beta.1 git submodule update --init SQLiteCustom/src ```` diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md new file mode 100644 index 000000000..5ef3899ef --- /dev/null +++ b/Documentation/GRDB2MigrationGuide.md @@ -0,0 +1,534 @@ +Migrating From GRDB 2 to GRDB 3 +=============================== + +GRDB 3 comes with new features, but also a few breaking changes, and a set of updated good practices. This guide aims at helping you upgrading your applications. + +**For all users** + +- [How To Upgrade] +- [Swift 4.1 Required] +- [iOS 8 Sunsetting] +- [Database Schema Recommendations] +- [Record Protocols Renaming] +- [Columns Definition] + +**By topic** + +- [If You Use Database Queues] +- [If You Use Database Pools] +- [If You Use Database Snapshots] +- [If You Use Record Types] +- [If You Use Custom Requests] +- [If You Use RxGRDB] +- [Notable Documentation Updates] + + +## How to Upgrade + +Target the "GRDB3" branch: + +### CocoaPods + +Update your Podfile: + +```ruby +pod 'GRDB.swift', git: 'https://github.com/groue/GRDB.swift', branch: 'GRDB3' +``` + +### Swift Package Manager + +Update your Package.swift file: + +```swift +let package = Package( + dependencies: [ + .package(url: "https://github.com/groue/GRDB.swift.git", .branchItem("GRDB3")) + ] +) +``` + +### Manually + +Update your local copy of GRDB: + +```sh +git checkout GRDB3 +git pull +``` + +## Swift 4.1 Required + +GRDB 3 uses [conditional conformances], introduced in Swift 4.1. It can only be built on Xcode 9.3+. + + +## iOS 8 Sunsetting + +GRDB 3 is only tested on iOS 9+, due to a limitation in Xcode 9.3. Code that targets older versions of SQLite and iOS is still there, but is not supported. + + +## Database Schema Recommendations + +GRDB 2 was totally schema-agnostic, and would gladly accept any database. + +GRDB 3 still accepts any database, but brings two schema recommendations: + +- :bulb: Integer primary keys should be auto-incremented, in order to avoid any row id to be reused. + + When ids can be reused, your app and [database observation tools] may think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not. + + GRDB 3 thus comes with a new good practice: use the `autoIncrementedPrimaryKey` method when you create a database table with an integer primary key: + + ```diff + try db.create(table: "author") { t in + - t.column("id", .integer).primaryKey() // GRDB 2 + + t.autoIncrementedPrimaryKey("id") // GRDB 3 recommendation + t.column("name", .text).notNull() + } + ``` + +- :bulb: Database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, 'httpRequest'. + + This will help you using the new [Associations] feature when you need it. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration. + + This convention is applied by the default implementation of the `TableRecord.databaseTableName`: see [If You Use Record Types] below. + +Since you are reading this guide, your application has already defined its database schema. You can migrate it in order to apply the new recommendations, if needed. Below is a sample code that uses [DatabaseMigrator], the recommended tool for managing your database schema: + +```swift +var migrator = DatabaseMigrator() + +// Existing GRDB 2 migration: +migrator.registerMigration("initial") { db in + try db.create(table: "authors") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text).notNull() + } + try db.create(table: "books") { t in + t.column("id", .integer).primaryKey() + t.column("authorId", .integer).notNull().references("authors") + t.column("title", .text).notNull() + } +} + +// New GRDB 3 migration: +// - Rename tables so that they look like Swift identifiers (singular and camelCased) +// - Make integer primary keys auto-incremented +// +// Since several tables are recreated from scratch, referential integrity +// constraints may break during the process. The +// registerMigrationWithDeferredForeignKeyCheck method makes sure that foreign +// key checks are temporarily disabled, and checked at the end: +migrator.registerMigrationWithDeferredForeignKeyCheck("GRDB3") { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text).notNull() + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorId", .integer).notNull().references("author") + t.column("title", .text).notNull() + } + try db.execute(""" + INSERT INTO author SELECT * FROM authors; + INSERT INTO book SELECT * FROM books; + """) + try db.drop(table: "authors") + try db.drop(table: "books") +} +``` + + +## Record Protocols Renaming + +GRDB 3 has renamed the [record protocols]: + +- `RowConvertible` -> `FetchableRecord` +- `TableMapping` -> `TableRecord` +- `Persistable` -> `PersistableRecord` +- `MutablePersistable` -> `MutablePersistableRecord` + +After upgrading, build your project: the compiler will guide you through the renaming by the way of fixits. + + +## Columns Definition + +GRDB 2 has you define columns of the query interface with the Column type: + +```swift +// GRDB 2 +let nameColumn = Column("name") +let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) +``` + +A recommended practice was to define enum namespaces in record types: + +```swift +// GRDB 2 +struct Player: RowConvertible, TableMapping { + enum Columns { + static let id = Column("id") + static let name = Column("name") + static let score = Column("score") + } + + init(row: Row) { + id = row[Columns.id] + name = row[Columns.name] + score = row[Columns.score] + } +} +``` + +In GRDB 3, `Column` is still there, but a new `ColumnExpression` protocol has been introduced in order to streamline column enums: + +```swift +// GRDB 3 +struct Player: FetchableRecord, TableRecord { + enum Columns: String, ColumnExpression { + case id, name, score + } + + init(row: Row) { + id = row[Columns.id] + name = row[Columns.name] + score = row[Columns.score] + } +} +``` + +GRDB can apply additional optimizations on expressions that adopt ColumnExpression, so conform to this protocol when you define a custom column type: + +```swift +struct TypedColumn: ColumnExpression { + var name: String + var sqlType: String +} +let nameColumn = TypedColumn(name: "name", sqlType: "VARCHAR") +let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) +``` + + +## If You Use Database Queues + +With GRDB 2, you used to access the database through the `inDatabase` or `inTransaction` [DatabaseQueue] methods: + +```swift +// GRDB 2 +let players = try dbQueue.inDatabase { db in + try Player.fetchAll(db) +} + +try dbQueue.inDatabase { db in + try player.updateChanges(db) +} + +var balance: Amount! = nil +try dbQueue.inTransaction { db in + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + balance = try sourceAccount.fetchBalance(db) + return .commit +} +``` + +The code above still runs, unchanged, in GRDB 3. + +Yet it is now recommended that you use the `read` and `write` methods instead: + +```swift +// GRDB 3 +let players = try dbQueue.read { db in + try Player.fetchAll(db) +} + +try dbQueue.write { db in + try player.updateChanges(db) +} + +let balance = try dbQueue.write { db in + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + return try sourceAccount.fetchBalance(db) +} +``` + +The purpose of the new `read` and `write` methods is to soothe the "transaction mental load" of previous versions of GRDB, a legacy of the [FMDB] heritage. All developers can *forget* to open transactions, with the unfortunate consequence that the database may end up containing inconsistent values. Experienced developers may *wonder* whether they should open transactions or not, even when this doesn't matter a lot. + +With GRDB 3, use `read` when you need to read values. It's impossible to write within a `read` block, which means that you can be sure that no unwanted side effect can happen. + +When you need to write, use `write`: your database changes are automatically wrapped in a transaction, with the guarantee that all changes are written to disk, or, should any error happen, none at all. + +Of course, precise transaction handling sometimes matter. Check the updated [Transactions and Savepoints] chapter. + + +## If You Use Database Pools + +With GRDB 2, you used to access the database through the `read`, `write` or `writeInTransaction` [DatabasePool] methods: + +```swift +// GRDB 2 +let players = try dbPool.read { db in + try Player.fetchAll(db) +} + +try dbPool.write { db in + try player.updateChanges(db) +} + +var balance: Amount! = nil +try dbPool.writeInTransaction { db in + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + balance = try sourceAccount.fetchBalance(db) + return .commit +} +``` + +In GRDB 3, the `write` method has changed: it now automatically wraps your database changes in a transaction, which means that the last block can be rewritten as below: + +```swift +// GRDB 3 +let balance = try dbPool.write { db in + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + return try sourceAccount.fetchBalance(db) +} +``` + +Side effect: you can no longer open explicit transactions inside a `write` block: + +```swift +// GRDB 2: OK +// GRDB 3: SQLite error 1 with statement `BEGIN DEFERRED TRANSACTION`: +// cannot start a transaction within a transaction +try dbPool.write { db in + try db.inTransaction { ... } +} +``` + +When precise transaction handling is needed, check the updated [Transactions and Savepoints] chapter. + +The purpose of this change is to prevent an easy misuse of database pools in previous GRDB versions. Unless writes were wrapped inside an explicit transactions, concurrent reads could see an inconsistent state of the database: + +```swift +// GRDB 2: unsafe +// GRDB 3: safe +try dbPool.write { db in + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) +} +``` + +Since `write` now wraps your changes in a transaction, you have the guarantee that concurrent reads can't see them until they are all written to disk. + + +## If You Use Database Snapshots + +With GRDB 2, you used to create [database snapshots] with the `makeSnaphot` [DatabasePool] method. For example: + +```swift +// GRDB 2 +let snapshot: DatabaseSnapshot = try dbPool.write { db in + try Player.deleteAll() + return dbPool.makeSnapshot() +} + +// Guaranteed to be zero +let count = try snapshot.read { db in + try Player.fetchCount(db) +} +``` + +GRDB 3 will crash the above code on the `makeSnapshot()` line, with a fatal error: "makeSnapshot() must not be called from inside a transaction." + +To avoid this error, you will need [precise transaction handling]: + +```swift +// GRDB 3 +let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in + try Player.deleteAll() + return dbPool.makeSnapshot() +} +``` + + +## If You Use Record Types + +Record types that adopt the former TableMapping protocol, renamed TableRecord, used to declare their table name: + +```swift +// GRDB 2 +struct Place: TableMapping { + static let databaseTableName = "place" +} +print(Place.databaseTableName) // print "place" +``` + +With GRDB 3, the `databaseTableName` property gets a default implementation: + +```swift +// GRDB 3 +struct Place: TableRecord { } +print(Place.databaseTableName) // print "place" +``` + +That default name follows the [Database Schema Recommendations]: it is singular, camel-cased, and looks like a Swift identifier: + +- Place: `place` +- Country: `country` +- PostalAddress: `postalAddress` +- HTTPRequest: `httpRequest` +- TOEFL: `toefl` + +When you subclass the Record class, the Swift compiler won't let you profit from this default name: you have to keep on providing an explicit table name: + +```swift +// GRDB 2 and GRDB 3 +class Place: Record { + override var databaseTableName: String { + return "place" + } +} +``` + + +## If You Use Custom Requests + +[Custom requests] let you escape the limitations of the [query interface], when it can not generate the requests you need. + +You may, for example, use `SQLRequest`: + +```swift +// GRDB 2 +extension Player { + static func filter(color: Color) -> AnyTypedRequest { + let sql = "SELECT * FROM players WHERE color = ?" + let request = SQLRequest(sql, arguments: [color]) + return request.asRequest(of: Player.self) + } +} + +let players = try Player.filter(color: .red).fetchAll(db) +``` + +The `AnyTypedRequest` type is no longer available, and `SQLRequest` is now a generic type: + +```swift +// GRDB 3 +extension Player { + static func filter(color: Color) -> SQLRequest { + let sql = "SELECT * FROM players WHERE color = ?" + return SQLRequest(sql, arguments: [color]) + } +} + +let players = try Player.filter(color: .red).fetchAll(db) +``` + +See the updated [Custom Requests](../README.md#custom-requests) chapter for more information. + + +## If You Use RxGRDB + +To install the GRDB 3 flavor of RxGRDB, update your Podfile: + +```ruby +pod 'RxGRDB', git: 'https://github.com/groue/RxGRDB', branch: 'GRDB3' +``` + +Some APIs have slighly changed. Did you track multiple requests at the same time with "fetch tokens"? + +```swift +// GRDB 2 +dbQueue.rx + .fetchTokens(in: [...]) + .mapFetch { db in ... } + .subscribe(...) +``` + +Now you'll write instead: + +```swift +// GRDB 3 +dbQueue.rx + .fetch(from: [...]) { db in ... } + .subscribe(...) +``` + +It's just a syntactic change, without any impact on the runtime. + +RxGRDB for GRDB 3 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition. + +For example: + +```swift +// GRDB 2: Track a team and its players +let teamId = 1 +let teamRequest = Team.filter(key: teamId) +let playersRequest = Player.filter(teamId: teamId) +dbQueue.rx + .fetchTokens(in: [teamRequest, playersRequest]) + .mapFetch { db -> TeamInfo? in + guard let team = try teamRequest.fetchOne(db) else { + return nil + } + let players = try playersRequest.fetchAll(db) + return TeamInfo(team: team, players: players) + } + .subscribe(onNext: { teamInfo: TeamInfo? in + ... + }) + +// GRDB 3: Track a team and its players +struct TeamInfoRequest: DatabaseRegionConvertible { ... } +let request = TeamInfoRequest(teamId: 1) +dbQueue.rx + .fetch(from: [request]) { try request.fetchOne($0) } + .subscribe(onNext: { teamInfo: TeamInfo? in + ... + }) +``` + + +## Notable Documentation Updates + +If you have time, you may dig deeper in GRDB 3 with those updated documentation chapter: + +- [Database Queues](../README.md#database-queues): focus on the new `read` and `write` methods. +- [Transactions and Savepoints](../README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature. +- [ScopeAdapter](../README.md#scopeadapter): do you use row adapters? If so, have a look. +- [Examples of Record Definitions](../README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass). +- [SQL Operators](../README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`. +- [Custom Requests](../README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter. +- [Migrations](../README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests). + + +[How To Upgrade]: #how-to-upgrade +[Database Schema Recommendations]: #database-schema-recommendations +[Record Protocols Renaming]: #record-protocols-renaming +[Columns Definition]: #columns-definition +[Swift 4.1 Required]: #swift-41-required +[iOS 8 Sunsetting]: #ios-8-sunsetting +[If You Use Database Queues]: #if-you-use-database-queues +[If You Use Database Pools]: #if-you-use-database-pools +[If You Use Database Snapshots]: #if-you-use-database-snapshots +[If You Use Record Types]: #if-you-use-record-types +[If You Use Custom Requests]: #if-you-use-custom-requests +[If You Use RxGRDB]: #if-you-use-rxgrdb +[Notable Documentation Updates]: #notable-documentation-updates +[FetchedRecordsController]: ../README.md#fetchedrecordscontroller +[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB +[Associations]: AssociationsBasics.md +[DatabaseMigrator]: ../README.md#migrations +[database observation tools]: ../README.md#database-changes-observation +[Transactions and Savepoints]: ../README.md#transactions-and-savepoints +[precise transaction handling]: ../README.md#transactions-and-savepoints +[DatabaseQueue]: ../README.md#database-queues +[DatabasePool]: ../README.md#database-pools +[database snapshots]: ../README.md#database-snapshots +[FMDB]: http://github.com/ccgus/fmdb +[record protocols]: ../README.md#record-protocols-overview +[Custom requests]: ../README.md#custom-requests +[query interface]: ../README.md#the-query-interface +[DatabaseRegionConvertible]: https://github.com/groue/RxGRDB/blob/GRDB3/README.md#databaseregionconvertible-protocol +[conditional conformances]: https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md new file mode 100644 index 000000000..65a0838c5 --- /dev/null +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -0,0 +1,326 @@ +Good Practices for Designing Record Types +========================================= + +This guide aims at helping you leverage the best of GRDB [records] and [associations]. + +Since GRDB sits right between low-level libraries like SQLite itself or [FMDB], and high-level ORM like [Core Data] or [Realm], you may face questions when designing the model layer of your application. + +To support this guide, we'll design a simply library application that lets the user crawl through books and their authors. + +- [Trust SQLite More Than Yourself] +- [Record Types are Responsible for Their Tables] +- [Compose Records] +- [Fetch In Time] +- [Observe the Database and Refetch when Needed] + + +## Trust SQLite More Than Yourself + +SQLite is a robust database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk. + +This is important because we developers write bugs, and some of them will ship in the wild, affecting your application users. But thanks to SQLite, those bugs will be unable to corrupt your precious users' data. All it takes a robust **database schema**. + +For example, if we were to define a [migration] that sets up our library database, made of books and their authors, we could write: + +```swift +var migrator = DatabaseMigrator() + +migrator.registerMigration("createLibrary") { db in + try db.create(table: "author") { t in // (1) + t.autoIncrementedPrimaryKey("id") // (2) + t.column("name", .text).notNull() // (3) + } + + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("title", .text) // (4) + t.column("authorId", .integer) // (5) + .notNull() // (6) + .indexed() // (7) + .references("author", onDelete: .cascade) // (8) + } +} + +try migrator.migrate(dbQueue) +``` + +1. Our database table names follow the GRDB 3 recommendation: generally speaking they should be singular, and camel-cased. Make them look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`. +2. Each author has a unique id. +3. An author must have a name. +4. A book must have a title. +5. The `book.authorId` column is used to link a book to the author it belongs to. +6. The `book.authorId` column is not null so that SQLite guarantees that all books have an author. +7. The `book.authorId` column is indexed in order to ease the selection of an author's books. +8. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, 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. + +Thanks to this database schema, you can be confident so no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc. + +> :bulb: **Tip**: Don't look at your local SQLite database as you look at the JSON you load from a remote server. You can't control the JSON, its format and content: your application must defend itself against wacky servers. But you can control the database. Put the database on your side, make it trustable. Learn about relational databases, and how they can help you guarantee the quality of your application data. Put as much energy as you can in the proper definition of your database schema. +> +> :bulb: **Tip**: Plan early for future versions of your application, and use [migrations]. +> +> :bulb: **Tip**: In the definition of your migrations, define tables and their columns with **strings**: +> +> ```swift +> migrator.registerMigration("createLibrary") { db in +> // RECOMMENDED +> try db.create(table: "author") { t in +> t.autoIncrementedPrimaryKey("id") +> ... +> } +> +> // NOT RECOMMENDED +> try db.create(table: Author.databaseTableName) { t in +> t.autoIncrementedPrimaryKey(Author.Columns.id.name) +> ... +> } +> } +> ``` +> +> By using strings, you make sure that you will not have to change the Swift code of your migrations in the future. Even if author columns eventually change. Even if the Author type eventually gets replaced with another type. Even when your startup eventually pivots and starts selling pet food. A good migration that never changes is easy to test once and for good. A good migration that never changes will run smoothly on all devices in the wild, even if a user upgrades straight from version 1.0 to version 5.0 of your application. +> +> So make sure that migrations don't use application types and values: migrations should talk to the database, only to the database, and use the database language: **strings**. + + +## Record Types are Responsible for Their Tables + +Define one record type per database table. + +In this sample code, we'll use codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records. + +```swift +struct Author: Codable, FetchableRecord, MutablePersistableRecord { + var id: Int64? + var name: String + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} + +struct Book: Codable, FetchableRecord, MutablePersistableRecord { + var id: Int64? + var authorId: Int64 + var title: String + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} +``` + +That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`. See [record protocols] for more information. + +> :bulb: **Tip**: When a column of a database table can't be NULL, store it in a non-optional property of your record type. On the other side, when the database may contain NULL, define an optional property. +> +> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(with:for:)` method: +> +> ```swift +> var author = Author(id: nil, name: "Hermann Melville") +> try author.insert(db) +> print(author.id) // Some non-nil id +> ``` + +Since `Author` and `Book` can insert, update, and delete rows in the `author` and `book` database tables, they are *responsible for modifying those database tables*. + +Applying the **[Single Responsibility Principle]** has a consequence: don't even try to have an author responsible for its books. Don't add a `books: [Book]` property in Author. Don't let Author write in the `book` table. When a new fellow coworker joins your team and asks you "who is saving books in the database?", you don't want to answer "it depends." You want to confidently answer: "the Book type". + +> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table. + + +## Compose Records + +Now that we have two types for authors and books, we'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author. + +GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations, along with their companion properties: + +```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) + } +} +``` + +Thanks to this setup, you can fetch associated records: + +```swift +// Fetch an author and its books +struct AuthorInfo { + var author: Author + var books: [Book] +} +let authorInfo: AuthorInfo? = try dbQueue.read { db in + guard let author = try Author.fetchOne(db, key: 123) else { return nil } + let books = try author.books.fetchAll(db) + return AuthorInfo(author: author, books: books) +} + +// Fetch all authorships +struct Authorship: Decodable, FetchableRecord { + var book: Book + var author: Author +} +let authorships: [Authorship] = try dbQueue.read { db in + let request = Book.including(required: Book.author) + return try Authorship.fetchAll(db, request) +} +``` + +The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they? + +That is because other ORMs perform lazy loading: + +```ruby +# Ruby's Active Record +author = Author.find(123) # fetch author +books = author.books # lazily fetches books on demand +``` + +GRDB does not perform lazy loading. Lazy loading either requires record to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer. This is why GRDB has removed lazy loading from the list of desirable features. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information. + +The consequence is that each part of your application will load the data it needs, at the moment it needs it, as below: + +1. Prepare the application screen that lists all authors: + + ```swift + let authors: [Author] = dbQueue.read { db in + Author.order(Colum("name")).fetchAll(db) + } + ``` + +2. Prepare the application screen that displays an author and her books: + + ```swift + struct AuthorInfo { + var author: Author + var books: [Book] + } + let authorId = 123 + let authorInfo: AuthorInfo? = dbQueue.read { db in + guard let author = try Author.fetchOne(db, key: authorId) else { return nil } + let books = try author.books.order(Column("publishDate").desc).fetchAll(db) + return AuthorInfo(author: author, books: books) + } + ``` + +3. Prepare the application screen that displays a book information: + + ```swift + struct BookInfo { + var book: Book + var author: Author + } + let bookId = 123 + let bookInfo: BookInfo? = dbQueue.read { db in + guard let book = try Book.fetchOne(db, key: bookId) else { return nil } + let author = try book.author.fetchOne(db)! + return BookInfo(book: book, author: author) + } + ``` + +> :bulb: **Tip**: Identify the various **graph of objects** needed by the various parts of your application. Design them independently, by composing the basic record types. Fetch the data your application needs, at the moment it needs it, no more, no less. + + +## Fetch In Time + +> :bulb: **Tip**: Make sure you fetch all the data your application needs in a **single database read**. + +```swift +// RECOMMENDED +let bookId = 123 +let bookInfo: BookInfo? = try dbQueue.read { db in + guard let book = try Book.fetchOne(db, key: bookId) else { return nil } + let author = try book.author.fetchOne(db)! + return BookInfo(book: book, author: author) +} +if let bookInfo = bookInfo { + // use bookInfo +} + +// NOT RECOMMENDED +let bookId = 123 +if let book = databaseManager.getBook(id: bookId) { + let author = databaseManager.getAuthor(id: book.authorId)! + // use book and author +} +``` + +This tip is paramount, and deserves an explanation: when you do not fetch your data in a single database read, other threads of your application may modify the database in the background, and have you fetch inconsistent data. This leads to hard-to-reproduce bugs, from funny values on screen to data loss. + +Wrapping all fetches in a `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony: + +```ruby +# Ruby's Active Record +if book = Book.find(123) # fetch book + author = book.author # fetch author + # use book and author +end +``` + +The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests. + +This isolation can be achieved with record management, as in [Core Data] or [Realm], that target with long-running multi-threaded applications. Most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others. + +GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. Unlike web-oriented ORMs, though, GRDB can't provide *implicit* isolation: the application must decide when it wants to safely read information in the database, and this decision is made *explicit* with the `read` GRDB method. + +Do not overlook this advice, or your application will exhibit weird concurrency-related bugs. Read the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale. + + +## Observe the Database and Refetch when Needed + +We have seen above that the Author and Book record types are [responsible](#record-types-are-responsible-for-their-tables) for their own dedicated database tables. Later we [composed](#compose-records) them into more complex types such as `BookInfo` or `AuthorInfo`. We advised the application to fetch database information [right on time](#fetch-in-time), when it needs to process it. + +Fetched information eventually becomes obsoleted, as the application modifies the database content. + +It is up to the application to decide how long it should keep fetched information in memory. Very often though, the application will want to keep memory information synchronized with the database content. + +This synchronization is not automatic with GRDB: records do not "auto-update". That is because applications do not always want this feature, and because it is difficult to write correct multi-threaded applications when values can change in unexpected ways. + +Instead, have a look at [Database Observation]: + +> :bulb: **Tip**: Use [FetchedRecordsController] when a table or collection views should remained synchronized with the database, in an animated way. +> +> :bulb: **Tip**: Use [RxGRDB] when your application needs to react to all changes in the results of a database request. +> +> :bulb: **Tip**: Use [TransactionObserver], the low-level protocol for database observation, for your most advanced needs. +> +> :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones. + + +[records]: ../README.md#records +[associations]: AssociationsBasics.md +[FMDB]: https://github.com/ccgus/fmdb +[Core Data]: https://developer.apple.com/documentation/coredata +[Realm]: https://realm.io +[Active Record]: http://guides.rubyonrails.org/active_record_basics.html +[Django]: https://docs.djangoproject.com/en/2.0/topics/db/ +[record protocols]: ../README.md#record-protocols-overview +[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns +[Single Responsibility Principle]: https://en.wikipedia.org/wiki/Single_responsibility_principle +[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth +[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule +[Why Adopt GRDB?]: WhyAdoptGRDB.md +[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems) +[migrations]: ../README.md#migrations +[migration]: ../README.md#migrations +[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions +[Concurrency Guide]: ../README.md#concurrency +[PersistableRecord]: ../README.md#persistablerecord-protocol +[Database Observation]: ../README.md#database-changes-observation +[FetchedRecordsController]: ../README.md#fetchedrecordscontroller +[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB +[TransactionObserver]: ../README.md#transactionobserver-protocol +[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself +[Record Types are Responsible for Their Tables]: #record-types-are-responsible-for-their-tables +[Compose Records]: #compose-records +[Fetch In Time]: #fetch-in-time +[Observe the Database and Refetch when Needed]: #observe-the-database-and-refetch-when-needed 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/Documentation/README.md b/Documentation/README.md index dff0e9633..b29c23d5f 100644 --- a/Documentation/README.md +++ b/Documentation/README.md @@ -1 +1 @@ -The main documentation is available in [README.md](../../../#documentation). +The main documentation is available in [README.md](../README.md#documentation). diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 5521063f4..6bf9019c7 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -10,7 +10,7 @@ We'll start with a few [core principles](#core-principles), so that you see wher ### It is generally easier to access a database through "record types". -This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow[nameColumn]`, doesn't it? +This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow["name"]`, doesn't it? The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that comes with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause. @@ -37,9 +37,9 @@ GRDB puts all bets on SQLite, and focuses on front-end GUI applications. This means that dealing with servers, MySQL, or PostgreSQL is out of scope. GRDB is not an alternative to IBM's [Swift-Kuery], Vapor's [Fluent], or Perfect's [StORM]. -Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, changes tracking, database observation, multi-threading safety, table view animations, support for reactive streams... +Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, record comparison, database observation, multi-threading safety, table view animations, support for reactive streams... -Some will call GRDB "opinionated", or "bloated". Well, the bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face. +The bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face. Since you don't have to take my words for granted, we'll now see how GRDB actually solves common problems that developers face with other database libraries. @@ -51,7 +51,7 @@ What is the purpose of the above principles, if not providing solutions to diffi ### Allow any Swift struct or class to become a database record -Most libraries that provide record types want you to subclass a root class: NSManagedObject, Realm.Object, FCModel. +Most libraries that provide record types want you to subclass a root class: [NSManagedObject](https://developer.apple.com/documentation/coredata/nsmanagedobject), [Realm.Object](https://www.realm.io/docs/swift/latest), [FCModel](https://github.com/marcoarment/FCModel). The main problem with those root classes is that they are classes. You can't define records from plain Swift structs, and leverage all advantages of Swift value types: immutability, multi-threading safety, etc. @@ -65,28 +65,28 @@ struct Place { } ``` -By adopting the [RowConvertible] protocol, places can be loaded from SQL requests: +By adopting the [FetchableRecord] protocol, places can be loaded from SQL requests: ```swift -extension Place: RowConvertible { ... } -let places = try Place.fetchAll(db, "SELECT * FROM places") // [Place] +extension Place: FetchableRecord { ... } +let places = try Place.fetchAll(db, "SELECT * FROM place") // [Place] ``` -Add the [TableMapping] protocol, and SQL requests are generated for you: +Add the [TableRecord] protocol, and SQL requests are generated for you: ```swift -extension Place: TableMapping { ... } +extension Place: TableRecord { ... } let place = try Place.fetchOne(db, key: 1) // Place? ``` -Add the [Persistable] protocol, and places know how to insert, update and delete themselves: +Add the [PersistableRecord] protocol, and places know how to insert, update and delete themselves: ```swift -extension Place: Persistable { ... } +extension Place: PersistableRecord { ... } try place.delete(db) ``` -Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with database change notifications, with many advantages. +Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages. ### Allow database records to cross threads @@ -129,16 +129,16 @@ First, notifications only come from database changes safely saved on disk. This Next, you choose the dispatch queue on which notifications happen. It can be on the special "writer queue", which allows you to process changes before any other thread has any opportunity to perform further database modifications. But notifications can also happen on the queue of your choice (generally the main queue, by default, as in the example above). Of course, GRDB makes sure notifications happen in the same order as database transactions. -Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers. +Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported. ### Non-blocking database reads -GRDB ships with two ways to access databases, [database queues](https://github.com/groue/GRDB.swift/blob/master/README.md#database-queues) and [pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools). +GRDB ships with two ways to access databases, [database queues](../README.md#database-queues) and [pools](../README.md#database-pools). Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen. -[Database pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured). +[Database pools](../README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured). ### Strong and clear multi-threading guarantees @@ -162,9 +162,9 @@ The more threats are handled by the application, the more skilled and careful a | GRDB's DatabaseQueue | :white_check_mark: | :white_check_mark: | Handled by the application | UI is blocked | | GRDB's DatabasePool | :white_check_mark: | :white_check_mark: | Handled by the application | :white_check_mark: (as long as the maximum number of readers has not been reached) | -I had to omit Realm and FCModel from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue. +I had to omit [Realm] and [FCModel] from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue. -We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to use or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way. A weaker way to say this is that conflict handling at the library level can wait :sweat_smile:. +We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to plan, use, or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way. Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and you'd better be a very skilled developer in order to use them properly. @@ -175,79 +175,89 @@ For further information about GRDB concurrency, check its detailed [Concurrency SQL is a weird language. Born in the 70s, easy to [misuse](https://xkcd.com/327/), feared by some developers, despised by others, and yet wonderfully concise and powerful. -GRDB provides high-level record methods that generate SQL for you: +GRDB [query interface] and [associations] can generate SQL for you: ```swift -// SELECT * FROM players ORDER BY score DESC LIMIT 10 +// SELECT * FROM player ORDER BY score DESC LIMIT 10 let bestPlayers: [Player] = try Player .order(scoreColumn.desc) .limit(10) .fetchAll(db) -// SELECT MAX(score) FROM players +// SELECT MAX(score) FROM player let maximumScore: Int? = try Player .select(max(scoreColumn)) .asRequestOf(Int.self) .fetchOne(db) - -// SELECT COUNT(*) FROM players WHERE score = ? -let exAequoCount: Int = try Player - .filter(scoreColumn == maximumScore) - .fetchCount(db) + +// SELECT book.*, author.* +// FROM book +// LEFT JOIN author ON author.id = book.authorId +let request = Book.including(optional: Book.author) +let bookInfos: [BookInfo] = BookInfo.fetchAll(db, request) ``` -But you can *always* switch to SQL when you want to: +But you can always switch to SQL when you want to: ```swift let bestPlayers: [Player] = try Player.fetchAll(db, """ - SELECT * FROM players ORDER BY score DESC LIMIT 10 + SELECT * FROM player ORDER BY score DESC LIMIT 10 """) let maximumScore: Int? = try Int.fetchOne(db, """ - SELECT MAX(score) FROM players + SELECT MAX(score) FROM player """) - -let exAequoCount: Int? = try Int.fetchOne(db, """ - SELECT COUNT(*) FROM players WHERE score = ? - """, arguments: [maximumScore]) ``` -SQL is also welcome in high-level database observation tools like [FetchedRecordsController] and [RxGRDB]: +Power users can also consume complex joined SQL queries into handy record values, by *adapting* raw database rows to the decoded records (see [Joined Queries Support](#../README.md#joined-queries-support)): ```swift -SQLRequest("SELECT * FROM players ORDER BY score DESC LIMIT 10") - .asRequest(of: Player.self) - .rx - .fetchAll(in: dbQueue) - .subscribe(onNext: { players: [Player] in - print("Best 10 players have changed") - }) +let bookInfos: [BookInfo] = SQLRequest(""" + SELECT book.*, author.* + FROM book + LEFT JOIN author ON author.id = book.authorId + """) + .adapted { db in + let adapters = try splittingRowAdapters(columnCounts: [ + db.columns(in: "book").count, + db.columns(in: "author").count]) + return ScopeAdapter([ + "book": adapters[0], + "author": adapters[1]]) + } ``` -You can of course deal with raw database rows, and fetch [lazy cursors](https://github.com/groue/GRDB.swift/blob/master/README.md#cursors) instead of arrays: +In performance-critical sections, you may want to deal with raw database rows, and fetch [lazy cursors](../README.md#cursors) instead of arrays: ```swift -let rows = try Row.fetchCursor(db, "SELECT * FROM players") +let rows = try Row.fetchCursor(db, "SELECT id, name, score FROM player") while let row = try rows.next() { - let id: Int64 = row["id"] - let name: String = row["name"] - let score: Int = row["score"] + let id: Int64 = row[0] + let name: String = row[1] + let score: Int = row[2] } ``` -When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](https://github.com/groue/GRDB.swift/blob/master/README.md#custom-requests): +When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](../README.md#custom-requests): ```swift extension Player { - static func customRequest(...) -> AnyTypedRequest { - return SQLRequest(""" - SELECT ... - """, arguments: ...) - .asRequestOf(Player.self) + static func customRequest(...) -> SQLRequest { + return SQLRequest("SELECT ...", arguments: ...) } } -let players = Player.customRequest(...).fetchAll(db) +let players = try Player.customRequest(...).fetchAll(db) +``` + +Those custom requests are welcome in database observation tools like [FetchedRecordsController] and [RxGRDB]: + +```swift +Player.customRequest(...).rx + .fetchAll(in: dbQueue) + .subscribe(onNext: { players: [Player] in + print("Players have changed") + }) ``` --- @@ -258,23 +268,25 @@ And if you happen to maintain an Objective-C application that uses FMDB, checkou Happy GRDB! :gift: -[Concurrency Guide]: https://github.com/groue/GRDB.swift/blob/master/README.md#concurrency +[Concurrency Guide]: ../README.md#concurrency [Core Data]: https://developer.apple.com/documentation/coredata -[DatabasePool]: https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools +[DatabasePool]: ../README.md#database-pools [Diesel]: http://diesel.rs [FCModel]: https://github.com/marcoarment/FCModel -[FetchedRecordsController]: https://github.com/groue/GRDB.swift/blob/master/README.md#fetchedrecordscontroller +[FetchedRecordsController]: ../README.md#fetchedrecordscontroller [Fluent]: https://github.com/vapor/fluent [FMDB]: http://github.com/ccgus/fmdb [GRDB]: http://github.com/groue/GRDB.swift [GRDBObjc]: http://github.com/groue/GRDBObjc -[Persistable]: https://github.com/groue/GRDB.swift/blob/master/README.md#records +[PersistableRecord]: ../README.md#records [Realm]: http://realm.io -[RowConvertible]: https://github.com/groue/GRDB.swift/blob/master/README.md#records +[FetchableRecord]: ../README.md#records [RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB [RxSwift]: https://github.com/ReactiveX/RxSwift [SQLite.swift]: http://github.com/stephencelis/SQLite.swift [StORM]: https://www.perfect.org/docs/StORM.html [Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery -[TableMapping]: https://github.com/groue/GRDB.swift/blob/master/README.md#records -[TransactionObserver]: https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol +[TableRecord]: ../README.md#records +[TransactionObserver]: ../README.md#transactionobserver-protocol +[query interface]: ../README.md#the-query-interface +[associations]: AssociationsBasics.md diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index ec712b7d5..aad819f0e 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -3,7 +3,7 @@ Pod::Spec.new do |s| s.version = '2.10.0' s.license = { :type => 'MIT', :file => 'LICENSE' } - s.summary = 'A Swift application toolkit for SQLite databases.' + s.summary = 'A toolkit for SQLite databases, with a focus on application development.' s.homepage = 'https://github.com/groue/GRDB.swift' s.author = { 'Gwendal Roué' => 'gr@pierlis.com' } s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" } diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 9f31314c6..4ee666f45 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -27,8 +27,8 @@ 5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; }; 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; 5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - 5605F1931C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; - 5605F1941C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + 5605F1931C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; + 5605F1941C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 56071A411DB54ED000CA6E47 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; @@ -45,11 +45,14 @@ 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; }; 560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; - 560D92471C672C4B00F4F92B /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; - 560D92481C672C4B00F4F92B /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; - 560D924B1C672C4B00F4F92B /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; - 560D924C1C672C4B00F4F92B /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; + 560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; + 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; + 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; + 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 561667051D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; + 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; + 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; + 5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; 56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD001DAA8ACA0056AF8C /* FTS5CustomTokenizerTests.swift */; }; 56176C5A1EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C01DA521450002DA19 /* FTS5PatternTests.swift */; }; 56176C5B1EACCCC7000F3F2B /* FTS5RecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C11DA521450002DA19 /* FTS5RecordTests.swift */; }; @@ -76,8 +79,6 @@ 5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; }; 562393301DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; 562393341DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; - 562393451DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; - 562393491DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; 562393521DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; 562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393561DEE013C00A6B01F /* FilterCursorTests.swift */; }; @@ -97,14 +98,14 @@ 562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 562EA8331F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; - 56300B621C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + 56300B621C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 56300B691C53D25E005A543B /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; - 56300B6C1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + 56300B6C1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; - 563363B01C933FF8000BE133 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - 563363B21C933FF8000BE133 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + 563363B01C933FF8000BE133 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + 563363B21C933FF8000BE133 /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; 563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; }; 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; }; 563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; }; @@ -113,8 +114,8 @@ 563363D11C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; }; 563363D61C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; }; 5634B10A1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; }; - 5636E9BC1D22574100B9B05F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; - 5636E9BF1D22574100B9B05F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; + 5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; + 5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 56439B331F4CA1DC0066043F /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86191BA988F2001F9168 /* FMDatabase.m */; }; 56439B341F4CA1DC0066043F /* InsertRecordClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86121BA9886D001F9168 /* InsertRecordClassTests.swift */; }; 56439B351F4CA1DC0066043F /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 56BB861B1BA988F2001F9168 /* FMDatabaseAdditions.m */; }; @@ -147,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 */; }; @@ -159,7 +218,7 @@ 565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238751B9C75030082EB20 /* DatabaseValue.swift */; }; 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; }; 565490C01D5AE236005622CB /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C31C942C37000BE133 /* DatabaseWriter.swift */; }; - 565490C11D5AE236005622CB /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; + 565490C11D5AE236005622CB /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 565490C21D5AE236005622CB /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; }; 565490C31D5AE236005622CB /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; }; 565490C41D5AE236005622CB /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; }; @@ -182,14 +241,17 @@ 565490D91D5AE252005622CB /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - 565490DE1D5AE252005622CB /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + 565490DE1D5AE252005622CB /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; - 565490E11D5AE252005622CB /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; + 565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; 565490E21D5AE252005622CB /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; - 565490E41D5AE252005622CB /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; + 565490E41D5AE252005622CB /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; 56553C131C3E906C00522B5C /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC3773F319C8CBB3004FCF85 /* GRDB.framework */; }; + 5656BF4F20C723E300F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF4E20C723E300F98521 /* QueryOrdering.swift */; }; + 5656BF5020C723E300F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF4E20C723E300F98521 /* QueryOrdering.swift */; }; + 5656BF5120C723E300F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF4E20C723E300F98521 /* QueryOrdering.swift */; }; 5657AAB91D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABC1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB0F1D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -213,7 +275,7 @@ 5659F4A01EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; 5659F4A31EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; 5659F4A61EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; - 565B0FF01BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + 565B0FF01BBC7D980098DE03 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; 565D5D721BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */; }; 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; 565EFAF21D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */; }; @@ -239,8 +301,8 @@ 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; }; 566A8425204120B700E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */; }; 566A8426204120B700E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */; }; - 566A84402041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutablePersistableChangesTests.swift */; }; - 566A84412041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutablePersistableChangesTests.swift */; }; + 566A84402041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */; }; + 566A84412041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */; }; 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8CA1D531BEC002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; }; @@ -268,20 +330,20 @@ 5672DE6A1CDB751D0022BA81 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */; }; 567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; }; 5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; }; - 56741EA81E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; - 56741EAC1E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; + 56741EA81E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; + 56741EAC1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; 5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6E81F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6E91F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6F01F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; - 5674A6F41F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6F81F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6F91F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6FB1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; - 5674A6FF1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; - 5674A7001F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; + 5674A6F41F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6F81F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6F91F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6FB1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; + 5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; + 5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A7081F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; @@ -289,13 +351,10 @@ 5674A7121F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */; }; 5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A71A1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; - 5674A7201F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A7231F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A72A1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; - 5674A72D1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; - 567517C820131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; }; - 567517C920131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; }; - 567517CA20131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; }; + 5674A7201F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A7231F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5674A72D1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; 567DAF1F1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; @@ -304,8 +363,6 @@ 567DAF391EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; 567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; - 56805210201320E600E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680520F201320E600E87861 /* RecordBoxTests.swift */; }; - 56805211201320E600E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680520F201320E600E87861 /* RecordBoxTests.swift */; }; 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568735A21CEDE16C009B9116 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 5687359E1CEDE16C009B9116 /* Betty.jpeg */; }; @@ -365,6 +422,9 @@ 5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 5698AD3B1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; + 569A98ED2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98EC2039B6F3008D7DBF /* Fixits-3.0.swift */; }; + 569A98EE2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98EC2039B6F3008D7DBF /* Fixits-3.0.swift */; }; + 569A98EF2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98EC2039B6F3008D7DBF /* Fixits-3.0.swift */; }; 569C1EB51CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; 569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; }; 569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; }; @@ -420,13 +480,12 @@ 56A8C2471D1918F00096E9D4 /* FoundationNSUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */; }; 56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C21E1D1914110096E9D4 /* FoundationUUIDTests.swift */; }; 56AF746F1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; - 56B021C91D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; - 56B021CD1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; + 56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; + 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 */; }; 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; @@ -459,9 +518,9 @@ 56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */; }; 56CC9251201E093F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */; }; 56CC9252201E093F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */; }; - 56CEB4F11EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; - 56CEB4F41EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; - 56CEB4F71EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; + 56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; + 56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; + 56CEB4F71EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; 56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; @@ -513,10 +572,10 @@ 56D496651D813076008276D7 /* DatabaseMigratorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238241B9C74A90082EB20 /* DatabaseMigratorTests.swift */; }; 56D496661D813086008276D7 /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; 56D496671D813086008276D7 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; - 56D496681D813086008276D7 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + 56D496681D813086008276D7 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; - 56D4966A1D813086008276D7 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; - 56D4966B1D81309E008276D7 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; + 56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; + 56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238261B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift */; }; 56D4966D1D81309E008276D7 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 56D4966E1D81309E008276D7 /* RecordPrimaryKeyMultipleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238281B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift */; }; @@ -550,10 +609,10 @@ 56D496901D81316E008276D7 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; 56D496911D81316E008276D7 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; 56D496921D81316E008276D7 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; - 56D496931D81316E008276D7 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + 56D496931D81316E008276D7 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; 56D496941D81317B008276D7 /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; - 56D496951D81317B008276D7 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - 56D496961D81317B008276D7 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + 56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; 56D496971D81317B008276D7 /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; 56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; 56D496AB1D8132CA008276D7 /* DatabasePoolFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */; }; @@ -577,9 +636,9 @@ 56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507831F6D7B2E00AE1C5B /* InsertRecordStructTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */; }; 56D507841F6D7B2F00AE1C5B /* InsertRecordStructTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */; }; - 56D51D001EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; - 56D51D031EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; - 56D51D061EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; + 56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; @@ -601,6 +660,8 @@ 56E5D82D1B4D438800430942 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; 56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 56E8CE111BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */; }; + 56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; }; + 56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; }; 56EA86951C91DFE7002BB4DF /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; 56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; @@ -620,9 +681,9 @@ 56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; - 56FEE7FB1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; - 56FEE7FF1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; - 56FF45441D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; + 56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; + 56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; + 56FF45441D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; 56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 6340BF801E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; 6340BF841E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; @@ -760,7 +821,7 @@ 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; - 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceSelectQueryDefinition.swift; sourceTree = ""; }; + 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceQuery.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; @@ -770,13 +831,13 @@ 560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; - 560D92441C672C4B00F4F92B /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = ""; }; - 560D92461C672C4B00F4F92B /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = ""; }; + 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; + 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 560FC5101CAEEDF10014AA8E /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; + 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; - 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IteratorCursorTests.swift; sourceTree = ""; }; 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = ""; }; 562393561DEE013C00A6B01F /* FilterCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FilterCursorTests.swift; sourceTree = ""; }; 5623935F1DEE06D300A6B01F /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = ""; }; @@ -787,13 +848,13 @@ 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = ""; }; 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; - 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExpressionsTests.swift; sourceTree = ""; }; - 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableMapping+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; - 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableTests.swift; sourceTree = ""; }; - 563363AA1C933FF8000BE133 /* PersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableTests.swift; sourceTree = ""; }; + 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordTests.swift; sourceTree = ""; }; + 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecordTests.swift; sourceTree = ""; }; 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueConcurrencyTests.swift; sourceTree = ""; }; 563363BF1C942C04000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = ""; }; 563363C31C942C37000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = ""; }; @@ -801,15 +862,40 @@ 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 563363F81C960711000BE133 /* PerformanceRealmTests.realm */ = {isa = PBXFileReference; lastKnownFileType = file; path = PerformanceRealmTests.realm; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; - 5636E9BB1D22574100B9B05F /* Request.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = ""; }; + 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; 56439B501F4CA1DC0066043F /* GRDBOSXPerformanceComparisonTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceComparisonTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 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; }; + 5656BF4E20C723E300F98521 /* QueryOrdering.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QueryOrdering.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 = ""; }; @@ -823,7 +909,7 @@ 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = ""; }; 5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = ""; }; 5659F49F1EA8D997004A4992 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = ""; }; - 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = ""; }; + 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = ""; }; 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; @@ -836,7 +922,7 @@ 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 566A84192041146100E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; - 566A843F2041914000E50BFD /* MutablePersistableChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableChangesTests.swift; sourceTree = ""; }; + 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = ""; }; 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = ""; }; 566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = ""; }; @@ -851,22 +937,20 @@ 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueBackupTests.swift; sourceTree = ""; }; 5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = ""; }; 567404871CEF84C8003ED5CC /* RowAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowAdapter.swift; sourceTree = ""; }; - 56741EA71E66A8B3003E422D /* RequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestTests.swift; sourceTree = ""; }; + 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; - 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RowConvertible+Decodable.swift"; sourceTree = ""; }; - 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Persistable+Encodable.swift"; sourceTree = ""; }; + 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+Decodable.swift"; sourceTree = ""; }; + 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Encodable.swift"; sourceTree = ""; }; 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = ""; }; 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = ""; }; 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; - 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableEncodableTests.swift; sourceTree = ""; }; - 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowConvertibleDecodableTests.swift; sourceTree = ""; }; - 567517C720131B220094BF41 /* RecordBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordBox.swift; sourceTree = ""; }; + 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = ""; }; + 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; - 5680520F201320E600E87861 /* RecordBoxTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordBoxTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = ""; }; @@ -903,6 +987,7 @@ 5698AD151DAAD16F0056AF8C /* FTS5Tokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5Tokenizer.swift; sourceTree = ""; }; 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 = ""; }; + 569A98EC2039B6F3008D7DBF /* Fixits-3.0.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-3.0.swift"; sourceTree = ""; }; 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = ""; }; 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = ""; }; 56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; @@ -945,10 +1030,10 @@ 56A8C22F1D1914540096E9D4 /* UUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUID.swift; sourceTree = ""; }; 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = ""; }; 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; - 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistablePersistenceConflictPolicyTests.swift; sourceTree = ""; }; + 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 = ""; }; 56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-4.1/Realm.framework"; sourceTree = ""; }; @@ -987,7 +1072,7 @@ 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; - 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; + 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecord.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS3+QueryInterfaceRequest.swift"; sourceTree = ""; }; @@ -1001,7 +1086,7 @@ 56D3BE701F4EB1900034C6D2 /* FetchRecordStructTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchRecordStructTests.swift; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InsertRecordStructTests.swift; sourceTree = ""; }; - 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+TableMapping.swift"; sourceTree = ""; }; + 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; @@ -1019,6 +1104,7 @@ 56E5D7F91B4D422D00430942 /* GRDBOSXTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = ""; }; + 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = ""; }; 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = ""; }; 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = ""; }; 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = ""; }; @@ -1029,8 +1115,8 @@ 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 /* TableMappingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableMappingTests.swift; sourceTree = ""; }; - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableDeleteTests.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 = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; C96C0F242084A442006B2981 /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; @@ -1179,17 +1265,17 @@ name = DatabasePool; sourceTree = ""; }; - 560B3FA41C19DFF800C58EC7 /* Persistable */ = { + 560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = { isa = PBXGroup; children = ( - 566A843F2041914000E50BFD /* MutablePersistableChangesTests.swift */, - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */, - 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */, - 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */, - 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */, - 563363AA1C933FF8000BE133 /* PersistableTests.swift */, + 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */, + 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, + 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, + 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, + 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, + 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, ); - name = Persistable; + name = PersistableRecord; sourceTree = ""; }; 56176C581EACC2D8000F3F2B /* GRDBTests */ = { @@ -1209,12 +1295,12 @@ path = GRDBTests; sourceTree = ""; }; - 56176C9C1EACEA8C000F3F2B /* TableMapping */ = { + 56176C9C1EACEA8C000F3F2B /* TableRecord */ = { isa = PBXGroup; children = ( - 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */, + 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */, ); - name = TableMapping; + name = TableRecord; sourceTree = ""; }; 56176C9E1EACEDF9000F3F2B /* Record */ = { @@ -1267,13 +1353,16 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EABF20944B1300F46237 /* Association */, + 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */, + 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */, + 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, - 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, - 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */, + 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, ); name = QueryInterface; @@ -1282,16 +1371,21 @@ 56300B6D1C53F592005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EAF720944BC900F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, + 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, - 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */, + 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */, + 5656BF4E20C723E300F98521 /* QueryOrdering.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 */, @@ -1316,6 +1410,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 = ( @@ -1336,13 +1466,13 @@ path = Support; sourceTree = ""; }; - 5674A7251F30A8EF0095F066 /* RowConvertible */ = { + 5674A7251F30A8EF0095F066 /* FetchableRecord */ = { isa = PBXGroup; children = ( - 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */, - 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */, + 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */, + 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */, ); - name = RowConvertible; + name = FetchableRecord; sourceTree = ""; }; 569530FA1C9067CC00CF1A2B /* Crash */ = { @@ -1433,11 +1563,11 @@ 56A238191B9C74A90082EB20 /* DatabaseValueConvertible */, 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */, 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */, + 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */, 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */, 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */, 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */, 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */, - 56741EA71E66A8B3003E422D /* RequestTests.swift */, 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */, 56A2381D1B9C74A90082EB20 /* Row */, 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */, @@ -1497,13 +1627,12 @@ 56A238251B9C74A90082EB20 /* Record */ = { isa = PBXGroup; children = ( + 5674A7251F30A8EF0095F066 /* FetchableRecord */, 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73DE203D50B9000C443C /* JoinSupportTests.swift */, - 560B3FA41C19DFF800C58EC7 /* Persistable */, + 560B3FA41C19DFF800C58EC7 /* PersistableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, - 5680520F201320E600E87861 /* RecordBoxTests.swift */, - 5674A7251F30A8EF0095F066 /* RowConvertible */, - 56176C9C1EACEA8C000F3F2B /* TableMapping */, + 56176C9C1EACEA8C000F3F2B /* TableRecord */, ); name = Record; sourceTree = ""; @@ -1528,7 +1657,7 @@ 56A238751B9C75030082EB20 /* DatabaseValue.swift */, 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, - 5636E9BB1D22574100B9B05F /* Request.swift */, + 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, @@ -1554,15 +1683,14 @@ 56A2389F1B9C753B0082EB20 /* Record */ = { isa = PBXGroup; children = ( + 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */, + 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */, + 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, - 560D92441C672C4B00F4F92B /* Persistable.swift */, - 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */, + 560D92441C672C4B00F4F92B /* PersistableRecord.swift */, + 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, - 567517C720131B220094BF41 /* RecordBox.swift */, - 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */, - 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */, - 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */, - 560D92461C672C4B00F4F92B /* TableMapping.swift */, + 560D92461C672C4B00F4F92B /* TableRecord.swift */, ); path = Record; sourceTree = ""; @@ -1624,7 +1752,7 @@ 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */, 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, - 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */, + 569A98EC2039B6F3008D7DBF /* Fixits-3.0.swift */, ); path = Legacy; sourceTree = ""; @@ -1654,7 +1782,6 @@ 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */, 562393561DEE013C00A6B01F /* FilterCursorTests.swift */, 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */, - 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */, 562393711DEE104400A6B01F /* MapCursorTests.swift */, 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */, 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */, @@ -2176,18 +2303,22 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 569A98EF2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, + 5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 56D51D061EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */, + 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, - 565490E41D5AE252005622CB /* TableMapping.swift in Sources */, + 565490E41D5AE252005622CB /* TableRecord.swift in Sources */, 565490CF1D5AE252005622CB /* NSNumber.swift in Sources */, 566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 565490E21D5AE252005622CB /* Record.swift in Sources */, - 565490C11D5AE236005622CB /* Request.swift in Sources */, + 5656BF5120C723E300F98521 /* QueryOrdering.swift in Sources */, + 565490C11D5AE236005622CB /* FetchRequest.swift in Sources */, 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 */, @@ -2195,6 +2326,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 */, @@ -2204,26 +2336,29 @@ 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 */, 56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */, - 5674A6FF1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, + 5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 56E06F181E85906E008AE2A4 /* Fixits-0.102.0.swift in Sources */, 56B964A31DA51B4C0002DA19 /* FTS5.swift in Sources */, 566475A01D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 565490BB1D5AE236005622CB /* DatabaseReader.swift in Sources */, 5659F4A61EA8D997004A4992 /* Result.swift in Sources */, - 5674A6F81F307F600095F066 /* Persistable+Encodable.swift in Sources */, + 5674A6F81F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 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 */, @@ -2232,6 +2367,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 */, @@ -2240,18 +2376,18 @@ 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 */, - 567517CA20131B220094BF41 /* RecordBox.swift in Sources */, 5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 565490C61D5AE236005622CB /* Statement.swift in Sources */, 56CEB5071EAA2F4D00BFAF62 /* FTS4.swift in Sources */, - 56CEB4F71EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */, + 56CEB4F71EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56F5ABD91D814330001F60CB /* Data.swift in Sources */, 565490D41D5AE252005622CB /* (null) in Sources */, 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 565490B61D5AE236005622CB /* Configuration.swift in Sources */, - 565490E11D5AE252005622CB /* Persistable.swift in Sources */, + 565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */, 56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */, 566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -2261,17 +2397,19 @@ 565490D31D5AE252005622CB /* (null) in Sources */, 566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 566B910F1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, - 565490DE1D5AE252005622CB /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + 565490DE1D5AE252005622CB /* QueryInterfaceQuery.swift in Sources */, 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; @@ -2297,24 +2435,28 @@ buildActionMask = 2147483647; files = ( 56BF6D401DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, - 5636E9BF1D22574100B9B05F /* Request.swift in Sources */, + 5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */, - 5674A6F91F307F600095F066 /* Persistable+Encodable.swift in Sources */, + 5674A6F91F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 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 */, 5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, @@ -2322,6 +2464,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 */, @@ -2332,13 +2475,16 @@ 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 /* RowConvertible+TableMapping.swift in Sources */, - 560D924C1C672C4B00F4F92B /* TableMapping.swift in Sources */, - 567517C920131B220094BF41 /* RecordBox.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 */, 56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */, 56DAA2DE1DE9C827006E10C8 /* Cursor.swift in Sources */, @@ -2346,20 +2492,20 @@ 5674A7081F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 56A2388C1B9C75030082EB20 /* Statement.swift in Sources */, 5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */, - 56B1C3CE201C8D0E001938DA /* Swift4.1.swift in Sources */, - 5605F1941C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + 5605F1941C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, 5690C3431D23E82A00E59934 /* Data.swift in Sources */, - 5674A7001F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, + 5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5674A6E91F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56A238881B9C75030082EB20 /* Row.swift in Sources */, - 56CEB4F41EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */, + 56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, 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 */, @@ -2368,15 +2514,18 @@ 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 */, 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, + 5656BF5020C723E300F98521 /* QueryOrdering.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, - 560D92481C672C4B00F4F92B /* Persistable.swift in Sources */, + 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 */, @@ -2399,7 +2548,7 @@ 56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */, 56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */, 56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, - 56FF45441D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, + 56FF45441D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, 56A238561B9C74A90082EB20 /* RecordPrimaryKeyNoneTests.swift in Sources */, 562EA8331F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, 563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -2407,7 +2556,6 @@ 564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 56A238461B9C74A90082EB20 /* RowFromDictionaryTests.swift in Sources */, 569C1EB51CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */, - 56805211201320E600E87861 /* RecordBoxTests.swift in Sources */, 562EA82A1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */, 56E8CE111BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift in Sources */, @@ -2418,21 +2566,22 @@ 56A2384E1B9C74A90082EB20 /* DatabaseMigratorTests.swift in Sources */, 56CC9244201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */, 5657AB4A1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, - 562393491DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 569531351C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */, 56A2385A1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift in Sources */, 56EE573E1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift in Sources */, 562756471E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */, 56A238481B9C74A90082EB20 /* RowCopiedFromStatementTests.swift in Sources */, + 56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */, 5674A71A1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 5698AC071D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 56C3F7561CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, - 56B021CD1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021CD1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 569531271C9087B700CF1A2B /* DatabaseQueueSchemaCacheTests.swift in Sources */, 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 */, @@ -2443,24 +2592,27 @@ 56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */, 56CC9252201E093F00CB597E /* PrefixCursorTests.swift in Sources */, - 563363B01C933FF8000BE133 /* MutablePersistableTests.swift in Sources */, + 563363B01C933FF8000BE133 /* MutablePersistableRecordTests.swift in Sources */, 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 /* RowConvertible+QueryInterfaceRequestTests.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 */, 56176C7F1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */, - 56741EAC1E66A8B3003E422D /* RequestTests.swift in Sources */, + 56741EAC1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 5672DE5C1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */, 56176C6C1EACCCC9000F3F2B /* FTS5PatternTests.swift in Sources */, - 563363B21C933FF8000BE133 /* PersistableTests.swift in Sources */, + 563363B21C933FF8000BE133 /* PersistableRecordTests.swift in Sources */, 56A238421B9C74A90082EB20 /* DatabaseValueConversionTests.swift in Sources */, 564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */, 5674A7121F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -2470,14 +2622,15 @@ 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 */, 5623935B1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, - 5674A72D1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, - 566A84412041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 5674A72D1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, + 566A84412041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, - 56FEE7FF1F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */, 56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */, 56A2383E1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */, 567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */, @@ -2486,22 +2639,28 @@ 5698AC441DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 5698ACBA1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 56176C6F1EACCCC9000F3F2B /* FTS5TokenizerTests.swift in Sources */, - 565B0FF01BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */, + 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 */, @@ -2517,17 +2676,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 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, - 5674A7231F30A8DF0095F066 /* MutablePersistableEncodableTests.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 */, @@ -2555,7 +2718,6 @@ 564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 56D496811D813131008276D7 /* TransactionObserverSavepointsTests.swift in Sources */, 56D496AB1D8132CA008276D7 /* DatabasePoolFunctionTests.swift in Sources */, - 56805210201320E600E87861 /* RecordBoxTests.swift in Sources */, 562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */, 562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, @@ -2569,9 +2731,10 @@ 56D496B11D8133BC008276D7 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */, - 56D4966B1D81309E008276D7 /* MutablePersistableDeleteTests.swift in Sources */, + 56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */, 56D4965B1D81304E008276D7 /* FoundationNSDecimalNumberTests.swift in Sources */, 562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, + 56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */, 56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */, 5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */, @@ -2580,11 +2743,12 @@ 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 */, 5698AC491DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, - 56D496931D81316E008276D7 /* RowConvertibleTests.swift in Sources */, + 56D496931D81316E008276D7 /* FetchableRecordTests.swift in Sources */, 56D496881D81316E008276D7 /* DatabaseValueConversionTests.swift in Sources */, 56D496BA1D813482008276D7 /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */, @@ -2594,17 +2758,20 @@ 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 */, 5698ACD71DA925420056AF8C /* RowTestCase.swift in Sources */, 56176C7D1EACCD2D000F3F2B /* EncryptionTests.swift in Sources */, - 56741EA81E66A8B3003E422D /* RequestTests.swift in Sources */, + 56741EA81E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56D496831D813147008276D7 /* DatabaseSavepointTests.swift in Sources */, 56D496871D81316E008276D7 /* DatabaseTimestampTests.swift in Sources */, 56176C5A1EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */, @@ -2617,15 +2784,16 @@ 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 */, - 56D496961D81317B008276D7 /* PersistableTests.swift in Sources */, + 56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */, 5698AC9E1DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, - 5674A72A1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, - 566A84402041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, + 566A84402041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, - 56FEE7FB1F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */, 56D496641D81304E008276D7 /* FoundationUUIDTests.swift in Sources */, 56D496921D81316E008276D7 /* RowFromDictionaryLiteralTests.swift in Sources */, 562206081E420EA4005860AC /* DatabasePoolReadOnlyTests.swift in Sources */, @@ -2636,22 +2804,28 @@ 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 /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */, 562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */, 56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */, @@ -2659,23 +2833,26 @@ 5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, 56E5D8041B4D424400430942 /* GRDBTestCase.swift in Sources */, 567DAF351EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, - 56D496681D813086008276D7 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, - 562393451DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, + 56D496681D813086008276D7 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, - 56D496951D81317B008276D7 /* MutablePersistableTests.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 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A7201F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */, - 56D4966A1D813086008276D7 /* TableMapping+QueryInterfaceRequestTests.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 */, @@ -2693,7 +2870,8 @@ files = ( 56873BEC1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D3D1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, - 5636E9BC1D22574100B9B05F /* Request.swift in Sources */, + 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */, + 5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */, @@ -2701,7 +2879,7 @@ 5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, - 56CEB4F11EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */, + 56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -2721,16 +2899,18 @@ 5698AC371D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */, 5659F4981EA8D989004A4992 /* Pool.swift in Sources */, - 5674A6F41F307F600095F066 /* Persistable+Encodable.swift in Sources */, + 5674A6F41F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 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 */, @@ -2738,22 +2918,23 @@ 56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D2F1DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */, - 56D51D001EA789FA0074638A /* RowConvertible+TableMapping.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 */, + 5656BF4F20C723E300F98521 /* QueryOrdering.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, 56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */, 5657AB0F1D10899D006283EF /* URL.swift in Sources */, - 560D924B1C672C4B00F4F92B /* TableMapping.swift in Sources */, + 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */, 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */, 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */, - 5605F1931C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + 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 */, @@ -2761,25 +2942,32 @@ 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 */, - 5674A6FB1F307F600095F066 /* RowConvertible+Decodable.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 */, 5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, + 569A98ED2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 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 */, - 567517C820131B220094BF41 /* RecordBox.swift in Sources */, - 560D92471C672C4B00F4F92B /* Persistable.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.xcworkspace/contents.xcworkspacedata b/GRDB.xcworkspace/contents.xcworkspacedata index d547997e4..3a81d3df3 100644 --- a/GRDB.xcworkspace/contents.xcworkspacedata +++ b/GRDB.xcworkspace/contents.xcworkspacedata @@ -19,6 +19,9 @@ + + diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 7afea0a74..0062157d4 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -28,8 +28,8 @@ extension Sequence { /// Returns a cursor over the concatenated results of mapping transform /// over self. - public func flatMap(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor, SegmentOfResult>> { - return IteratorCursor(self).flatMap(transform) + public func flatMap(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor, SegmentOfResult>> { + return AnyCursor(self).flatMap(transform) } } @@ -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`. @@ -168,7 +160,7 @@ extension Cursor { /// If the number of elements to drop exceeds the number of elements in /// the cursor, the result is an empty cursor. /// - /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// let numbers = AnyCursor([1, 2, 3, 4, 5]) /// try print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// try print(numbers.dropFirst(10)) @@ -186,7 +178,7 @@ extension Cursor { /// /// The following example drops the first element from a cursor of integers. /// - /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// let numbers = AnyCursor([1, 2, 3, 4, 5]) /// try print(numbers.dropFirst()) /// // Prints "[2, 3, 4, 5]" /// @@ -203,7 +195,7 @@ extension Cursor { /// The cursor must be finite. If the number of elements to drop exceeds /// the number of elements in the cursor, the result is an empty array. /// - /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// let numbers = AnyCursor([1, 2, 3, 4, 5]) /// try print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// try print(numbers.dropLast(10)) @@ -236,7 +228,7 @@ extension Cursor { /// /// The following example drops the last element from a cursor of integers. /// - /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// let numbers = AnyCursor([1, 2, 3, 4, 5]) /// try print(numbers.dropLast()) /// // Prints "[1, 2, 3, 4]" /// @@ -249,8 +241,8 @@ extension Cursor { /// Returns a cursor over the concatenated results of mapping transform /// over self. - public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor>> { - return flatMap { try IteratorCursor(transform($0)) } + public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor>> { + return flatMap { try AnyCursor(transform($0)) } } /// Returns a cursor over the concatenated results of mapping transform @@ -318,7 +310,7 @@ extension Cursor { /// If the maximum length exceeds the number of elements in the cursor, /// the result contains all the elements in the cursor. /// - /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// let numbers = AnyCursor([1, 2, 3, 4, 5]) /// try print(numbers.prefix(2)) /// // Prints "[1, 2]" /// try print(numbers.prefix(10)) @@ -378,7 +370,7 @@ extension Cursor { /// elements in the cursor, the result contains all the elements in the /// cursor. /// - /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// let numbers = AnyCursor([1, 2, 3, 4, 5]) /// try print(numbers.suffix(2)) /// // Prints "[4, 5]" /// try print(numbers.suffix(10)) @@ -472,7 +464,7 @@ extension Cursor where Element: Cursor { extension Cursor where Element: Sequence { /// Returns the elements of this cursor of sequences, concatenated. - public func joined() -> FlattenCursor>> { + public func joined() -> FlattenCursor>> { return flatMap { $0 } } } @@ -509,7 +501,7 @@ extension Cursor where Element: StringProtocol { /// This cursor forwards its next() method to an arbitrary underlying cursor /// having the same Element type, hiding the specifics of the underlying /// cursor. -public class AnyCursor : Cursor { +public final class AnyCursor : Cursor { private let element: () throws -> Element? /// Creates a cursor that wraps a base cursor but whose type depends only on @@ -518,6 +510,19 @@ public class AnyCursor : Cursor { element = base.next } + /// Creates a cursor that wraps a base iterator but whose type depends only + /// on the base iterator’s element type + public convenience init(iterator: I) where I.Element == Element { + var iterator = iterator + self.init { iterator.next() } + } + + /// Creates a cursor that wraps a base sequence but whose type depends only + /// on the base sequence’s element type + public convenience init(_ s: S) where S.Element == Element { + self.init(iterator: s.makeIterator()) + } + /// Creates a cursor that wraps the given closure in its next() method public init(_ body: @escaping () throws -> Element?) { element = body @@ -749,25 +754,3 @@ public final class PrefixWhileCursor : Cursor { return nil } } - -/// A Cursor whose elements are those of a sequence iterator. -public final class IteratorCursor : Cursor { - private var base: Base - - /// Creates a cursor from a sequence iterator. - public init(_ base: Base) { - self.base = base - } - - /// Creates a cursor from a sequence. - public init(_ s: S) where S.Iterator == Base { - self.base = s.makeIterator() - } - - /// Advances to the next element and returns it, or nil if no next - /// element exists. - /// :nodoc: - public func next() -> Base.Element? { - return base.next() - } -} diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 24a4d7b42..ec1eba555 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -30,6 +30,28 @@ extension Database { return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ?", arguments: [tableName.lowercased()]) != nil } + /// Returns whether a table is an internal SQLite table. + /// + /// Those are tables whose name begins with "sqlite_". + /// + /// For more information, see https://www.sqlite.org/fileformat2.html + public func isSQLiteInternalTable(_ tableName: String) -> Bool { + // https://www.sqlite.org/fileformat2.html#internal_schema_objects + // > The names of internal schema objects always begin with "sqlite_" + // > and any table, index, view, or trigger whose name begins with + // > "sqlite_" is an internal schema object. SQLite prohibits + // > applications from creating objects whose names begin with + // > "sqlite_". + return tableName.starts(with: "sqlite_") + } + + /// Returns whether a table is an internal GRDB table. + /// + /// Those are tables whose name begins with "grdb_". + public func isGRDBInternalTable(_ tableName: String) -> Bool { + return tableName.starts(with: "grdb_") + } + /// Returns whether a view exists. public func viewExists(_ viewName: String) throws -> Bool { // SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html) @@ -129,14 +151,6 @@ extension Database { return primaryKey } - /// The number of columns in the table named `tableName`. - /// - /// - throws: A DatabaseError if table does not exist. - @available(*, deprecated, message: "Use db.columns(in: tableName).count instead") - public func columnCount(in tableName: String) throws -> Int { - return try columns(in: tableName).count - } - /// The indexes on table named `tableName`; returns the empty array if the /// table does not exist. /// @@ -160,6 +174,14 @@ extension Database { return IndexInfo(name: indexName, columns: columns, unique: unique) } + if indexes.isEmpty { + // PRAGMA index_list doesn't throw any error when table does + // not exist. So let's check if table exists: + if try tableExists(tableName) == false { + throw DatabaseError(message: "no such table: \(tableName)") + } + } + schemaCache.set(indexes: indexes, forTable: tableName) return indexes } @@ -179,7 +201,7 @@ extension Database { var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = [] var previousId: Int? = nil for row in try Row.fetchAll(self, "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") { - // row = + // row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."] let id: Int = row[0] let seq: Int = row[1] let table: String = row[2] @@ -194,6 +216,14 @@ extension Database { } } + if rawForeignKeys.isEmpty { + // PRAGMA foreign_key_list doesn't throw any error when table does + // not exist. So let's check if table exists: + if try tableExists(tableName) == false { + throw DatabaseError(message: "no such table: \(tableName)") + } + } + let foreignKeys = try rawForeignKeys.map { (destinationTable, columnMapping) -> ForeignKeyInfo in let orderedMapping = columnMapping .sorted { $0.seq < $1.seq } @@ -218,24 +248,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 } } @@ -313,11 +343,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 @@ -325,7 +355,7 @@ extension Database { /// 2 score INTEGER 0 NULL 0 /// /// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info -public struct ColumnInfo : RowConvertible { +public struct ColumnInfo : FetchableRecord { let cid: Int /// The column name @@ -348,14 +378,14 @@ public struct ColumnInfo : RowConvertible { /// 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" @@ -410,38 +440,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 ad48f304e..56e708767 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -21,8 +21,8 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// let dbQueue = DatabaseQueue(...) /// /// // The Database is the `db` in the closure: -/// try dbQueue.inDatabase { db in -/// try db.execute(...) +/// try dbQueue.write { db in +/// try Player(...).insert(db) /// } public final class Database { // The Database class is not thread-safe. An instance should always be @@ -98,8 +98,6 @@ public final class Database { /// True if the database connection is currently in a transaction. public var isInsideTransaction: Bool { - if isClosed { return false } - // https://sqlite.org/c3ref/get_autocommit.html // // > The sqlite3_get_autocommit() interface returns non-zero or zero if @@ -109,6 +107,12 @@ public final class Database { // > Autocommit mode is on by default. Autocommit mode is disabled by a // > BEGIN statement. Autocommit mode is re-enabled by a COMMIT // > or ROLLBACK. + // + // > If another thread changes the autocommit status of the database + // > connection while this routine is running, then the return value + // > is undefined. + SchedulingWatchdog.preconditionValidQueue(self) + if isClosed { return false } // Support for SerializedDatabasae.deinit return sqlite3_get_autocommit(sqliteConnection) == 0 } @@ -146,7 +150,9 @@ public final class Database { lazy var observationBroker = DatabaseObservationBroker(self) /// The list of compile options used when building SQLite - static let sqliteCompileOptions: Set = DatabaseQueue().inDatabase { try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS")) } + static let sqliteCompileOptions: Set = DatabaseQueue().inDatabase { + try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS")) + } // MARK: - Private properties @@ -298,7 +304,7 @@ extension Database { let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() db.configuration.trace!(sql) }, dbPointer) - #else + #elseif !os(Linux) if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) { sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in guard let stmt = stmt else { return SQLITE_OK } @@ -316,6 +322,12 @@ extension Database { db.configuration.trace!(sql) }, dbPointer) } + #else + sqlite3_trace(sqliteConnection, { (dbPointer, sql) in + guard let sql = sql.map({ String(cString: $0) }) else { return } + let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() + db.configuration.trace!(sql) + }, dbPointer) #endif } @@ -523,6 +535,25 @@ extension Database { } } +extension Database { + + // MARK: - Read-Only Access + + /// Grants read-only access, starting SQLite 3.8.0 + func readOnly(_ block: () throws -> T) rethrows -> T { + if configuration.readonly { + return try block() + } + + // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 + // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // Assume those pragmas never fail + try! execute("PRAGMA query_only = 1") + defer { try! execute("PRAGMA query_only = 0") } + return try block() + } +} + extension Database { // MARK: - Transactions & Savepoint @@ -544,7 +575,7 @@ extension Database { /// - parameters: /// - kind: The transaction type (default nil). If nil, the transaction /// type is configuration.defaultTransactionKind, which itself - /// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html + /// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html /// for more information. /// - block: A block that executes SQL statements and return either /// .commit or .rollback. @@ -639,6 +670,7 @@ extension Database { switch completion { case .commit: try execute("RELEASE SAVEPOINT grdb") + assert(!topLevelSavepoint || !isInsideTransaction) needsRollback = false case .rollback: needsRollback = true @@ -675,7 +707,7 @@ extension Database { /// /// - parameter kind: The transaction type (default nil). If nil, the /// transaction type is configuration.defaultTransactionKind, which itself - /// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html + /// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html /// for more information. /// - throws: The error thrown by the block. public func beginTransaction(_ kind: TransactionKind? = nil) throws { @@ -724,14 +756,17 @@ extension Database { // The second technique is more robust, because we don't have to guess // which rollback errors should be ignored, and which rollback errors // should be exposed to the library user. + SchedulingWatchdog.preconditionValidQueue(self) // guard sqlite3_get_autocommit if sqlite3_get_autocommit(sqliteConnection) == 0 { try execute("ROLLBACK TRANSACTION") } + assert(!isInsideTransaction) } /// Commits a database transaction. public func commit() throws { try execute("COMMIT TRANSACTION") + assert(!isInsideTransaction) } } @@ -841,14 +876,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") @@ -861,8 +888,8 @@ extension Database { /// An SQL column type. /// - /// try db.create(table: "players") { t in - /// t.column("id", .integer).primaryKey() + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// } /// @@ -880,14 +907,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 873a3e922..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 } @@ -82,7 +72,7 @@ public final class DatabaseFunction: Hashable { /// let dbQueue = DatabaseQueue() /// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self) /// dbQueue.add(function: fn) - /// try dbQueue.inDatabase { db in + /// try dbQueue.write { db in /// try db.execute("CREATE TABLE test(i)") /// try db.execute("INSERT INTO test(i) VALUES (1)") /// try db.execute("INSERT INTO test(i) VALUES (2)") @@ -357,7 +347,7 @@ extension DatabaseFunction { /// let dbQueue = DatabaseQueue() /// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self) /// dbQueue.add(function: fn) -/// try dbQueue.inDatabase { db in +/// try dbQueue.write { db in /// try db.execute("CREATE TABLE test(i)") /// try db.execute("INSERT INTO test(i) VALUES (1)") /// try db.execute("INSERT INTO test(i) VALUES (2)") @@ -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 f21e3e8fe..21e908166 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -9,7 +9,7 @@ import Foundation #endif /// A DatabasePool grants concurrent accesses to an SQLite database. -public final class DatabasePool { +public final class DatabasePool: DatabaseWriter { private let writer: SerializedDatabase private var readerConfig: Configuration private var readerPool: Pool! @@ -119,7 +119,7 @@ extension DatabasePool { /// /// - parameter kind: The checkpoint mode (default passive) public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws { - try write { db in + try writer.sync { db in // TODO: read https://www.sqlite.org/c3ref/wal_checkpoint_v2.html and // check whether we need a busy handler on writer and/or readers // when kind is not .Passive. @@ -142,7 +142,7 @@ extension DatabasePool { /// See also setupMemoryManagement(application:) public func releaseMemory() { // TODO: test that this method blocks the current thread until all database accesses are completed. - write { $0.releaseMemory() } + writer.sync { $0.releaseMemory() } readerPool.forEach { reader in reader.sync { $0.releaseMemory() } } @@ -201,7 +201,7 @@ extension DatabasePool { /// Changes the passphrase of an encrypted database public func change(passphrase: String) throws { try readerPool.clear(andThen: { - try write { try $0.change(passphrase: passphrase) } + try writer.sync { try $0.change(passphrase: passphrase) } readerConfig.passphrase = passphrase }) } @@ -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: @@ -315,8 +315,8 @@ extension DatabasePool : DatabaseReader { /// while let row = try rows.next() { ... } /// } /// - /// This method is reentrant. It should be avoided because it fosters - /// dangerous concurrency practices. + /// This method is reentrant. It is unsafe because it fosters dangerous + /// concurrency practices. /// /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block, or any DatabaseError that would @@ -335,179 +335,6 @@ extension DatabasePool : DatabaseReader { } } - /// Returns a reader that can be used from the current dispatch queue, - /// if any. - private var currentReader: SerializedDatabase? { - var readers: [SerializedDatabase] = [] - readerPool.forEach { reader in - // We can't check for reader.onValidQueue here because - // Pool.forEach() runs its closure argument in some arbitrary - // dispatch queue. We thus extract the reader so that we can query - // it below. - readers.append(reader) - } - - // Now the readers array contains some readers. The pool readers may - // already be different, because some other thread may have started - // a new read, for example. - // - // This doesn't matter: the reader we are looking for is already on - // its own dispatch queue. If it exists, is still in use, thus still - // in the pool, and thus still relevant for our check: - return readers.first { $0.onValidQueue } - } - - // MARK: - Functions - - /// Add or redefine an SQL function. - /// - /// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in - /// guard let int = Int.fromDatabaseValue(dbValues[0]) else { - /// return nil - /// } - /// return int + 1 - /// } - /// dbPool.add(function: fn) - /// try dbPool.read { db in - /// try Int.fetchOne(db, "SELECT succ(1)") // 2 - /// } - public func add(function: DatabaseFunction) { - functions.update(with: function) - write { $0.add(function: function) } - readerPool.forEach { reader in - reader.sync { $0.add(function: function) } - } - } - - /// Remove an SQL function. - public func remove(function: DatabaseFunction) { - functions.remove(function) - write { $0.remove(function: function) } - readerPool.forEach { reader in - reader.sync { $0.remove(function: function) } - } - } - - // MARK: - Collations - - /// Add or redefine a collation. - /// - /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in - /// return (string1 as NSString).localizedStandardCompare(string2) - /// } - /// dbPool.add(collation: collation) - /// try dbPool.write { db in - /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") - /// } - public func add(collation: DatabaseCollation) { - collations.update(with: collation) - write { $0.add(collation: collation) } - readerPool.forEach { reader in - reader.sync { $0.add(collation: collation) } - } - } - - /// Remove a collation. - public func remove(collation: DatabaseCollation) { - collations.remove(collation) - write { $0.remove(collation: collation) } - readerPool.forEach { reader in - reader.sync { $0.remove(collation: collation) } - } - } -} - -extension DatabasePool : DatabaseWriter { - - // MARK: - Writing in Database - - /// Synchronously executes an update block in a protected dispatch queue, - /// and returns its result. - /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. - /// - /// try dbPool.write { db in - /// try db.execute(...) - /// } - /// - /// To maintain database integrity, and preserve eventual concurrent reads - /// from seeing an inconsistent database state, prefer the - /// writeInTransaction method. - /// - /// This method is *not* reentrant. - /// - /// - parameters block: A block that executes SQL statements and return - /// either .commit or .rollback. - /// - throws: The error thrown by the block. - public func write(_ block: (Database) throws -> T) rethrows -> T { - return try writer.sync(block) - } - - /// Synchronously executes a block in a protected dispatch queue, wrapped - /// inside a transaction. - /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. - /// - /// If the block throws an error, the transaction is rollbacked and the - /// error is rethrown. If the block returns .rollback, the transaction is - /// also rollbacked, but no error is thrown. - /// - /// try dbPool.writeInTransaction { db in - /// db.execute(...) - /// return .commit - /// } - /// - /// Eventual concurrent readers do not see partial changes: - /// - /// dbPool.writeInTransaction { db in - /// // Eventually preserve a zero balance - /// try db.execute(db, "INSERT INTO credits ...", arguments: [amount]) - /// try db.execute(db, "INSERT INTO debits ...", arguments: [amount]) - /// } - /// - /// dbPool.read { db in - /// // Here the balance is guaranteed to be zero - /// } - /// - /// This method is *not* reentrant. - /// - /// - parameters: - /// - kind: The transaction type (default nil). If nil, the transaction - /// type is configuration.defaultTransactionKind, which itself - /// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html - /// for more information. - /// - block: A block that executes SQL statements and return either - /// .commit or .rollback. - /// - throws: The error thrown by the block, or any error establishing the - /// transaction. - public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { - try write { db in - try db.inTransaction(kind) { - try block(db) - } - } - } - - /// Synchronously executes an update block in a protected dispatch queue, - /// and returns its result. - /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. - /// - /// try dbPool.unsafeReentrantWrite { db in - /// try db.execute(...) - /// } - /// - /// This method is reentrant. It should be avoided because it fosters - /// dangerous concurrency practices. - public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { - return try writer.reentrantSync(block) - } - - // MARK: - Reading from Database - /// Asynchronously executes a read-only block in a protected dispatch queue, /// wrapped in a deferred transaction. /// @@ -519,12 +346,12 @@ extension DatabasePool : DatabaseWriter { /// 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 @@ -581,7 +408,7 @@ extension DatabasePool : DatabaseWriter { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. - GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.") + GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction. If this error is raised from a DatabasePool.write block, use DatabasePool.writeWithoutTransaction instead (and use transactions when needed).") } // The semaphore that blocks the writing dispatch queue until snapshot @@ -615,6 +442,193 @@ extension DatabasePool : DatabaseWriter { throw readError } } + + /// Returns a reader that can be used from the current dispatch queue, + /// if any. + private var currentReader: SerializedDatabase? { + var readers: [SerializedDatabase] = [] + readerPool.forEach { reader in + // We can't check for reader.onValidQueue here because + // Pool.forEach() runs its closure argument in some arbitrary + // dispatch queue. We thus extract the reader so that we can query + // it below. + readers.append(reader) + } + + // Now the readers array contains some readers. The pool readers may + // already be different, because some other thread may have started + // a new read, for example. + // + // This doesn't matter: the reader we are looking for is already on + // its own dispatch queue. If it exists, is still in use, thus still + // in the pool, and thus still relevant for our check: + return readers.first { $0.onValidQueue } + } + + // MARK: - Writing in Database + + /// Synchronously executes an update block in a protected dispatch queue, + /// wrapped inside a transaction, and returns the result of the block. + /// + /// Eventual concurrent database updates are postponed until the block + /// has executed. + /// + /// try dbPool.write { db in + /// try db.execute(...) + /// } + /// + /// Eventual concurrent reads are guaranteed not to see any changes + /// performed in the block until they are all saved in the database. + /// + /// This method is *not* reentrant. + /// + /// - parameters block: A block that executes SQL statements. + /// - throws: The error thrown by the block, or by the wrapping transaction. + public func write(_ block: (Database) throws -> T) throws -> T { + return try writer.sync { db in + var result: T? = nil + try db.inTransaction { + result = try block(db) + return .commit + } + return result! + } + } + + /// Synchronously executes a block that takes a database connection, and + /// returns its result. + /// + /// Eventual concurrent database updates are postponed until the block + /// has executed. + /// + /// Eventual concurrent reads may see changes performed in the block before + /// the block completes. + /// + /// The block is guaranteed to be executed outside of a transaction. + /// + /// This method is *not* reentrant. + /// + /// - parameters block: A block that executes SQL statements and return + /// either .commit or .rollback. + /// - throws: The error thrown by the block. + public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { + return try writer.sync(block) + } + + /// Synchronously executes a block in a protected dispatch queue, wrapped + /// inside a transaction. + /// + /// Eventual concurrent database updates are postponed until the block + /// has executed. + /// + /// If the block throws an error, the transaction is rollbacked and the + /// error is rethrown. If the block returns .rollback, the transaction is + /// also rollbacked, but no error is thrown. + /// + /// try dbPool.writeInTransaction { db in + /// db.execute(...) + /// return .commit + /// } + /// + /// Eventual concurrent reads are guaranteed not to see any changes + /// performed in the block until they are all saved in the database. + /// + /// This method is *not* reentrant. + /// + /// - parameters: + /// - kind: The transaction type (default nil). If nil, the transaction + /// type is configuration.defaultTransactionKind, which itself + /// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html + /// for more information. + /// - block: A block that executes SQL statements and return either + /// .commit or .rollback. + /// - throws: The error thrown by the block, or any error establishing the + /// transaction. + public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { + try writer.sync { db in + try db.inTransaction(kind) { + try block(db) + } + } + } + + /// Synchronously executes an update block in a protected dispatch queue, + /// and returns its result. + /// + /// Eventual concurrent database updates are postponed until the block + /// has executed. + /// + /// try dbPool.unsafeReentrantWrite { db in + /// try db.execute(...) + /// } + /// + /// Eventual concurrent reads may see changes performed in the block before + /// the block completes. + /// + /// This method is reentrant. It is unsafe because it fosters dangerous + /// concurrency practices. + public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { + return try writer.reentrantSync(block) + } + + // MARK: - Functions + + /// Add or redefine an SQL function. + /// + /// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in + /// guard let int = Int.fromDatabaseValue(dbValues[0]) else { + /// return nil + /// } + /// return int + 1 + /// } + /// dbPool.add(function: fn) + /// try dbPool.read { db in + /// try Int.fetchOne(db, "SELECT succ(1)") // 2 + /// } + public func add(function: DatabaseFunction) { + functions.update(with: function) + writer.sync { $0.add(function: function) } + readerPool.forEach { reader in + reader.sync { $0.add(function: function) } + } + } + + /// Remove an SQL function. + public func remove(function: DatabaseFunction) { + functions.remove(function) + writer.sync { $0.remove(function: function) } + readerPool.forEach { reader in + reader.sync { $0.remove(function: function) } + } + } + + // MARK: - Collations + + /// Add or redefine a collation. + /// + /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in + /// return (string1 as NSString).localizedStandardCompare(string2) + /// } + /// dbPool.add(collation: collation) + /// try dbPool.write { db in + /// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD") + /// } + public func add(collation: DatabaseCollation) { + collations.update(with: collation) + writer.sync { $0.add(collation: collation) } + readerPool.forEach { reader in + reader.sync { $0.add(collation: collation) } + } + } + + /// Remove a collation. + public func remove(collation: DatabaseCollation) { + collations.remove(collation) + writer.sync { $0.remove(collation: collation) } + readerPool.forEach { reader in + reader.sync { $0.remove(collation: collation) } + } + } } extension DatabasePool { @@ -622,7 +636,7 @@ extension DatabasePool { // MARK: - Snapshots /// Creates a database snapshot. - //: + /// /// The snapshot sees an unchanging database content, as it existed at the /// moment it was created. /// @@ -631,7 +645,7 @@ extension DatabasePool { /// /// let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in /// try Player.deleteAll() - /// return dbPool.makeSnapshot() + /// return try dbPool.makeSnapshot() /// } /// // <- Other threads may modify the database here /// let snapshot2 = try dbPool.makeSnapshot() @@ -646,11 +660,47 @@ extension DatabasePool { /// try Player.fetchCount(db) /// } /// + /// It is forbidden to create a snapshot from the writer protected dispatch + /// queue when a transaction is opened, though, because it is likely a + /// programmer error: + /// + /// try dbPool.write { db in + /// try db.inTransaction { + /// try Player.deleteAll() + /// // fatal error: makeSnapshot() must not be called from inside a transaction + /// let snapshot = try dbPool.makeSnapshot() + /// return .commit + /// } + /// } + /// + /// To avoid this fatal error, create the snapshot *before* or *after* the + /// transaction: + /// + /// try dbPool.writeWithoutTransaction { db in + /// // OK + /// let snapshot = try dbPool.makeSnapshot() + /// + /// try db.inTransaction { + /// try Player.deleteAll() + /// return .commit + /// } + /// + /// // OK + /// let snapshot = try dbPool.makeSnapshot() + /// } + /// /// You can create as many snapshots as you need, regardless of the maximum /// number of reader connections in the pool. /// /// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html public func makeSnapshot() throws -> DatabaseSnapshot { + // Sanity check + if writer.onValidQueue { + writer.execute { db in + GRDBPrecondition(!db.isInsideTransaction, "makeSnapshot() must not be called from inside a transaction.") + } + } + let snapshot = try DatabaseSnapshot(path: path, configuration: writer.configuration) snapshot.read { setupDatabase($0) } return snapshot diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 6d69228f3..600ed95c5 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -5,22 +5,22 @@ import UIKit #endif /// A DatabaseQueue serializes access to an SQLite database. -public final class DatabaseQueue { - private var serializedDatabase: SerializedDatabase +public final class DatabaseQueue: DatabaseWriter { + private var writer: SerializedDatabase #if os(iOS) private weak var application: UIApplication? #endif - + // MARK: - Configuration /// The database configuration public var configuration: Configuration { - return serializedDatabase.configuration + return writer.configuration } /// The path to the database file; it is ":memory:" for in-memory databases. public var path: String { - return serializedDatabase.path + return writer.path } // MARK: - Initializers @@ -36,7 +36,7 @@ public final class DatabaseQueue { /// - configuration: A configuration. /// - throws: A DatabaseError whenever an SQLite error occurs. public init(path: String, configuration: Configuration = Configuration()) throws { - serializedDatabase = try SerializedDatabase( + writer = try SerializedDatabase( path: path, configuration: configuration, schemaCache: SimpleDatabaseSchemaCache()) @@ -51,7 +51,7 @@ public final class DatabaseQueue { /// - parameter configuration: A configuration. public init(configuration: Configuration = Configuration()) { // Assume SQLite always succeeds creating an in-memory database - serializedDatabase = try! SerializedDatabase( + writer = try! SerializedDatabase( path: ":memory:", configuration: configuration, schemaCache: SimpleDatabaseSchemaCache()) @@ -68,56 +68,6 @@ public final class DatabaseQueue { #endif } -extension DatabaseQueue { - - // MARK: - Database Access - - /// Synchronously executes a block in a protected dispatch queue, and - /// returns its result. - /// - /// let players = try dbQueue.inDatabase { db in - /// try Player.fetchAll(...) - /// } - /// - /// This method is *not* reentrant. - /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block. - public func inDatabase(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.sync(block) - } - - /// Synchronously executes a block in a protected dispatch queue, wrapped - /// inside a transaction. - /// - /// If the block throws an error, the transaction is rollbacked and the - /// error is rethrown. If the block returns .rollback, the transaction is - /// also rollbacked, but no error is thrown. - /// - /// try dbQueue.inTransaction { db in - /// db.execute(...) - /// return .commit - /// } - /// - /// This method is *not* reentrant. - /// - /// - parameters: - /// - kind: The transaction type (default nil). If nil, the transaction - /// type is configuration.defaultTransactionKind, which itself - /// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html - /// for more information. - /// - block: A block that executes SQL statements and return either - /// .commit or .rollback. - /// - throws: The error thrown by the block. - public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { - try inDatabase { db in - try db.inTransaction(kind) { - try block(db) - } - } - } -} - extension DatabaseQueue { // MARK: - Memory management @@ -128,7 +78,7 @@ extension DatabaseQueue { /// /// See also setupMemoryManagement(application:) public func releaseMemory() { - inDatabase { $0.releaseMemory() } + writer.sync { $0.releaseMemory() } } #if os(iOS) @@ -181,12 +131,12 @@ extension DatabaseQueue { /// Changes the passphrase of an encrypted database public func change(passphrase: String) throws { - try inDatabase { try $0.change(passphrase: passphrase) } + try writer.sync { try $0.change(passphrase: passphrase) } } } #endif -extension DatabaseQueue : DatabaseReader { +extension DatabaseQueue { // MARK: - Reading from Database @@ -194,51 +144,178 @@ extension DatabaseQueue : DatabaseReader { /// and returns its result. /// /// let players = try dbQueue.read { db in - /// try Player.fetchAll(...) + /// try Player.fetchAll(db) /// } /// /// This method is *not* reentrant. /// - /// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and - /// SQLCipher, attempts to write in the database throw a DatabaseError whose - /// resultCode is `SQLITE_READONLY`. + /// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and + /// SQLCipher), attempts to write in the database from this meethod throw a + /// DatabaseError of resultCode `SQLITE_READONLY`. /// /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block. public func read(_ block: (Database) throws -> T) rethrows -> T { - // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - #if GRDBCUSTOMSQLITE || GRDBCIPHER - return try inDatabase { try readOnly($0, block) } - #else - if #available(iOS 8.2, OSX 10.10, *) { - return try inDatabase { try readOnly($0, block) } - } else { - return try inDatabase(block) - } - #endif - } - - /// Alias for `inDatabase`. See `DatabaseReader.unsafeRead`. - /// - /// :nodoc: - public func unsafeRead(_ block: (Database) throws -> T) rethrows -> T { - return try inDatabase(block) + return try writer.sync { db in + try db.readOnly { try block(db) } + } } /// Synchronously executes a block in a protected dispatch queue, and /// returns its result. /// - /// try dbQueue.unsafeReentrantRead { db in - /// try db.execute(...) + /// let players = try dbQueue.unsafeRead { db in + /// try Player.fetchAll(db) /// } /// - /// This method is reentrant. It should be avoided because it fosters - /// dangerous concurrency practices. + /// This method is *not* reentrant. + /// + /// - parameter block: A block that accesses the database. + /// - throws: The error thrown by the block. + /// + /// :nodoc: + public func unsafeRead(_ block: (Database) throws -> T) rethrows -> T { + return try writer.sync(block) + } + + /// Synchronously executes a block in a protected dispatch queue, and + /// returns its result. + /// + /// let players = try dbQueue.unsafeReentrantRead { db in + /// try Player.fetchAll(db) + /// } + /// + /// This method is reentrant. It is unsafe because it fosters dangerous + /// concurrency practices. /// /// :nodoc: public func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { - return try serializedDatabase.reentrantSync(block) + return try writer.reentrantSync(block) + } + + /// Synchronously executes *block*. + /// + /// This method must be called from the protected database dispatch queue, + /// outside of a transaction. You'll get a fatal error otherwise. + /// + /// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and + /// SQLCipher), attempts to write in the database from this meethod throw a + /// DatabaseError of resultCode `SQLITE_READONLY`. + /// + /// See `DatabaseWriter.readFromCurrentState`. + /// + /// :nodoc: + public func readFromCurrentState(_ block: @escaping (Database) -> Void) { + // Check that we're on the correct queue... + writer.execute { db in + // ... and that no transaction is opened. + GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.") + db.readOnly { block(db) } + } + } + + // MARK: - Writing in Database + + /// Synchronously executes a block in a protected dispatch queue, wrapped + /// inside a transaction. + /// + /// If the block throws an error, the transaction is rollbacked and the + /// error is rethrown. + /// + /// try dbQueue.write { db in + /// try Player(...).insert(db) + /// } + /// + /// This method is *not* reentrant. + /// + /// - parameter block: A block that executes SQL statements. + /// - throws: An eventual database error, or the error thrown by the block. + public func write(_ block: (Database) throws -> T) rethrows -> T { + return try writer.sync { db in + var result: T? = nil + try db.inTransaction { + result = try block(db) + return .commit + } + return result! + } + } + + /// Synchronously executes a block in a protected dispatch queue, wrapped + /// inside a transaction. + /// + /// If the block throws an error, the transaction is rollbacked and the + /// error is rethrown. If the block returns .rollback, the transaction is + /// also rollbacked, but no error is thrown. + /// + /// try dbQueue.inTransaction { db in + /// try Player(...).insert(db) + /// return .commit + /// } + /// + /// This method is *not* reentrant. + /// + /// - parameters: + /// - kind: The transaction type (default nil). If nil, the transaction + /// type is configuration.defaultTransactionKind, which itself + /// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html + /// for more information. + /// - block: A block that executes SQL statements and return either + /// .commit or .rollback. + /// - throws: The error thrown by the block. + public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { + try writer.sync { db in + try db.inTransaction(kind) { + try block(db) + } + } + } + + /// Synchronously executes a block in a protected dispatch queue, and + /// returns its result. + /// + /// let players = try dbQueue.writeWithoutTransaction { db in + /// try Player(...).insert(db) + /// } + /// + /// This method is *not* reentrant. + /// + /// - parameter block: A block that accesses the database. + /// - throws: The error thrown by the block. + /// + /// :nodoc: + public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { + return try writer.sync(block) + } + + /// Synchronously executes a block in a protected dispatch queue, and + /// returns its result. + /// + /// // INSERT INTO player ... + /// let players = try dbQueue.inDatabase { db in + /// try Player(...).insert(db) + /// } + /// + /// This method is *not* reentrant. + /// + /// - parameter block: A block that accesses the database. + /// - throws: The error thrown by the block. + public func inDatabase(_ block: (Database) throws -> T) rethrows -> T { + return try writer.sync(block) + } + + /// Synchronously executes a block in a protected dispatch queue, and + /// returns its result. + /// + /// // INSERT INTO player ... + /// try dbQueue.unsafeReentrantWrite { db in + /// try Player(...).insert(db) + /// } + /// + /// This method is reentrant. It is unsafe because it fosters dangerous + /// concurrency practices. + public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { + return try writer.reentrantSync(block) } // MARK: - Functions @@ -252,16 +329,16 @@ extension DatabaseQueue : DatabaseReader { /// return int + 1 /// } /// dbQueue.add(function: fn) - /// try dbQueue.inDatabase { db in + /// try dbQueue.read { db in /// try Int.fetchOne(db, "SELECT succ(1)") // 2 /// } public func add(function: DatabaseFunction) { - inDatabase { $0.add(function: function) } + writer.sync { $0.add(function: function) } } /// Remove an SQL function. public func remove(function: DatabaseFunction) { - inDatabase { $0.remove(function: function) } + writer.sync { $0.remove(function: function) } } // MARK: - Collations @@ -272,83 +349,16 @@ extension DatabaseQueue : DatabaseReader { /// return (string1 as NSString).localizedStandardCompare(string2) /// } /// dbQueue.add(collation: collation) - /// try dbQueue.inDatabase { db in - /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") + /// try dbQueue.write { db in + /// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD") /// } public func add(collation: DatabaseCollation) { - inDatabase { $0.add(collation: collation) } + writer.sync { $0.add(collation: collation) } } /// Remove a collation. public func remove(collation: DatabaseCollation) { - inDatabase { $0.remove(collation: collation) } + writer.sync { $0.remove(collation: collation) } } } -extension DatabaseQueue : DatabaseWriter { - - /// Alias for `inDatabase`. See `DatabaseWriter.write`. - /// - /// :nodoc: - public func write(_ block: (Database) throws -> T) rethrows -> T { - return try inDatabase(block) - } - - /// Synchronously executes *block*. - /// - /// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and - /// SQLCipher, attempts to write in the database throw a DatabaseError whose - /// resultCode is `SQLITE_READONLY`. - /// - /// This method must be called from the protected database dispatch queue, - /// outside of a transaction. You'll get a fatal error otherwise. - /// - /// See `DatabaseWriter.readFromCurrentState`. - /// - /// :nodoc: - public func readFromCurrentState(_ block: @escaping (Database) -> Void) { - // Check that we're on the correct queue... - serializedDatabase.execute { db in - // ... and that no transaction is opened. - GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.") - - // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - #if GRDBCUSTOMSQLITE || GRDBCIPHER - readOnly(db, block) - #else - if #available(iOS 8.2, OSX 10.10, *) { - readOnly(db, block) - } else { - block(db) - } - #endif - } - } - - // MARK: - Unsafe Database Access - - /// Synchronously executes a block in a protected dispatch queue, and - /// returns its result. - /// - /// try dbQueue.unsafeReentrantWrite { db in - /// try db.execute(...) - /// } - /// - /// This method is reentrant. It should be avoided because it fosters - /// dangerous concurrency practices. - public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.reentrantSync(block) - } -} - -private func readOnly(_ db: Database, _ block: (Database) throws -> T) rethrows -> T { - guard !db.configuration.readonly else { - return try block(db) - } - - // Assume those pragmas never fail - try! db.execute("PRAGMA query_only = 1") - defer { try! db.execute("PRAGMA query_only = 0") } - return try block(db) -} 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..490450ebb 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -6,39 +6,39 @@ /// cover a full table, or the combination of columns and rows (identified by /// their rowids): /// -/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 | -/// |-------| |-------| |-------| |-------| |-------| -/// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | | -/// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | | -/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | | -/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | | +/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 | +/// |-------| |-------| |-------| |-------| |-------| +/// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | | +/// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | | +/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | | +/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | | /// /// You don't create a database region directly. Instead, you use one of /// those methods: /// -/// - `SelectStatement.fetchedRegion`: +/// - `SelectStatement.databaseRegion`: /// -/// let statement = db.makeSelectStatement("SELECT name, score FROM players") -/// print(statement.fetchedRegion) -/// // prints "players(name,score)" +/// let statement = db.makeSelectStatement("SELECT name, score FROM player") +/// print(statement.databaseRegion) +/// // prints "player(name,score)" /// -/// - `Request.fetchedRegion(_:)` +/// - `FetchRequest.databaseRegion(_:)` /// /// let request = Player.filter(key: 1) -/// try print(request.fetchedRegion(db)) -/// // prints "players(*)[1]" +/// try print(request.databaseRegion(db)) +/// // 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.databaseRegion // "player(*)" /// /// // A query interface request that executes the same statement: /// let request = Player.filter(key: 1) -/// try request.fetchedRegion(db) // "players(*)[1]" +/// try request.databaseRegion(db) // "player(*)[1]" public struct DatabaseRegion: CustomStringConvertible, Equatable { private let tableRegions: [String: TableRegion]? private init(tableRegions: [String: TableRegion]?) { @@ -51,8 +51,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { return tableRegions.isEmpty } - /// The full database: (All columns in all tables) × (all rows) - static let fullDatabase = DatabaseRegion(tableRegions: nil) + /// The region that covers the full database: all columns and all rows + /// from all tables. + public static let fullDatabase = DatabaseRegion(tableRegions: nil) /// The empty database region public init() { @@ -255,14 +256,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 95b313efd..3b804a745 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -10,7 +10,7 @@ import Foundation /// DatabaseValue is the intermediate type between SQLite and your values. /// /// See https://www.sqlite.org/datatype3.html -public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpressible, SQLExpression { +public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpression { /// The SQLite storage public let storage: Storage @@ -204,17 +204,6 @@ extension DatabaseValue { } } -// MARK: - SQLSelectable - -extension DatabaseValue { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// :nodoc: - public func qualified(by qualifier: SQLTableQualifier) -> DatabaseValue { - return self - } -} - // MARK: - Lossless conversions extension DatabaseValue { @@ -319,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. @@ -360,6 +348,18 @@ extension DatabaseValue { return SQLExpressionNot(self) } } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + 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 + } } // CustomStringConvertible @@ -376,7 +376,7 @@ extension DatabaseValue { case .string(let string): return String(reflecting: string) case .blob(let data): - return data.description + return "Data(\(data.description))" } } } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 43cbc96f9..2a72042eb 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -41,8 +41,8 @@ extension DatabaseValueConvertible { /// A cursor of database values extracted from a single column. /// For example: /// -/// try dbQueue.inDatabase { db in -/// let urls: DatabaseValueCursor = try URL.fetchCursor(db, "SELECT url FROM links") +/// try dbQueue.read { db in +/// let urls: DatabaseValueCursor = try URL.fetchCursor(db, "SELECT url FROM link") /// while let url = urls.next() { // URL /// print(url) /// } @@ -81,8 +81,8 @@ public final class DatabaseValueCursor : Cursor /// A cursor of optional database values extracted from a single column. /// For example: /// -/// try dbQueue.inDatabase { db in -/// let urls: NullableDatabaseValueCursor = try Optional.fetchCursor(db, "SELECT url FROM links") +/// try dbQueue.read { db in +/// let urls: NullableDatabaseValueCursor = try Optional.fetchCursor(db, "SELECT url FROM link") /// while let url = urls.next() { // URL? /// print(url) /// } @@ -194,64 +194,6 @@ extension DatabaseValueConvertible { } } -extension DatabaseValueConvertible { - - // MARK: Fetching From Request - - /// Returns a cursor over values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try String.fetchCursor(db, request) // Cursor of String - /// for let name = try names.next() { // String - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - request: A fetch request. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseValueCursor { - let (statement, adapter) = try request.prepare(db) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try String.fetchAll(db, request) // [String] - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] { - let (statement, adapter) = try request.prepare(db) - return try fetchAll(statement, adapter: adapter) - } - - /// Returns a single value fetched from a fetch request. - /// - /// The result is nil if the query returns no row, or if no value can be - /// extracted from the first row. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let name = try String.fetchOne(db, request) // String? - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? { - let (statement, adapter) = try request.prepare(db) - return try fetchOne(statement, adapter: adapter) - } -} - extension DatabaseValueConvertible { // MARK: Fetching From SQL @@ -276,7 +218,7 @@ extension DatabaseValueConvertible { /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor { - return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns an array of values fetched from an SQL query. @@ -291,7 +233,7 @@ extension DatabaseValueConvertible { /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { - return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns a single value fetched from an SQL query. @@ -309,10 +251,122 @@ extension DatabaseValueConvertible { /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { - return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } } +extension DatabaseValueConvertible { + + // MARK: Fetching From FetchRequest + + /// Returns a cursor over values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try String.fetchCursor(db, request) // Cursor of String + /// while let name = try name.next() { // String + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: A cursor over fetched values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: R) throws -> DatabaseValueCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + /// Returns an array of values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try String.fetchAll(db, request) // [String] + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An array. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: R) throws -> [Self] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } + + /// Returns a single value fetched from a fetch request. + /// + /// The result is nil if the query returns no row, or if no value can be + /// extracted from the first row. + /// + /// let request = Player.filter(key: 1).select(Column("name")) + /// let name = try String.fetchOne(db, request) // String? + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An optional value. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchOne(_ db: Database, _ request: R) throws -> Self? { + let (statement, adapter) = try request.prepare(db) + return try fetchOne(statement, adapter: adapter) + } +} + +extension FetchRequest where RowDecoder: DatabaseValueConvertible { + + // MARK: Fetching Values + + /// A cursor over fetched values. + /// + /// let request: ... // Some TypedRequest that fetches String + /// let strings = try request.fetchCursor(db) // Cursor of String + /// while let string = try strings.next() { // String + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor { + return try RowDecoder.fetchCursor(db, self) + } + + /// An array of fetched values. + /// + /// let request: ... // Some TypedRequest that fetches String + /// let strings = try request.fetchAll(db) // [String] + /// + /// - parameter db: A database connection. + /// - returns: An array of values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder] { + return try RowDecoder.fetchAll(db, self) + } + + /// The first fetched value. + /// + /// The result is nil if the request returns no row, or if no value can be + /// extracted from the first row. + /// + /// let request: ... // Some TypedRequest that fetches String + /// let string = try request.fetchOne(db) // String? + /// + /// - parameter db: A database connection. + /// - returns: An optional value. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder? { + return try RowDecoder.fetchOne(db, self) + } +} /// Swift's Optional comes with built-in methods that allow to fetch cursors /// and arrays of optional DatabaseValueConvertible: @@ -368,48 +422,6 @@ extension Optional where Wrapped: DatabaseValueConvertible { } } -extension Optional where Wrapped: DatabaseValueConvertible { - - // MARK: Fetching From Request - - /// Returns a cursor over optional values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try Optional.fetchCursor(db, request) // Cursor of String? - /// while let name = try names.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - requet: A fetch request. - /// - returns: A cursor over fetched optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableDatabaseValueCursor { - let (statement, adapter) = try request.prepare(db) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of optional values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try Optional.fetchAll(db, request) // [String?] - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] { - let (statement, adapter) = try request.prepare(db) - return try fetchAll(statement, adapter: adapter) - } -} - extension Optional where Wrapped: DatabaseValueConvertible { // MARK: Fetching From SQL @@ -434,7 +446,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor { - return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns an array of optional values fetched from an SQL query. @@ -449,6 +461,87 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { - return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } } + +extension Optional where Wrapped: DatabaseValueConvertible { + + // MARK: Fetching From FetchRequest + + /// Returns a cursor over optional values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try Optional.fetchCursor(db, request) // Cursor of String? + /// while let name = try names.next() { // String? + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: A cursor over fetched optional values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: R) throws -> NullableDatabaseValueCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + /// Returns an array of optional values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try Optional.fetchAll(db, request) // [String?] + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An array of optional values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: R) throws -> [Wrapped?] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } +} + +extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible { + + // MARK: Fetching Optional values + + /// A cursor over fetched optional values. + /// + /// let request: ... // Some TypedRequest that fetches Optional + /// let strings = try request.fetchCursor(db) // Cursor of String? + /// while let string = try strings.next() { // String? + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor { + return try Optional.fetchCursor(db, self) + } + + /// An array of fetched optional values. + /// + /// let request: ... // Some TypedRequest that fetches Optional + /// let strings = try request.fetchAll(db) // [String?] + /// + /// - parameter db: A database connection. + /// - returns: An array of values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { + return try Optional.fetchAll(db, self) + } +} + diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 5c5c1b003..d60a88c93 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -23,8 +23,13 @@ public protocol DatabaseWriter : DatabaseReader { /// Eventual concurrent database updates are postponed until the block /// has executed. /// + /// Eventual concurrent reads are guaranteed not to see any changes + /// performed in the block until they are all saved in the database. + /// + /// The block may, or may not, be wrapped inside a transaction. + /// /// This method is *not* reentrant. - func write(_ block: (Database) throws -> T) rethrows -> T + func write(_ block: (Database) throws -> T) throws -> T /// Synchronously executes a block that takes a database connection, and /// returns its result. @@ -32,6 +37,23 @@ public protocol DatabaseWriter : DatabaseReader { /// Eventual concurrent database updates are postponed until the block /// has executed. /// + /// Eventual concurrent reads may see changes performed in the block before + /// the block completes. + /// + /// The block is guaranteed to be executed outside of a transaction. + /// + /// This method is *not* reentrant. + func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T + + /// Synchronously executes a block that takes a database connection, and + /// returns its result. + /// + /// Eventual concurrent database updates are postponed until the block + /// has executed. + /// + /// Eventual concurrent reads may see changes performed in the block before + /// the block completes. + /// /// This method is reentrant. It should be avoided because it fosters /// dangerous concurrency practices. func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T @@ -51,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 } @@ -73,12 +95,12 @@ extension DatabaseWriter { /// the observer lifetime (observation lasts until observer /// is deallocated). public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) { - write { $0.add(transactionObserver: transactionObserver, extent: extent) } + writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) } } /// Remove a transaction observer. public func remove(transactionObserver: TransactionObserver) { - write { $0.remove(transactionObserver: transactionObserver) } + writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) } } } @@ -119,9 +141,14 @@ public final class AnyDatabaseWriter : DatabaseWriter { // MARK: - Writing in Database /// :nodoc: - public func write(_ block: (Database) throws -> T) rethrows -> T { + public func write(_ block: (Database) throws -> T) throws -> T { return try base.write(block) } + + /// :nodoc: + public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { + return try base.writeWithoutTransaction(block) + } /// :nodoc: public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift new file mode 100644 index 000000000..cf8995872 --- /dev/null +++ b/GRDB/Core/FetchRequest.swift @@ -0,0 +1,255 @@ +// MARK: - FetchRequest + +/// The protocol for all requests that run from a single select statement, and +/// tell how fetched rows should be interpreted. +/// +/// struct Player: FetchableRecord { ... } +/// let request: ... // Some FetchRequest that fetches Player +/// try request.fetchCursor(db) // Cursor of Player +/// try request.fetchAll(db) // [Player] +/// try request.fetchOne(db) // Player? +public protocol FetchRequest { + /// The type that tells how fetched database rows should be interpreted. + associatedtype RowDecoder + + /// Returns a tuple that contains a prepared statement that is ready to be + /// executed, and an eventual row adapter. + /// + /// - parameter db: A database connection. + /// - returns: A prepared statement and an eventual row adapter. + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) + + /// Returns the number of rows fetched by the request. + /// + /// The default implementation builds a naive SQL query based on the + /// statement returned by the `prepare` method: + /// `SELECT COUNT(*) FROM (...)`. + /// + /// Adopting types can refine this method in order to use more + /// efficient SQL. + /// + /// - parameter db: A database connection. + func fetchCount(_ db: Database) throws -> Int + + /// Returns the database region that the request looks into. + /// + /// - parameter db: A database connection. + func databaseRegion(_ db: Database) throws -> DatabaseRegion +} + +extension FetchRequest { + /// Returns an adapted request. + public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { + return AdaptedFetchRequest(self, adapter) + } + + /// Returns the number of rows fetched by the request. + /// + /// This default implementation builds a naive SQL query based on the + /// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`. + /// + /// - parameter db: A database connection. + public func fetchCount(_ db: Database) throws -> Int { + let (statement, _) = try prepare(db) + let sql = "SELECT COUNT(*) FROM (\(statement.sql))" + return try Int.fetchOne(db, sql, arguments: statement.arguments)! + } + + /// Returns the database region that the request looks into. + /// + /// This default implementation returns a region built from the statement + /// returned by the `prepare` method. + /// + /// - parameter db: A database connection. + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + let (statement, _) = try prepare(db) + return statement.databaseRegion + } +} + +// MARK: - AdaptedFetchRequest + +/// An adapted request. +public struct AdaptedFetchRequest : FetchRequest { + public typealias RowDecoder = Base.RowDecoder + + private let base: Base + private let adapter: (Database) throws -> RowAdapter + + /// Creates an adapted request from a base request and a closure that builds + /// a row adapter from a database connection. + init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) { + self.base = base + self.adapter = adapter + } + + /// :nodoc: + public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + let (statement, baseAdapter) = try base.prepare(db) + if let baseAdapter = baseAdapter { + return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db))) + } else { + return try (statement, adapter(db)) + } + } + + /// :nodoc: + public func fetchCount(_ db: Database) throws -> Int { + return try base.fetchCount(db) + } + + /// :nodoc: + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + return try base.databaseRegion(db) + } +} + +// MARK: - AnyFetchRequest + +/// A type-erased FetchRequest. +/// +/// An AnyFetchRequest forwards its operations to an underlying request, +/// hiding its specifics. +public struct AnyFetchRequest : FetchRequest { + public typealias RowDecoder = T + + private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?) + private let _fetchCount: (Database) throws -> Int + private let _databaseRegion: (Database) throws -> DatabaseRegion + + /// Creates a request that wraps and forwards operations to `request`. + public init(_ request: Request) { + _prepare = request.prepare + _fetchCount = request.fetchCount + _databaseRegion = request.databaseRegion + } + + /// Creates a request whose `prepare()` method wraps and forwards + /// operations the argument closure. + public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) { + _prepare = { db in + try prepare(db) + } + + _fetchCount = { db in + let (statement, _) = try prepare(db) + let sql = "SELECT COUNT(*) FROM (\(statement.sql))" + return try Int.fetchOne(db, sql, arguments: statement.arguments)! + } + + _databaseRegion = { db in + let (statement, _) = try prepare(db) + return statement.databaseRegion + } + } + + /// :nodoc: + public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try _prepare(db) + } + + /// :nodoc: + public func fetchCount(_ db: Database) throws -> Int { + return try _fetchCount(db) + } + + /// :nodoc: + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + return try _databaseRegion(db) + } +} + +// MARK: - SQLRequest + +/// A FetchRequest built from raw SQL. +public struct SQLRequest : FetchRequest { + public typealias RowDecoder = T + + public var sql: String + public var arguments: StatementArguments? + public var adapter: RowAdapter? + private let cache: Cache? + + /// Creates a request from an SQL string, optional arguments, and + /// optional row adapter. + /// + /// let request = SQLRequest("SELECT * FROM player") + /// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1]) + /// + /// - parameters: + /// - sql: An SQL query. + /// - arguments: Optional statement arguments. + /// - adapter: Optional RowAdapter. + /// - cached: Defaults to false. If true, the request reuses a cached + /// prepared statement. + /// - returns: A SQLRequest + public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) { + self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil) + } + + /// Creates an SQL request from any other fetch request. + /// + /// - parameters: + /// - db: A database connection. + /// - request: A request. + /// - cached: Defaults to false. If true, the request reuses a cached + /// prepared statement. + /// - returns: An SQLRequest + public init(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder { + let (statement, adapter) = try request.prepare(db) + self.init(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached) + } + + /// Creates an SQL request from an SQL string, optional arguments, and + /// optional row adapter. + /// + /// let request = SQLRequest("SELECT * FROM player") + /// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1]) + /// + /// - parameters: + /// - sql: An SQL query. + /// - arguments: Optional statement arguments. + /// - adapter: Optional RowAdapter. + /// - statementCacheName: Optional statement cache name. + /// - returns: A SQLRequest + init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) { + self.sql = sql + self.arguments = arguments + self.adapter = adapter + self.cache = cache + } + + /// A tuple that contains a prepared statement that is ready to be + /// executed, and an eventual row adapter. + /// + /// - parameter db: A database connection. + /// + /// :nodoc: + public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + let statement: SelectStatement + switch cache { + case .none: + statement = try db.makeSelectStatement(sql) + case .public?: + statement = try db.cachedSelectStatement(sql) + case .internal?: + statement = try db.internalCachedSelectStatement(sql) + } + if let arguments = arguments { + try statement.setArgumentsWithValidation(arguments) + } + return (statement, adapter) + } + + /// There are two statement caches: one for statements generated by the + /// user, and one for the statements generated by GRDB. Those are separated + /// so that GRDB has no opportunity to inadvertently modify the arguments of + /// user's cached statements. + enum Cache { + /// The public cache, for library user + case `public` + + /// The internal cache, for grdb + case `internal` + } +} diff --git a/GRDB/Core/Request.swift b/GRDB/Core/Request.swift deleted file mode 100644 index 4e67887fa..000000000 --- a/GRDB/Core/Request.swift +++ /dev/null @@ -1,622 +0,0 @@ -/// The protocol for all types that define a way to fetch database rows. -/// -/// Requests can feed the fetching methods of any fetchable type (Row, -/// value, record): -/// -/// let request: Request = ... -/// try Row.fetchCursor(db, request) // RowCursor -/// try String.fetchAll(db, request) // [String] -/// try Player.fetchOne(db, request) // Player? -public protocol Request { - /// A tuple that contains a prepared statement that is ready to be - /// executed, and an eventual row adapter. - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) - - /// The number of rows fetched by the request. - /// - /// Default implementation builds a naive SQL query based on the statement - /// returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`. - /// - /// Adopting types can refine this countRequest method and return more - /// efficient SQL. - /// - /// - parameter db: A database connection. - func fetchCount(_ db: Database) throws -> Int - - /// The database region that the request looks into. - /// - /// This method has a default implementation. - /// - /// - parameter db: A database connection. - func fetchedRegion(_ db: Database) throws -> DatabaseRegion -} - -extension Request { - /// The number of rows fetched by the request. - /// - /// This default implementation builds a naive SQL query based on the - /// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`. - /// - /// - parameter db: A database connection. - public func fetchCount(_ db: Database) throws -> Int { - let (statement, _) = try prepare(db) - let sql = "SELECT COUNT(*) FROM (\(statement.sql))" - return try Int.fetchOne(db, sql, arguments: statement.arguments)! - } - - /// Returns an equivalent SQLRequest. - /// - /// - parameters: - /// - db: A database connection. - /// - cached: Defaults to false. If true, the request reuses a cached - /// prepared statement. - /// - returns: An SQLRequest - public func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest { - let (statement, adapter) = try prepare(db) - return SQLRequest(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached) - } - - /// The database region that the request looks into. - /// - /// - parameter db: A database connection. - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - let (statement, _) = try prepare(db) - return statement.fetchedRegion - } -} - -extension Request { - /// 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) -> AnyTypedRequest { - return AnyTypedRequest(self) - } - - /// Returns an adapted request. - public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest { - return AdaptedRequest(self, adapter) - } -} - -/// An adapted request. -public struct AdaptedRequest : Request { - private let base: Base - private let adapter: (Database) throws -> RowAdapter - - /// Creates an adapted request from a base request and a closure that builds - /// a row adapter from a database connection. - init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) { - self.base = base - self.adapter = adapter - } - - /// :nodoc: - public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - let (statement, baseAdapter) = try base.prepare(db) - if let baseAdapter = baseAdapter { - return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db))) - } else { - return try (statement, adapter(db)) - } - } - - /// :nodoc: - public func fetchCount(_ db: Database) throws -> Int { - return try base.fetchCount(db) - } - - /// :nodoc: - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try base.fetchedRegion(db) - } -} - -/// A type-erased Request. -/// -/// An instance of AnyRequest forwards its operations to an underlying request, -/// hiding its specifics. -public struct AnyRequest : Request { - private let base: Request - - /// Creates a new request that wraps and forwards operations to `request`. - public init(_ request: Request) { - base = request - } - - /// Creates a new request whose `prepare()` method wraps and forwards - /// operations the argument closure. - public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) { - struct PrepareRequest: Request { - let base: (Database) throws -> (SelectStatement, RowAdapter?) - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try base(db) - } - } - base = PrepareRequest(base: prepare) - } - - /// :nodoc: - public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try base.prepare(db) - } - - /// :nodoc: - public func fetchCount(_ db: Database) throws -> Int { - return try base.fetchCount(db) - } - - /// :nodoc: - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try base.fetchedRegion(db) - } -} - -/// A Request built from raw SQL. -public struct SQLRequest : Request { - public let sql: String - public let arguments: StatementArguments? - public let adapter: RowAdapter? - private let cache: Cache? - - /// Creates a new 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]) - /// - /// - parameters: - /// - sql: An SQL query. - /// - arguments: Optional statement arguments. - /// - adapter: Optional RowAdapter. - /// - cached: Defaults to false. If true, the request reuses a cached - /// prepared statement. - /// - returns: A SQLRequest - public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) { - self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil) - } - - /// Creates a new 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]) - /// - /// - parameters: - /// - sql: An SQL query. - /// - arguments: Optional statement arguments. - /// - adapter: Optional RowAdapter. - /// - statementCacheName: Optional statement cache name. - /// - returns: A SQLRequest - init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) { - self.sql = sql - self.arguments = arguments - self.adapter = adapter - self.cache = cache - } - - /// A tuple that contains a prepared statement that is ready to be - /// executed, and an eventual row adapter. - /// - /// - parameter db: A database connection. - /// - /// :nodoc: - public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - let statement: SelectStatement - switch cache { - case .none: - statement = try db.makeSelectStatement(sql) - case .public?: - statement = try db.cachedSelectStatement(sql) - case .internal?: - statement = try db.internalCachedSelectStatement(sql) - } - if let arguments = arguments { - try statement.setArgumentsWithValidation(arguments) - } - return (statement, adapter) - } - - /// There are two statement caches: one for statements generated by the - /// user, and one for the statements generated by GRDB. Those are separated - /// so that GRDB has no opportunity to inadvertently modify the arguments of - /// user's cached statements. - enum Cache { - /// The public cache, for library user - case `public` - - /// The internal cache, for grdb - case `internal` - } -} - -/// The protocol for requests that know how to decode database rows. -/// -/// Typed requests can fetch if their associated type RowDecoder is able to -/// decode rows (Row, value, record) -/// -/// struct Player: RowConvertible { ... } -/// let request: ... // Some TypedRequest that fetches Player -/// try request.fetchCursor(db) // Cursor of Player -/// try request.fetchAll(db) // [Player] -/// try request.fetchOne(db) // Player? -public protocol TypedRequest : Request { - - /// The type that can convert raw database rows to fetched values - associatedtype RowDecoder -} - -extension TypedRequest { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Returns an adapted typed request. - public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest { - return AdaptedTypedRequest(self, adapter) - } -} - -/// An adapted typed request. -public struct AdaptedTypedRequest : TypedRequest { - /// The type that can convert raw database rows to fetched values - public typealias RowDecoder = Base.RowDecoder - - private let base: AdaptedRequest - - /// Creates an adapted request from a base request and a closure that builds - /// a row adapter from a database connection. - init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) { - self.base = AdaptedRequest(base, adapter) - } - - /// :nodoc: - public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try base.prepare(db) - } - - /// :nodoc: - public func fetchCount(_ db: Database) throws -> Int { - return try base.fetchCount(db) - } - - /// :nodoc: - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try base.fetchedRegion(db) - } -} - -/// A type-erased TypedRequest. -/// -/// An instance of AnyTypedRequest forwards its operations to an underlying -/// typed request, hiding its specifics. -public struct AnyTypedRequest : TypedRequest { - /// The type that can convert raw database rows to fetched values - public typealias RowDecoder = T - private let base: Request - - /// Support for Request.asRequest(of:) - /// Not public because not type-safe. - fileprivate init(_ request: Request) { - base = request - } - - /// Creates a new request that wraps and forwards operations to `request`. - public init(_ request: Request) where Request: TypedRequest, Request.RowDecoder == RowDecoder { - base = request - } - - /// Creates a new request whose `prepare()` method wraps and forwards - /// operations the argument closure. - public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) { - base = AnyRequest(prepare) - } - - /// :nodoc: - public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try base.prepare(db) - } - - /// :nodoc: - public func fetchCount(_ db: Database) throws -> Int { - return try base.fetchCount(db) - } - - /// :nodoc: - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try base.fetchedRegion(db) - } -} - -extension TypedRequest where RowDecoder: RowConvertible { - - // MARK: Fetching Record and RowConvertible - - /// A cursor over fetched records. - /// - /// let request: ... // Some TypedRequest that fetches Player - /// let players = try request.fetchCursor(db) // Cursor of Player - /// while let player = try players.next() { // Player - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> RecordCursor { - return try RowDecoder.fetchCursor(db, self) - } - - /// An array of fetched records. - /// - /// let request: ... // Some TypedRequest that fetches Player - /// let players = try request.fetchAll(db) // [Player] - /// - /// - parameter db: A database connection. - /// - returns: An array of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { - return try RowDecoder.fetchAll(db, self) - } - - /// The first fetched record. - /// - /// let request: ... // Some TypedRequest that fetches Player - /// let player = try request.fetchOne(db) // Player? - /// - /// - parameter db: A database connection. - /// - returns: An optional record. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { - return try RowDecoder.fetchOne(db, self) - } -} - -extension TypedRequest where RowDecoder: DatabaseValueConvertible { - - // MARK: Fetching Values - - /// A cursor over fetched values. - /// - /// let request: ... // Some TypedRequest that fetches String - /// let strings = try request.fetchCursor(db) // Cursor of String - /// while let string = try strings.next() { // String - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor { - return try RowDecoder.fetchCursor(db, self) - } - - /// An array of fetched values. - /// - /// let request: ... // Some TypedRequest that fetches String - /// let strings = try request.fetchAll(db) // [String] - /// - /// - parameter db: A database connection. - /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { - return try RowDecoder.fetchAll(db, self) - } - - /// The first fetched value. - /// - /// The result is nil if the request returns no row, or if no value can be - /// extracted from the first row. - /// - /// let request: ... // Some TypedRequest that fetches String - /// let string = try request.fetchOne(db) // String? - /// - /// - parameter db: A database connection. - /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { - return try RowDecoder.fetchOne(db, self) - } -} - -extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible { - - // MARK: Fetching Values - - /// A cursor over fetched values. - /// - /// let request: ... // Some TypedRequest that fetches String - /// let strings = try request.fetchCursor(db) // Cursor of String - /// while let string = try strings.next() { // String - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> ColumnCursor { - return try RowDecoder.fetchCursor(db, self) - } - - /// An array of fetched values. - /// - /// let request: ... // Some TypedRequest that fetches String - /// let strings = try request.fetchAll(db) // [String] - /// - /// - parameter db: A database connection. - /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { - return try RowDecoder.fetchAll(db, self) - } - - /// The first fetched value. - /// - /// The result is nil if the request returns no row, or if no value can be - /// extracted from the first row. - /// - /// let request: ... // Some TypedRequest that fetches String - /// let string = try request.fetchOne(db) // String? - /// - /// - parameter db: A database connection. - /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { - return try RowDecoder.fetchOne(db, self) - } -} - -extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible { - - // MARK: Fetching Optional values - - /// A cursor over fetched optional values. - /// - /// let request: ... // Some TypedRequest that fetches Optional - /// let strings = try request.fetchCursor(db) // Cursor of String? - /// while let string = try strings.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor { - return try Optional.fetchCursor(db, self) - } - - /// An array of fetched optional values. - /// - /// let request: ... // Some TypedRequest that fetches Optional - /// let strings = try request.fetchAll(db) // [String?] - /// - /// - parameter db: A database connection. - /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { - return try Optional.fetchAll(db, self) - } -} - -extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible { - - // MARK: Fetching Optional values - - /// A cursor over fetched optional values. - /// - /// let request: ... // Some TypedRequest that fetches Optional - /// let strings = try request.fetchCursor(db) // Cursor of String? - /// while let string = try strings.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> NullableColumnCursor { - return try Optional.fetchCursor(db, self) - } - - /// An array of fetched optional values. - /// - /// let request: ... // Some TypedRequest that fetches Optional - /// let strings = try request.fetchAll(db) // [String?] - /// - /// - parameter db: A database connection. - /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { - return try Optional.fetchAll(db, self) - } -} - -extension TypedRequest where RowDecoder: Row { - - // MARK: Fetching Rows - - /// A cursor over fetched rows. - /// - /// let request: ... // Some TypedRequest that fetches Row - /// let rows = try request.fetchCursor(db) // RowCursor - /// while let row = try rows.next() { // Row - /// let id: Int64 = row[0] - /// let name: String = row[1] - /// } - /// - /// Fetched rows are reused during the cursor iteration: don't turn a row - /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since - /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` - /// instead. - /// - /// For the same reason, make sure you make a copy whenever you extract a - /// row for later use: `row.copy()`. - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> RowCursor { - return try Row.fetchCursor(db, self) - } - - /// An array of fetched rows. - /// - /// let request: ... // Some TypedRequest that fetches Row - /// let rows = try request.fetchAll(db) - /// - /// - parameter db: A database connection. - /// - returns: An array of fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [Row] { - return try Row.fetchAll(db, self) - } - - /// The first fetched row. - /// - /// let request: ... // Some TypedRequest that fetches Row - /// let row = try request.fetchOne(db) - /// - /// - parameter db: A database connection. - /// - returns: A,n optional rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> Row? { - return try Row.fetchOne(db, self) - } -} diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 348c6976a..804054651 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -6,7 +6,7 @@ import Foundation #endif /// A database row. -public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible { +public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible, CustomDebugStringConvertible { let impl: RowImpl /// Unless we are producing a row array, we use a single row when iterating @@ -61,7 +61,7 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl /// the iteration of a query: make sure to make a copy of it whenever you /// want to keep a specific one: `row.copy()`. public func copy() -> Row { - return impl.copy(self) + return impl.copiedRow(self) } // MARK: - Not Public @@ -143,11 +143,11 @@ extension Row { /// let row = try Row.fetchOne(db, "SELECT NULL, NULL")! /// row.containsNonNullValue // false public var containsNonNullValue: Bool { - for i in (0.. DatabaseValueConvertible? { + public subscript(_ column: ColumnExpression) -> DatabaseValueConvertible? { return self[column.name] } @@ -359,7 +359,7 @@ extension Row { /// If the column is missing or if the SQLite value is NULL, the result is /// nil. Otherwise the SQLite value is converted to the requested type /// `Value`. Should this conversion fail, a fatal error is raised. - public subscript(_ column: Column) -> Value? { + public subscript(_ column: ColumnExpression) -> Value? { return self[column.name] } @@ -375,7 +375,7 @@ extension Row { /// This method exists as an optimization opportunity for types that adopt /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions /// (see https://www.sqlite.org/datatype3.html). - public subscript(_ column: Column) -> Value? { + public subscript(_ column: ColumnExpression) -> Value? { return self[column.name] } @@ -388,7 +388,7 @@ extension Row { /// /// This method crashes if the fetched SQLite value is NULL, or if the /// SQLite value can not be converted to `Value`. - public subscript(_ column: Column) -> Value { + public subscript(_ column: ColumnExpression) -> Value { return self[column.name] } @@ -405,7 +405,7 @@ extension Row { /// This method exists as an optimization opportunity for types that adopt /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions /// (see https://www.sqlite.org/datatype3.html). - public subscript(_ column: Column) -> Value { + public subscript(_ column: ColumnExpression) -> Value { return self[column.name] } @@ -453,7 +453,7 @@ extension Row { /// /// The returned data does not owns its bytes: it must not be used longer /// than the row's lifetime. - public func dataNoCopy(_ column: Column) -> Data? { + public func dataNoCopy(_ column: ColumnExpression) -> Data? { return dataNoCopy(named: column.name) } } @@ -482,8 +482,8 @@ extension Row { /// /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support /// for more information. - public subscript(_ scope: String) -> Record { - guard let scopedRow = scoped(on: scope) else { + public subscript(_ scope: String) -> Record { + guard let scopedRow = scopesTree[scope] else { // Programmer error fatalError("no such scope: \(scope)") } @@ -498,8 +498,8 @@ extension Row { /// /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support /// for more information. - public subscript(_ scope: String) -> Record? { - guard let scopedRow = scoped(on: scope), scopedRow.containsNonNullValue else { + public subscript(_ scope: String) -> Record? { + guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else { return nil } return Record(row: scopedRow) @@ -510,48 +510,80 @@ extension Row { // MARK: - Scopes - var scopeNames: Set { - return impl.scopeNames - } - - /// Returns a scoped row, if the row was fetched with a row adapter that - /// defines this scope. + /// Returns a view on the scopes defined by row adapters. /// - /// // Two adapters - /// let fooAdapter = ColumnMapping(["value": "foo"]) - /// let barAdapter = ColumnMapping(["value": "bar"]) + /// For example: /// - /// // Define scopes + /// // Define a tree of nested scopes /// let adapter = ScopeAdapter([ - /// "foo": fooAdapter, - /// "bar": barAdapter]) + /// "foo": RangeRowAdapter(0..<1), + /// "bar": RangeRowAdapter(1..<2).addingScopes([ + /// "baz" : RangeRowAdapter(2..<3)])]) /// /// // Fetch - /// let sql = "SELECT 'foo' AS foo, 'bar' AS bar" + /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" /// let row = try Row.fetchOne(db, sql, adapter: adapter)! /// - /// // Scoped rows: - /// if let fooRow = row.scoped(on: "foo") { - /// fooRow["value"] // "foo" - /// } - /// if let barRow = row.scopeed(on: "bar") { - /// barRow["value"] // "bar" - /// } - public func scoped(on name: String) -> Row? { - return impl.scoped(on: name) + /// row.scopes.count // 2 + /// row.scopes.names // ["foo", "bar"] + /// + /// row.scopes["foo"] // [foo:1] + /// row.scopes["bar"] // [bar:2] + /// row.scopes["baz"] // nil + public var scopes: ScopesView { + return impl.scopes } - /// Returns a copy of the row, without any scoped row (if the row was fetched - /// with a row adapter that defines scopes). + /// Returns a view on the scopes tree defined by row adapters. + /// + /// For example: + /// + /// // Define a tree of nested scopes + /// let adapter = ScopeAdapter([ + /// "foo": RangeRowAdapter(0..<1), + /// "bar": RangeRowAdapter(1..<2).addingScopes([ + /// "baz" : RangeRowAdapter(2..<3)])]) + /// + /// // Fetch + /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" + /// let row = try Row.fetchOne(db, sql, adapter: adapter)! + /// + /// row.scopesTree.names // ["foo", "bar", "baz"] + /// + /// row.scopesTree["foo"] // [foo:1] + /// row.scopesTree["bar"] // [bar:2] + /// row.scopesTree["baz"] // [baz:3] + public var scopesTree: ScopesTreeView { + return ScopesTreeView(scopes: scopes) + } + + /// Returns a copy of the row, without any scopes. + /// + /// This property can turn out useful when you want to test the content of + /// adapted rows, such as rows fetched from joined requests. + /// + /// let row = ... + /// // Failure because row equality tests for row scopes: + /// XCTAssertEqual(row, ["id": 1, "name": "foo"]) + /// // Success: + /// XCTAssertEqual(row.unscoped, ["id": 1, "name": "foo"]) public var unscoped: Row { - return Row(impl: ArrayRowImpl(columns: map { ($0, $1) })) + return impl.unscopedRow(self) + } + + /// Return the raw row fetched from the database. + /// + /// This property can turn out useful when you debug the consumption of + /// adapted rows, such as rows fetched from joined requests. + public var unadapted: Row { + return impl.unadaptedRow(self) } } /// A cursor of database rows. For example: /// -/// try dbQueue.inDatabase { db in -/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM players") +/// try dbQueue.read { db in +/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM player") /// } public final class RowCursor : Cursor { public let statement: SelectStatement @@ -652,80 +684,13 @@ extension Row { } } -extension Row { - - // MARK: - Fetching From Request - - /// Returns a cursor over rows fetched from a fetch request. - /// - /// let idColumn = Column("id") - /// let nameColumn = Column("name") - /// let request = Player.select(idColumn, nameColumn) - /// let rows = try Row.fetchCursor(db) // RowCursor - /// while let row = try rows.next() { // Row - /// let id: Int64 = row[0] - /// let name: String = row[1] - /// } - /// - /// Fetched rows are reused during the cursor iteration: don't turn a row - /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since - /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` - /// instead. - /// - /// For the same reason, make sure you make a copy whenever you extract a - /// row for later use: `row.copy()`. - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - request: A fetch request. - /// - returns: A cursor over fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: Request) throws -> RowCursor { - let (statement, adapter) = try request.prepare(db) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of rows fetched from a fetch request. - /// - /// let idColumn = Column("id") - /// let nameColumn = Column("name") - /// let request = Player.select(idColumn, nameColumn) - /// let rows = try Row.fetchAll(db, request) - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: Request) throws -> [Row] { - let (statement, adapter) = try request.prepare(db) - return try fetchAll(statement, adapter: adapter) - } - - /// Returns a single row fetched from a fetch request. - /// - /// let idColumn = Column("id") - /// let nameColumn = Column("name") - /// let request = Player.select(idColumn, nameColumn) - /// let row = try Row.fetchOne(db, request) - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: Request) throws -> Row? { - let (statement, adapter) = try request.prepare(db) - return try fetchOne(statement, adapter: adapter) - } -} - extension Row { // MARK: - Fetching From SQL /// 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] @@ -752,7 +717,7 @@ extension Row { /// - returns: A cursor over fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor { - return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns an array of rows fetched from an SQL query. @@ -767,7 +732,7 @@ extension Row { /// - returns: An array of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] { - return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns a single row fetched from an SQL query. @@ -782,10 +747,135 @@ extension Row { /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? { - return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } } +extension Row { + + // MARK: - Fetching From FetchRequest + + /// Returns a cursor over rows fetched from a fetch request. + /// + /// let request = Player.all() + /// let rows = try Row.fetchCursor(db, request) // RowCursor + /// while let row = try rows.next() { // Row + /// let id: Int64 = row["id"] + /// let name: String = row["name"] + /// } + /// + /// Fetched rows are reused during the cursor iteration: don't turn a row + /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since + /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` + /// instead. + /// + /// For the same reason, make sure you make a copy whenever you extract a + /// row for later use: `row.copy()`. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: A cursor over fetched rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: R) throws -> RowCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + /// Returns an array of rows fetched from a fetch request. + /// + /// let request = Player.all() + /// let rows = try Row.fetchAll(db, request) + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An array of rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: R) throws -> [Row] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } + + /// Returns a single row fetched from a fetch request. + /// + /// let request = Player.filter(key: 1) + /// let row = try Row.fetchOne(db, request) + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An optional row. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchOne(_ db: Database, _ request: R) throws -> Row? { + let (statement, adapter) = try request.prepare(db) + return try fetchOne(statement, adapter: adapter) + } +} + +extension FetchRequest where RowDecoder: Row { + + // MARK: Fetching Rows + + /// A cursor over fetched rows. + /// + /// let request: ... // Some TypedRequest that fetches Row + /// let rows = try request.fetchCursor(db) // RowCursor + /// while let row = try rows.next() { // Row + /// let id: Int64 = row[0] + /// let name: String = row[1] + /// } + /// + /// Fetched rows are reused during the cursor iteration: don't turn a row + /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since + /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` + /// instead. + /// + /// For the same reason, make sure you make a copy whenever you extract a + /// row for later use: `row.copy()`. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> RowCursor { + return try Row.fetchCursor(db, self) + } + + /// An array of fetched rows. + /// + /// let request: ... // Some TypedRequest that fetches Row + /// let rows = try request.fetchAll(db) + /// + /// - parameter db: A database connection. + /// - returns: An array of fetched rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [Row] { + return try Row.fetchAll(db, self) + } + + /// The first fetched row. + /// + /// let request: ... // Some TypedRequest that fetches Row + /// let row = try request.fetchOne(db) + /// + /// - parameter db: A database connection. + /// - returns: A,n optional rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> Row? { + return try Row.fetchOne(db, self) + } +} + // ExpressibleByDictionaryLiteral extension Row { @@ -794,7 +884,7 @@ extension Row { /// /// let row: Row = ["foo": 1, "foo": "bar", "baz": nil] /// print(row) - /// // Prints + /// // Prints [foo:1 foo:"bar" baz:NULL] public convenience init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) { self.init(impl: ArrayRowImpl(columns: elements.map { ($0, $1?.databaseValue ?? .null) })) } @@ -852,15 +942,15 @@ extension Row { } } - let lscopeNames = lhs.impl.scopeNames - let rscopeNames = rhs.impl.scopeNames + let lscopeNames = lhs.scopes.names + let rscopeNames = rhs.scopes.names guard lscopeNames == rscopeNames else { return false } for name in lscopeNames { - let lscope = lhs.scoped(on: name) - let rscope = rhs.scoped(on: name) + let lscope = lhs.scopes[name] + let rscope = rhs.scopes[name] guard lscope == rscope else { return false } @@ -880,15 +970,40 @@ extension Row { } } -// CustomStringConvertible +// CustomStringConvertible & CustomDebugStringConvertible extension Row { /// :nodoc: public var description: String { - return "" + return "[" + + map { (column, dbValue) in "\(column):\(dbValue)" }.joined(separator: " ") + + "]" + } + + /// :nodoc: + public var debugDescription: String { + return debugDescription(level: 0) + } + + private func debugDescription(level: Int) -> String { + if level == 0 && self == self.unadapted { + return description + } + let prefix = repeatElement(" ", count: level + 1).joined(separator: "") + var str = "" + if level == 0 { + str = "▿ " + description + let unadapted = self.unadapted + if self != unadapted { + str += "\n" + prefix + "unadapted: " + unadapted.description + } + } else { + str = description + } + for (name, scopedRow) in scopes.sorted(by: { $0.name < $1.name }) { + str += "\n" + prefix + "- " + name + ": " + scopedRow.debugDescription(level: level + 1) + } + + return str } } @@ -927,6 +1042,134 @@ extension RowIndex { } } +// MARK: - Row.ScopesView + +extension Row { + /// A view of the scopes defined by row adapters. It is a collection of + /// tuples made of a scope name and a scoped row, which behaves like a + /// dictionary. + /// + /// For example: + /// + /// // Define a tree of nested scopes + /// let adapter = ScopeAdapter([ + /// "foo": RangeRowAdapter(0..<1), + /// "bar": RangeRowAdapter(1..<2).addingScopes([ + /// "baz" : RangeRowAdapter(2..<3)])]) + /// + /// // Fetch + /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" + /// let row = try Row.fetchOne(db, sql, adapter: adapter)! + /// + /// row.scopes.count // 2 + /// row.scopes.names // ["foo", "bar"] + /// + /// row.scopes["foo"] // [foo:1] + /// row.scopes["bar"] // [bar:2] + /// row.scopes["baz"] // nil + public struct ScopesView: Collection { + public typealias Index = Dictionary.Index + private let row: Row + private let scopes: [String: LayoutedRowAdapter] + + /// The scopes defined on this row. + public var names: Dictionary.Keys { + return scopes.keys + } + + init() { + self.init(row: Row(), scopes: [:]) + } + + init(row: Row, scopes: [String: LayoutedRowAdapter]) { + self.row = row + self.scopes = scopes + } + + /// :nodoc: + public var startIndex: Index { + return scopes.startIndex + } + + /// :nodoc: + public var endIndex: Index { + return scopes.endIndex + } + + /// :nodoc: + public func index(after i: Index) -> Index { + return scopes.index(after: i) + } + + /// :nodoc: + public subscript(position: Index) -> (name: String, row: Row) { + let (name, adapter) = scopes[position] + return (name: name, row: Row(base: row, adapter: adapter)) + } + + /// Returns the row associated with the given scope, or nil if the + /// scope is not defined. + public subscript(_ name: String) -> Row? { + guard let adapter = scopes[name] else { + return nil + } + return Row(base: row, adapter: adapter) + } + } +} + +// MARK: - Row.ScopesTreeView + +extension Row { + + /// A view on the scopes tree defined by row adapters. + /// + /// For example: + /// + /// // Define a tree of nested scopes + /// let adapter = ScopeAdapter([ + /// "foo": RangeRowAdapter(0..<1), + /// "bar": RangeRowAdapter(1..<2).addingScopes([ + /// "baz" : RangeRowAdapter(2..<3)])]) + /// + /// // Fetch + /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" + /// let row = try Row.fetchOne(db, sql, adapter: adapter)! + /// + /// row.scopesTree.names // ["foo", "bar", "baz"] + /// + /// row.scopesTree["foo"] // [foo:1] + /// row.scopesTree["bar"] // [bar:2] + /// row.scopesTree["baz"] // [baz:3] + public struct ScopesTreeView { + let scopes: ScopesView + + /// The scopes defined on this row, recursively. + public var names: Set { + var names = Set() + for (name, row) in scopes { + names.insert(name) + names.formUnion(row.scopesTree.names) + } + return names + } + + /// Returns the row associated with the given scope, by performing a + /// breadth-first search in this row's scopes and the scopes of its + /// scoped rows, recursively. + public subscript(_ name: String) -> Row? { + var fifo = Array(scopes) + while !fifo.isEmpty { + let scope = fifo.removeFirst() + if scope.name == name { + return scope.row + } + fifo.append(contentsOf: scope.row.scopes) + } + return nil + } + } +} // MARK: - RowImpl @@ -934,6 +1177,7 @@ extension RowIndex { protocol RowImpl { var count: Int { get } var isFetched: Bool { get } + var scopes: Row.ScopesView { get } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue func fastValue(atUncheckedIndex index: Int) -> Value func fastValue(atUncheckedIndex index: Int) -> Value? @@ -945,14 +1189,29 @@ protocol RowImpl { // leftmost column that matches *name*. func index(ofColumn name: String) -> Int? - func scoped(on name: String) -> Row? - var scopeNames: Set { get } - // row.impl is guaranteed to be self. - func copy(_ row: Row) -> Row + func unscopedRow(_ row: Row) -> Row + func unadaptedRow(_ row: Row) -> Row + func copiedRow(_ row: Row) -> Row } extension RowImpl { + func copiedRow(_ row: Row) -> Row { + return row + } + + func unscopedRow(_ row: Row) -> Row { + return row + } + + func unadaptedRow(_ row: Row) -> Row { + return row + } + + var scopes: Row.ScopesView { + return Row.ScopesView() + } + func hasNull(atUncheckedIndex index:Int) -> Bool { return databaseValue(atUncheckedIndex: index).isNull } @@ -1008,18 +1267,6 @@ private struct ArrayRowImpl : RowImpl { let lowercaseName = name.lowercased() return columns.index { (column, _) in column.lowercased() == lowercaseName } } - - func scoped(on name: String) -> Row? { - return nil - } - - var scopeNames: Set { - return [] - } - - func copy(_ row: Row) -> Row { - return row - } } @@ -1060,18 +1307,6 @@ private struct StatementCopyRowImpl : RowImpl { let lowercaseName = name.lowercased() return columnNames.index { $0.lowercased() == lowercaseName } } - - func scoped(on name: String) -> Row? { - return nil - } - - var scopeNames: Set { - return [] - } - - func copy(_ row: Row) -> Row { - return row - } } @@ -1142,20 +1377,11 @@ private struct StatementRowImpl : RowImpl { return lowercaseColumnIndexes[name.lowercased()] } - func scoped(on name: String) -> Row? { - return nil - } - - var scopeNames: Set { - return [] - } - - func copy(_ row: Row) -> Row { + func copiedRow(_ row: Row) -> Row { return Row(copiedFromSQLiteStatement: sqliteStatement, statementRef: statementRef) } } - /// See Row.init() private struct EmptyRowImpl : RowImpl { var count: Int { @@ -1184,16 +1410,4 @@ private struct EmptyRowImpl : RowImpl { func index(ofColumn name: String) -> Int? { return nil } - - func scoped(on name: String) -> Row? { - return nil - } - - var scopeNames: Set { - return [] - } - - func copy(_ row: Row) -> Row { - return row - } } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index fdc7775ee..f322bf4d2 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -14,10 +14,10 @@ import Foundation /// "c": adapters[2], /// "d": adapters[3]]) /// let row = try Row.fetchOne(db, sql, adapter: adapter) -/// row.scoped(on: "a") // [1] -/// row.scoped(on: "b") // [2, 3, 4] -/// row.scoped(on: "c") // [5, 6] -/// row.scoped(on: "d") // [7, 8] +/// row.scopes["a"] // [1] +/// row.scopes["b"] // [2, 3, 4] +/// row.scopes["c"] // [5, 6] +/// row.scopes["d"] // [7, 8] public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] { guard !columnCounts.isEmpty else { // Identity adapter @@ -77,7 +77,7 @@ public struct LayoutedColumnMapping { /// } /// } /// - /// // + /// // [foo:"foo" bar: "bar"] /// try Row.fetchOne(db, "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter()) public init(layoutColumns: S) where S.Iterator.Element == (Int, String) { self.layoutColumns = Array(layoutColumns) @@ -173,14 +173,12 @@ public protocol RowLayout { extension SelectStatement : RowLayout { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public var layoutColumns: [(Int, String)] { return Array(columnNames.enumerated()) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func layoutIndex(ofColumn name: String) -> Int? { return index(ofColumn: name) @@ -202,7 +200,7 @@ extension SelectStatement : RowLayout { /// let adapter = SuffixRowAdapter(fromIndex: 2) /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" /// -/// // +/// // [baz:3] /// try Row.fetchOne(db, sql, adapter: adapter) public protocol RowAdapter { @@ -225,7 +223,7 @@ public protocol RowAdapter { /// } /// } /// - /// // + /// // [foo:1] /// try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter()) func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter } @@ -239,7 +237,11 @@ extension RowAdapter { /// - parameter scopes: A dictionary that maps scope names to /// row adapters. public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter { - return ScopeAdapter(base: self, scopes: scopes) + if scopes.isEmpty { + return self + } else { + return ScopeAdapter(base: self, scopes: scopes) + } } } @@ -255,7 +257,6 @@ public struct EmptyRowAdapter: RowAdapter { public init() { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return LayoutedColumnMapping(layoutColumns: []) @@ -267,7 +268,7 @@ public struct EmptyRowAdapter: RowAdapter { /// let adapter = ColumnMapping(["foo": "bar"]) /// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz" /// -/// // +/// // [foo:"bar"] /// try Row.fetchOne(db, sql, adapter: adapter) public struct ColumnMapping : RowAdapter { /// A dictionary from mapped column names to column names in a base row. @@ -280,7 +281,6 @@ public struct ColumnMapping : RowAdapter { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { let layoutColumns = try mapping @@ -302,7 +302,7 @@ public struct ColumnMapping : RowAdapter { /// let adapter = SuffixRowAdapter(fromIndex: 2) /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" /// -/// // +/// // [baz:3] /// try Row.fetchOne(db, sql, adapter: adapter) public struct SuffixRowAdapter : RowAdapter { /// The suffix index @@ -318,7 +318,6 @@ public struct SuffixRowAdapter : RowAdapter { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index)) @@ -330,7 +329,7 @@ public struct SuffixRowAdapter : RowAdapter { /// let adapter = RangeRowAdapter(1..<3) /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux" /// -/// // +/// // [bar:2 baz:3] /// try Row.fetchOne(db, sql, adapter: adapter) public struct RangeRowAdapter : RowAdapter { /// The range @@ -349,7 +348,6 @@ public struct RangeRowAdapter : RowAdapter { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range]) @@ -372,10 +370,10 @@ public struct RangeRowAdapter : RowAdapter { /// let row = try Row.fetchOne(db, sql, adapter: adapter)! /// /// // Scoped rows: -/// if let fooRow = row.scoped(on: "foo") { +/// if let fooRow = row.scopes["foo"] { /// fooRow["value"] // "foo" /// } -/// if let barRow = row.scopeed(on: "bar") { +/// if let barRow = row.scopes["bar"] { /// barRow["value"] // "bar" /// } public struct ScopeAdapter : RowAdapter { @@ -392,8 +390,8 @@ public struct ScopeAdapter : RowAdapter { /// /// let adapter = ScopeAdapter(["suffix": SuffixRowAdapter(fromIndex: 1)]) /// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)! - /// row // [1, 2, 3] - /// row.scoped(on: "suffix") // [2, 3] + /// row // [1, 2, 3] + /// row.scopes["suffix"] // [2, 3] /// /// - parameter scopes: A dictionary that maps scope names to /// row adapters. @@ -409,8 +407,8 @@ public struct ScopeAdapter : RowAdapter { /// let baseAdapter = RangeRowAdapter(0..<1) /// let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)]) /// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)! - /// row // [1] - /// row.scoped(on: "initial") // [2, 3] + /// row // [1] + /// row.scopes["initial"] // [2, 3] /// /// If the base adapter already defines scopes, the given scopes replace /// eventual existing scopes with the same name. @@ -427,7 +425,6 @@ public struct ScopeAdapter : RowAdapter { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { let layoutedAdapter = try base.layoutedAdapter(from: layout) @@ -459,7 +456,7 @@ struct ChainedAdapter : RowAdapter { extension Row { /// Creates a row from a base row and a statement adapter convenience init(base: Row, adapter: LayoutedRowAdapter) { - self.init(impl: AdapterRowImpl(base: base, adapter: adapter)) + self.init(impl: AdaptedRowImpl(base: base, adapter: adapter)) } /// Returns self if adapter is nil @@ -471,7 +468,7 @@ extension Row { } } -struct AdapterRowImpl : RowImpl { +struct AdaptedRowImpl : RowImpl { let base: Row let adapter: LayoutedRowAdapter let mapping: LayoutedColumnMapping @@ -490,6 +487,10 @@ struct AdapterRowImpl : RowImpl { return base.isFetched } + var scopes: Row.ScopesView { + return Row.ScopesView(row: base, scopes: adapter.scopes) + } + func hasNull(atUncheckedIndex index: Int) -> Bool { let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) return base.impl.hasNull(atUncheckedIndex: mappedIndex) @@ -523,18 +524,16 @@ struct AdapterRowImpl : RowImpl { return mapping.layoutIndex(ofColumn: name) } - func scoped(on name: String) -> Row? { - guard let adapter = adapter.scopes[name] else { - return nil - } - return Row(base: base, adapter: adapter) - } - - var scopeNames: Set { - return Set(adapter.scopes.keys) - } - - func copy(_ row: Row) -> Row { + func copiedRow(_ row: Row) -> Row { return Row(base: base.copy(), adapter: adapter) } + + func unscopedRow(_ row: Row) -> Row { + assert(adapter.mapping.scopes.isEmpty) + return Row(base: base, adapter: adapter.mapping) + } + + func unadaptedRow(_ row: Row) -> Row { + return base.unadapted + } } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 129870a83..9d9a44066 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -61,27 +61,27 @@ final class SerializedDatabase { // // 1. A database is invoked from some queue like the main queue: // - // dbQueue.inDatabase { db in // <-- we're here + // serializedDatabase.sync { db in // <-- we're here // } // // 2. A database is invoked in a reentrant way: // - // dbQueue.inDatabase { db in - // dbQueue.inDatabase { db in // <-- we're here + // serializedDatabase.sync { db in + // serializedDatabase.sync { db in // <-- we're here // } // } // // 3. A database in invoked from another database: // - // dbQueue1.inDatabase { db1 in - // dbQueue2.inDatabase { db2 in // <-- we're here + // serializedDatabase1.sync { db1 in + // serializedDatabase2.sync { db2 in // <-- we're here // } // } guard let watchdog = SchedulingWatchdog.current else { // Case 1 return try queue.sync { - defer { preconditionNoTransactionLeft(db) } + defer { preconditionNoUnsafeTransactionLeft(db) } return try block(db) } } @@ -92,7 +92,7 @@ final class SerializedDatabase { // Case 3 return try queue.sync { try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) { - defer { preconditionNoTransactionLeft(db) } + defer { preconditionNoUnsafeTransactionLeft(db) } return try block(db) } } @@ -107,42 +107,60 @@ final class SerializedDatabase { // // 1. A database is invoked from some queue like the main queue: // - // dbQueue.inDatabase { db in // <-- we're here + // serializedDatabase.reentrantSync { db in // <-- we're here // } // // 2. A database is invoked in a reentrant way: // - // dbQueue.inDatabase { db in - // dbQueue.inDatabase { db in // <-- we're here + // serializedDatabase.reentrantSync { db in + // serializedDatabase.reentrantSync { db in // <-- we're here // } // } // // 3. A database in invoked from another database: // - // dbQueue1.inDatabase { db1 in - // dbQueue2.inDatabase { db2 in // <-- we're here + // serializedDatabase1.reentrantSync { db1 in + // serializedDatabase2.reentrantSync { db2 in // <-- we're here // } // } guard let watchdog = SchedulingWatchdog.current else { // Case 1 return try queue.sync { - defer { preconditionNoTransactionLeft(db) } - return try block(db) + // Since we are reentrant, a transaction may already be opened. + // In this case, don't check for unsafe transaction at the end. + if db.isInsideTransaction { + return try block(db) + } else { + defer { preconditionNoUnsafeTransactionLeft(db) } + return try block(db) + } } } // Case 2 if watchdog.allows(db) { - defer { preconditionNoTransactionLeft(db) } - return try block(db) + // Since we are reentrant, a transaction may already be opened. + // In this case, don't check for unsafe transaction at the end. + if db.isInsideTransaction { + return try block(db) + } else { + defer { preconditionNoUnsafeTransactionLeft(db) } + return try block(db) + } } // Case 3 return try queue.sync { try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) { - defer { preconditionNoTransactionLeft(db) } - return try block(db) + // Since we are reentrant, a transaction may already be opened. + // In this case, don't check for unsafe transaction at the end. + if db.isInsideTransaction { + return try block(db) + } else { + defer { preconditionNoUnsafeTransactionLeft(db) } + return try block(db) + } } } } @@ -151,7 +169,7 @@ final class SerializedDatabase { func async(_ block: @escaping (Database) -> Void) { queue.async { block(self.db) - self.preconditionNoTransactionLeft(self.db) + self.preconditionNoUnsafeTransactionLeft(self.db) } } @@ -174,7 +192,7 @@ final class SerializedDatabase { } /// Fatal error if a transaction has been left opened. - func preconditionNoTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) { + private func preconditionNoUnsafeTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) { GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message, file: file, line: line) } } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index e0bf95f60..cb3e30cd7 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -222,6 +222,8 @@ protocol AuthorizedStatement { // https://bugs.swift.org/browse/SR-2347 // // We work around SR-2347 with this internal protocol. + // + // TODO: hasn't this bug been fixed in Swift 4.2? https://github.com/apple/swift/blob/master/CHANGELOG.md#swift-42 init( database: Database, statementStart: UnsafePointer, @@ -286,22 +288,14 @@ extension AuthorizedStatement { /// /// You create SelectStatement with the Database.makeSelectStatement() method: /// -/// try dbQueue.inDatabase { db in -/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?") +/// try dbQueue.read { db in +/// 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])! /// } -public final class SelectStatement : Statement { - /// :nodoc: - @available(*, deprecated, renamed:"DatabaseRegion") - public typealias SelectionInfo = DatabaseRegion - - /// :nodoc: - @available(*, deprecated, renamed:"fetchedRegion") - public var selectionInfo: DatabaseRegion { return fetchedRegion } - +public final class SelectStatement : Statement { /// The database region that the statement looks into. - public private(set) var fetchedRegion: DatabaseRegion + public private(set) var databaseRegion: DatabaseRegion /// Creates a prepared statement. /// @@ -322,7 +316,7 @@ public final class SelectStatement : Statement { prepFlags: Int32, authorizer: StatementCompilationAuthorizer) throws { - self.fetchedRegion = DatabaseRegion() + self.databaseRegion = DatabaseRegion() try super.init( database: database, statementStart: statementStart, @@ -332,7 +326,7 @@ public final class SelectStatement : Statement { GRDBPrecondition(authorizer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.") GRDBPrecondition(authorizer.transactionEffect == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.") - self.fetchedRegion = authorizer.region + self.databaseRegion = authorizer.databaseRegion } /// The number of columns in the resulting rows. @@ -380,8 +374,8 @@ extension SelectStatement: AuthorizedStatement { } /// A cursor that iterates a database statement without producing any value. /// For example: /// -/// try dbQueue.inDatabase { db in -/// let statement = db.makeSelectStatement("SELECT * FROM players") +/// try dbQueue.read { db in +/// let statement = db.makeSelectStatement("SELECT * FROM player") /// let cursor: StatementCursor = statement.cursor() /// } public final class StatementCursor: Cursor { @@ -420,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 @@ -592,10 +586,10 @@ extension UpdateStatement: AuthorizedStatement { } /// let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar" /// let row = try Row.fetchOne(db, sql, arguments: [1, 2, "bar"] + ["foo": "foo"])! /// print(row) -/// // Prints +/// // 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 @@ -911,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/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 208150c5a..7a2750e43 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -1,3 +1,6 @@ +#if os(Linux) + import Glibc +#endif #if SWIFT_PACKAGE import CSQLite #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER @@ -18,7 +21,7 @@ protocol StatementAuthorizer : class { /// A class that gathers information about one statement during its compilation. final class StatementCompilationAuthorizer : StatementAuthorizer { /// What this statements reads - var region = DatabaseRegion() + var databaseRegion = DatabaseRegion() /// What this statements writes var databaseEventKinds: [DatabaseEventKind] = [] @@ -66,10 +69,10 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK } if columnName.isEmpty { // SELECT COUNT(*) FROM table - region.formUnion(DatabaseRegion(table: tableName)) + databaseRegion.formUnion(DatabaseRegion(table: tableName)) } else { // SELECT column FROM table - region.formUnion(DatabaseRegion(table: tableName, columns: [columnName])) + databaseRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName])) } return SQLITE_OK @@ -135,7 +138,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK } guard let cString2 = cString2 else { return SQLITE_OK } if sqlite3_stricmp(cString2, "COUNT") == 0 { - region = .fullDatabase + databaseRegion = .fullDatabase } return SQLITE_OK diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index f0ade5e43..499c39dd9 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -74,8 +74,8 @@ extension StatementColumnConvertible { /// A cursor of database values extracted from a single column. /// For example: /// -/// try dbQueue.inDatabase { db in -/// let names: ColumnCursor = try String.fetchCursor(db, "SELECT name FROM players") +/// try dbQueue.read { db in +/// let names: ColumnCursor = try String.fetchCursor(db, "SELECT name FROM player") /// while let name = names.next() { // String /// print(name) /// } @@ -120,8 +120,8 @@ public final class ColumnCursor = try Optional.fetchCursor(db, "SELECT email FROM players") +/// try dbQueue.read { db in +/// let emails: NullableColumnCursor = try Optional.fetchCursor(db, "SELECT email FROM player") /// while let email = emails.next() { // String? /// print(email ?? "") /// } @@ -225,64 +225,6 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { } } -extension DatabaseValueConvertible where Self: StatementColumnConvertible { - - // MARK: Fetching From Request - - /// Returns a cursor over values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try String.fetchCursor(db, request) // Cursor of String - /// while let name = try names.next() { // String - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - request: A fetch request. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: Request) throws -> ColumnCursor { - let (statement, adapter) = try request.prepare(db) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try String.fetchAll(db, request) // [String] - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] { - let (statement, adapter) = try request.prepare(db) - return try fetchAll(statement, adapter: adapter) - } - - /// Returns a single value fetched from a fetch request. - /// - /// The result is nil if the query returns no row, or if no value can be - /// extracted from the first row. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let name = try String.fetchOne(db, request) // String? - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? { - let (statement, adapter) = try request.prepare(db) - return try fetchOne(statement, adapter: adapter) - } -} - extension DatabaseValueConvertible where Self: StatementColumnConvertible { // MARK: Fetching From SQL @@ -307,7 +249,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor { - return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns an array of values fetched from an SQL query. @@ -322,7 +264,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { - return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns a single value fetched from an SQL query. @@ -337,10 +279,119 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { - return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } } +extension DatabaseValueConvertible where Self: StatementColumnConvertible { + + // MARK: Fetching From FetchRequest + + /// Returns a cursor over values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try String.fetchCursor(db, request) // Cursor of String + /// while let name = try names.next() { // String + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: A cursor over fetched values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: R) throws -> ColumnCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + /// Returns an array of values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try String.fetchAll(db, request) // [String] + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An array of values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: R) throws -> [Self] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } + + /// Returns a single value fetched from a fetch request. + /// + /// let request = Player.filter(key: 1).select(Column("name")) + /// let name = try String.fetchOne(db, request) // String? + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An optional value. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchOne(_ db: Database, _ request: R) throws -> Self? { + let (statement, adapter) = try request.prepare(db) + return try fetchOne(statement, adapter: adapter) + } +} + +extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible { + + // MARK: Fetching Values + + /// A cursor over fetched values. + /// + /// let request: ... // Some TypedRequest that fetches String + /// let strings = try request.fetchCursor(db) // Cursor of String + /// while let string = try strings.next() { // String + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> ColumnCursor { + return try RowDecoder.fetchCursor(db, self) + } + + /// An array of fetched values. + /// + /// let request: ... // Some TypedRequest that fetches String + /// let strings = try request.fetchAll(db) // [String] + /// + /// - parameter db: A database connection. + /// - returns: An array of values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder] { + return try RowDecoder.fetchAll(db, self) + } + + /// The first fetched value. + /// + /// The result is nil if the request returns no row, or if no value can be + /// extracted from the first row. + /// + /// let request: ... // Some TypedRequest that fetches String + /// let string = try request.fetchOne(db) // String? + /// + /// - parameter db: A database connection. + /// - returns: An optional value. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder? { + return try RowDecoder.fetchOne(db, self) + } +} /// Swift's Optional comes with built-in methods that allow to fetch cursors /// and arrays of optional DatabaseValueConvertible: @@ -396,48 +447,6 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv } } -extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible { - - // MARK: Fetching From Request - - /// Returns a cursor over optional values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try Optional.fetchCursor(db, request) // Cursor of String? - /// while let name = try names.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - requet: A fetch request. - /// - returns: A cursor over fetched optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableColumnCursor { - let (statement, adapter) = try request.prepare(db) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of optional values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try Optional.fetchAll(db, request) // [String?] - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] { - let (statement, adapter) = try request.prepare(db) - return try fetchAll(statement, adapter: adapter) - } -} - extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible { // MARK: Fetching From SQL @@ -462,7 +471,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor { - return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns an array of optional values fetched from an SQL query. @@ -477,6 +486,86 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { - return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + } +} + +extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible { + + // MARK: Fetching From FetchRequest + + /// Returns a cursor over optional values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try Optional.fetchCursor(db, request) // Cursor of String? + /// while let name = try names.next() { // String? + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: A cursor over fetched optional values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: R) throws -> NullableColumnCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + /// Returns an array of optional values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try Optional.fetchAll(db, request) // [String?] + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An array of optional values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: R) throws -> [Wrapped?] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } +} + +extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible { + + // MARK: Fetching Optional values + + /// A cursor over fetched optional values. + /// + /// let request: ... // Some TypedRequest that fetches Optional + /// let strings = try request.fetchCursor(db) // Cursor of String? + /// while let string = try strings.next() { // String? + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> NullableColumnCursor { + return try Optional.fetchCursor(db, self) + } + + /// An array of fetched optional values. + /// + /// let request: ... // Some TypedRequest that fetches Optional + /// let strings = try request.fetchAll(db) // [String?] + /// + /// - parameter db: A database connection. + /// - returns: An array of values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { + return try Optional.fetchAll(db, self) } } diff --git a/GRDB/Core/Support/CoreGraphics/CGFloat.swift b/GRDB/Core/Support/CoreGraphics/CGFloat.swift index 7359eb3fd..0b7fb1f3c 100644 --- a/GRDB/Core/Support/CoreGraphics/CGFloat.swift +++ b/GRDB/Core/Support/CoreGraphics/CGFloat.swift @@ -1,3 +1,4 @@ +#if !os(Linux) import CoreGraphics /// CGFloat adopts DatabaseValueConvertible @@ -16,3 +17,4 @@ extension CGFloat : DatabaseValueConvertible { return CGFloat(double) } } +#endif diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 7d2db6f00..92e0b9288 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -58,17 +58,11 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn /// Creates a DatabaseDateComponents from a DateComponents and a format. /// - /// The result is nil if and only if *dateComponents* is nil. - /// /// - parameters: /// - dateComponents: An optional DateComponents. /// - format: The format used for storing the date components in /// the database. - /// - returns: An optional DatabaseDateComponents. - public init?(_ dateComponents: DateComponents?, format: Format) { - guard let dateComponents = dateComponents else { - return nil - } + public init(_ dateComponents: DateComponents, format: Format) { self.format = format self.dateComponents = dateComponents } @@ -81,9 +75,14 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. public init(sqliteStatement: SQLiteStatement, index: Int32) { - let cString = UnsafePointer(OpaquePointer(sqlite3_column_text(sqliteStatement, index)!)) + guard let cString = sqlite3_column_text(sqliteStatement, index) else { + fatalError("could not convert database value \(DatabaseValue(sqliteStatement: sqliteStatement, index: index)) to DatabaseDateComponents") + } let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen - guard let components = SQLiteDateParser().components(cString: cString, length: length) else { + let optionalComponents = cString.withMemoryRebound(to: Int8.self, capacity: length + 1 /* trailing \0 */) { cString in + SQLiteDateParser().components(cString: cString, length: length) + } + guard let components = optionalComponents else { fatalError("could not convert database value \(String(cString: cString)) to DatabaseDateComponents") } self.dateComponents = components.dateComponents @@ -100,7 +99,7 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn let year = dateComponents.year ?? 0 let month = dateComponents.month ?? 1 let day = dateComponents.day ?? 1 - dateString = NSString(format: "%04d-%02d-%02d", year, month, day) as String + dateString = String(format: "%04d-%02d-%02d", year, month, day) default: dateString = nil } @@ -110,18 +109,18 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn case .YMD_HM, .HM: let hour = dateComponents.hour ?? 0 let minute = dateComponents.minute ?? 0 - timeString = NSString(format: "%02d:%02d", hour, minute) as String + timeString = String(format: "%02d:%02d", hour, minute) case .YMD_HMS, .HMS: let hour = dateComponents.hour ?? 0 let minute = dateComponents.minute ?? 0 let second = dateComponents.second ?? 0 - timeString = NSString(format: "%02d:%02d:%02d", hour, minute, second) as String + timeString = String(format: "%02d:%02d:%02d", hour, minute, second) case .YMD_HMSS, .HMSS: let hour = dateComponents.hour ?? 0 let minute = dateComponents.minute ?? 0 let second = dateComponents.second ?? 0 let nanosecond = dateComponents.nanosecond ?? 0 - timeString = NSString(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) as String + timeString = String(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) default: timeString = nil } diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index 78cdbbd30..c5e1e1d6b 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -5,6 +5,7 @@ import Foundation import SQLite3 #endif +#if !os(Linux) /// NSDate is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. extension NSDate : DatabaseValueConvertible { @@ -31,6 +32,7 @@ extension NSDate : DatabaseValueConvertible { return cast(date) } } +#endif /// Date is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. diff --git a/GRDB/Core/Support/Foundation/NSData.swift b/GRDB/Core/Support/Foundation/NSData.swift index 28a7ae8ba..8bd9d2ecf 100644 --- a/GRDB/Core/Support/Foundation/NSData.swift +++ b/GRDB/Core/Support/Foundation/NSData.swift @@ -1,3 +1,4 @@ +#if !os(Linux) import Foundation /// NSData is convertible to and from DatabaseValue. @@ -17,3 +18,4 @@ extension NSData : DatabaseValueConvertible { return cast(data) } } +#endif diff --git a/GRDB/Core/Support/Foundation/NSNumber.swift b/GRDB/Core/Support/Foundation/NSNumber.swift index 2a00c1618..2caf60868 100644 --- a/GRDB/Core/Support/Foundation/NSNumber.swift +++ b/GRDB/Core/Support/Foundation/NSNumber.swift @@ -1,3 +1,4 @@ +#if !os(Linux) import Foundation private let integerRoundingBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) @@ -65,3 +66,4 @@ extension NSNumber : DatabaseValueConvertible { } } } +#endif diff --git a/GRDB/Core/Support/Foundation/NSString.swift b/GRDB/Core/Support/Foundation/NSString.swift index 577725992..d5455bed4 100644 --- a/GRDB/Core/Support/Foundation/NSString.swift +++ b/GRDB/Core/Support/Foundation/NSString.swift @@ -1,3 +1,4 @@ +#if !os(Linux) import Foundation /// NSString adopts DatabaseValueConvertible @@ -16,3 +17,4 @@ extension NSString : DatabaseValueConvertible { return self.init(string: string) } } +#endif diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 8ac84c250..ba2f83814 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -11,7 +11,7 @@ class SQLiteDateParser { var hour: Int32 = 0 var minute: Int32 = 0 var second: Int32 = 0 - var nanosecond = ContiguousArray.init(repeating: 0, count: 10) // 9 digits, and trailing \0 + var nanosecond = ContiguousArray(repeating: 0, count: 10) // 9 digits, and trailing \0 } func components(from dateString: String) -> DatabaseDateComponents? { @@ -55,7 +55,7 @@ class SQLiteDateParser { withUnsafeMutablePointer(to: &parserComponents.second) { secondP in parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in withVaList([yearP, monthP, dayP, hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in - vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%10s", pointer) + vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%9s", pointer) } } } @@ -100,7 +100,7 @@ class SQLiteDateParser { withUnsafeMutablePointer(to: &parserComponents.second) { secondP in parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in withVaList([hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in - vsscanf(cString, "%2d:%2d:%2d.%10s", pointer) + vsscanf(cString, "%2d:%2d:%2d.%9s", pointer) } } } diff --git a/GRDB/Core/Support/Foundation/URL.swift b/GRDB/Core/Support/Foundation/URL.swift index 516dcc1fb..4cc95b1b4 100644 --- a/GRDB/Core/Support/Foundation/URL.swift +++ b/GRDB/Core/Support/Foundation/URL.swift @@ -1,5 +1,6 @@ import Foundation +#if !os(Linux) /// NSURL stores its absoluteString in the database. extension NSURL : DatabaseValueConvertible { @@ -17,6 +18,7 @@ extension NSURL : DatabaseValueConvertible { return cast(URL(string: string)) } } +#endif /// URL stores its absoluteString in the database. extension URL : DatabaseValueConvertible { } diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 5d6d7cfee..7deb4e2cf 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -1,5 +1,6 @@ import Foundation +#if !os(Linux) /// NSUUID adopts DatabaseValueConvertible extension NSUUID : DatabaseValueConvertible { @@ -18,8 +19,9 @@ extension NSUUID : DatabaseValueConvertible { return nil } return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self)) - } + } } +#endif /// UUID adopts DatabaseValueConvertible extension UUID : DatabaseValueConvertible { } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 00df65ec3..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() @@ -874,12 +873,6 @@ public enum DatabaseEventKind { return DatabaseRegion(table: tableName, columns: updatedColumnNames) } } - - /// :nodoc: - @available(*, deprecated, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead") - public func impacts(_ region: DatabaseRegion) -> Bool { - return region.isModified(byEventsOfKind: self) - } } extension DatabaseEventKind { 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 883f1fbc0..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 /// } @@ -160,7 +160,7 @@ /// class MyTokenizer : FTS5CustomTokenizer { ... } /// dbPool.add(tokenizer: MyTokenizer.self) public func add(tokenizer: Tokenizer.Type) { - write { db in + writeWithoutTransaction { db in db.add(tokenizer: Tokenizer.self) } } 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-90-1.swift b/GRDB/Legacy/Fixits-0-90-1.swift index 681937a45..cb886e4de 100644 --- a/GRDB/Legacy/Fixits-0-90-1.swift +++ b/GRDB/Legacy/Fixits-0-90-1.swift @@ -2,7 +2,7 @@ extension Row { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") - public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } + public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } } @@ -11,7 +11,7 @@ extension DatabaseValueConvertible { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") - public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } + public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } } @@ -20,7 +20,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") - public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } + public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } } @@ -30,16 +30,16 @@ extension QueryInterfaceRequest { public func fetch(_ db: Database) -> Any { preconditionFailure() } } -extension RowConvertible { +extension FetchableRecord { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") - public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } + public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } } -extension RowConvertible where Self: TableMapping { +extension FetchableRecord where Self: TableRecord { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ db: Database) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") diff --git a/GRDB/Legacy/Fixits-0.109.0.swift b/GRDB/Legacy/Fixits-0.109.0.swift index d26a5d501..1b9dcc727 100644 --- a/GRDB/Legacy/Fixits-0.109.0.swift +++ b/GRDB/Legacy/Fixits-0.109.0.swift @@ -1,4 +1,4 @@ -extension Request { - @available(*, unavailable, renamed:"asRequest(of:)") - public func bound(to type: T.Type) -> AnyTypedRequest { preconditionFailure() } +extension FetchRequest { + @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 new file mode 100644 index 000000000..6ec160f41 --- /dev/null +++ b/GRDB/Legacy/Fixits-3.0.swift @@ -0,0 +1,85 @@ +/// :nodoc: +@available(*, unavailable, renamed:"FetchRequest") +public typealias Request = FetchRequest + +/// :nodoc: +@available(*, unavailable, renamed:"FetchableRecord") +public typealias RowConvertible = FetchableRecord + +/// :nodoc: +@available(*, unavailable, renamed:"TableRecord") +public typealias TableMapping = TableRecord + +/// :nodoc: +@available(*, unavailable, renamed:"MutablePersistableRecord") +public typealias MutablePersistable = MutablePersistableRecord + +/// :nodoc: +@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") + public func columnCount(in tableName: String) throws -> Int { preconditionFailure() } +} + +extension SelectStatement { + /// :nodoc: + @available(*, unavailable, renamed:"DatabaseRegion") + public typealias SelectionInfo = DatabaseRegion + + /// :nodoc: + @available(*, unavailable, renamed:"databaseRegion") + public var selectionInfo: DatabaseRegion { preconditionFailure() } + + /// :nodoc: + @available(*, unavailable, renamed:"databaseRegion") + public var fetchedRegion: DatabaseRegion { preconditionFailure() } +} + +extension DatabaseEventKind { + /// :nodoc: + @available(*, unavailable, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead") + public func impacts(_ region: DatabaseRegion) -> Bool { preconditionFailure() } +} + +extension Record { + /// :nodoc: + @available(*, unavailable, renamed: "hasDatabaseChanges") + public var hasPersistentChangedValues: Bool { preconditionFailure() } + + /// :nodoc: + @available(*, unavailable, renamed: "databaseChanges") + public var persistentChangedValues: [String: DatabaseValue?] { preconditionFailure() } +} + +@available(*, unavailable, message: "Use changes methods defined on the MutablePersistableRecord protocol: databaseEquals(_:), databaseChanges(from:), updateChanges(from:)") +public final class RecordBox: Record { } + +extension MutablePersistableRecord { + /// :nodoc: + @available(*, unavailable, renamed: "databaseEquals") + public func databaseEqual(_ record: Self) -> Bool { preconditionFailure() } +} + +extension Row { + /// :nodoc: + @available(*, unavailable, message: "Use row.scopes.names instead") + var scopeNames: Set { preconditionFailure() } + + /// :nodoc: + @available(*, unavailable, message: "Use row.scopes[name] instead") + public func scoped(on name: String) -> Row? { preconditionFailure() } +} + +extension FetchRequest { + + /// :nodoc: + @available(*, unavailable, renamed:"databaseRegion(_:)") + public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { preconditionFailure() } +} 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 b6de0e654..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 @@ -125,7 +128,7 @@ public struct DatabaseMigrator { /// migrations should apply. /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter) throws { - try writer.write { db in + try writer.writeWithoutTransaction { db in try setupMigrations(db) try runMigrations(db) } @@ -140,12 +143,17 @@ public struct DatabaseMigrator { /// - targetIdentifier: The identifier of a registered migration. /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws { - try writer.write { db in + try writer.writeWithoutTransaction { db in try setupMigrations(db) try runMigrations(db, upTo: targetIdentifier) } } + /// Returns the set of applied migration identifiers. + public func appliedMigrations(in reader: DatabaseReader) throws -> Set { + return try reader.read { try appliedIdentifiers($0) } + } + // MARK: - Non public diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift new file mode 100644 index 000000000..212fe3452 --- /dev/null +++ b/GRDB/QueryInterface/Association/Association.swift @@ -0,0 +1,318 @@ +/// [**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: DerivableRequest { + associatedtype OriginRowDecoder + associatedtype RowDecoder + + /// 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 + + /// :nodoc: + var request: AssociationRequest { get } + + /// :nodoc: + func joinCondition(_ db: Database) throws -> JoinCondition + + /// :nodoc: + func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> Self +} + +extension Association { + /// Creates an association with a new set 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 promise*. + /// + /// 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 { _ in [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{ _ in [Column("color")] } + /// .reversed() + /// .order{ _ in [Column("name")] } + /// var request = Player.including(required: association) + public func order(_ orderings: @escaping (Database) throws -> [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) } + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// :nodoc: +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.OriginRowDecoder == RowDecoder { + 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.OriginRowDecoder == RowDecoder { + 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.OriginRowDecoder == RowDecoder { + 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.OriginRowDecoder == RowDecoder { + return mapRequest { $0.joining(.required, association.select([])) } + } +} + +extension Association where OriginRowDecoder: 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: OriginRowDecoder) -> QueryInterfaceRequest { + // Goal: turn `JOIN association ON association.recordId = record.id` + // into a regular request `SELECT * FROM association WHERE association.recordId = 123` + + // We need table aliases to build the joining condition + let associationAlias = TableAlias() + let recordAlias = TableAlias() + + // Turn the association request into a query interface request: + // JOIN association -> SELECT FROM association + return QueryInterfaceRequest(request) + + // Turn the JOIN condition into a regular WHERE condition + .filter { db in + // Build a join condition: `association.recordId = record.id` + // We still need to replace `record.id` with the actual record id. + guard let joinCondition = try self.joinCondition(db)(recordAlias, associationAlias) else { + fatalError("Can't request from record without join condition") + } + + // Serialize record: ["id": 123, ...] + // We do it as late as possible, when request is about to be + // executed, in order to support long-lived reference types. + let container = PersistenceContainer(record) + + // Replace `record.id` with 123 + return joinCondition.resolvedExpression(inContext: [recordAlias: container]) + } + + // We just added a condition qualified with associationAlias. Don't + // risk introducing conflicting aliases that would prevent the user + // from setting a custom alias name: force the same alias for the + // whole request. + .aliased(associationAlias) + } +} diff --git a/GRDB/QueryInterface/Association/AssociationQuery.swift b/GRDB/QueryInterface/Association/AssociationQuery.swift new file mode 100644 index 000000000..fb70e808c --- /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: @escaping (Database) throws -> [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..1f52aa2bc --- /dev/null +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -0,0 +1,50 @@ +/// [**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'`). +/// :nodoc: +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: @escaping (Database) throws -> [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.OriginRowDecoder == 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..3b9fd882d --- /dev/null +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -0,0 +1,178 @@ +/// 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: +/// +/// struct Author: TableRecord { ... } +/// struct Book: TableRecord { +/// static let author = belongsTo(Author.self) +/// ... +/// } +/// +/// A BelongsTo associations should be supported by an SQLite foreign key. +/// +/// Foreign keys are the recommended way to declare relationships between +/// database tables because not only will SQLite guarantee the integrity of your +/// data, but GRDB will be able to use those foreign keys to automatically +/// configure your association. +/// +/// You define the foreign key when you create database tables. For example: +/// +/// 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 https://sqlite.org/foreignkeys.html#fk_actions for more information. +/// +/// The example above uses auto-incremented primary keys. But generally +/// speaking, all primary keys are supported. +/// +/// If the database schema does not define foreign keys between tables, you can +/// still use BelongsTo associations. But your help is needed to define the +/// missing foreign key: +/// +/// struct Book: FetchableRecord, TableRecord { +/// static let author = belongsTo(Author.self, using: ForeignKey(...)) +/// } +/// +/// See ForeignKey for more information. +public struct BelongsToAssociation: Association { + fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest + + /// :nodoc: + public typealias OriginRowDecoder = Origin + + /// :nodoc: + public typealias RowDecoder = Destination + + public var key: String + + /// :nodoc: + public var request: AssociationRequest + + public func forKey(_ key: String) -> BelongsToAssociation { + var association = self + association.key = key + return association + } + + /// :nodoc: + public func joinCondition(_ db: Database) throws -> JoinCondition { + return try joinConditionRequest.fetch(db) + } + + /// :nodoc: + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> BelongsToAssociation { + var association = self + association.request = transform(request) + return association + } +} + +// Allow BelongsToAssociation(...).filter(key: ...) +extension BelongsToAssociation: TableRequest where Destination: TableRecord { + /// :nodoc: + public var databaseTableName: String { return Destination.databaseTableName } +} + +extension TableRecord { + /// Creates a "Belongs To" association between Self and the + /// destination type. + /// + /// struct Author: TableRecord { ... } + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// } + /// + /// The association will let you define requests that load both the source + /// and the destination type: + /// + /// // A request for all books with their authors: + /// let request = Book.including(optional: Book.author) + /// + /// To consume those requests, define a type that adopts both the + /// FetchableRecord and Decodable protocols: + /// + /// struct BookInfo: FetchableRecord, Decodable { + /// var book: Book + /// var author: Author? + /// } + /// + /// let bookInfos = try dbQueue.read { db in + /// return try BookInfo.fetchAll(db, request) + /// } + /// for bookInfo in bookInfos { + /// print("\(bookInfo.book.title) by \(bookInfo.author.name)") + /// } + /// + /// It is recommended that you define, alongside the association, a property + /// with the same name: + /// + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// var author: QueryInterfaceRequest { + /// return request(for: Book.author) + /// } + /// } + /// + /// This property will let you navigate from the source type to the + /// destination type: + /// + /// try dbQueue.read { db in + /// let book: Book = ... + /// let author = try book.author.fetchOne(db) // Author? + /// } + /// + /// - parameters: + /// - destination: The record type at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key to the destination table, or when the schema defines several + /// foreign keys to the destination table. + public static func belongsTo( + _ destination: Destination.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + where Destination: TableRecord + { + let foreignKeyRequest = ForeignKeyRequest( + originTable: databaseTableName, + destinationTable: Destination.databaseTableName, + foreignKey: foreignKey) + + let joinConditionRequest = ForeignKeyJoinConditionRequest( + foreignKeyRequest: foreignKeyRequest, + originIsLeft: true) + + return BelongsToAssociation( + joinConditionRequest: joinConditionRequest, + key: key ?? Destination.databaseTableName, + request: AssociationRequest(Destination.all())) + } +} diff --git a/GRDB/QueryInterface/Association/ForeignKey.swift b/GRDB/QueryInterface/Association/ForeignKey.swift new file mode 100644 index 000000000..5b4312762 --- /dev/null +++ b/GRDB/QueryInterface/Association/ForeignKey.swift @@ -0,0 +1,108 @@ +/// A ForeignKey helps building associations when GRDB can't infer a foreign +/// key from the database schema. +/// +/// Sometimes the database schema does not define any foreign key between two +/// tables. And sometimes, there are several foreign keys from a table +/// to another: +/// +/// | Table book | | Table person | +/// | ------------ | | ------------ | +/// | id | +-->• id | +/// | authorId •---+ | name | +/// | translatorId •---+ +/// | title | +/// +/// 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 person", or "Could not infer foreign key from book +/// to person". +/// +/// Your help is needed. You have to instruct GRDB which foreign key to use: +/// +/// 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: +/// +/// 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 query interface columns: +/// +/// struct Book: TableRecord { +/// enum Columns: String, ColumnExpression { +/// case id, title, authorId, translatorId +/// } +/// +/// static let authorForeignKey = ForeignKey([Columns.authorId])) +/// static let translatorForeignKey = ForeignKey([Columns.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: +/// +/// struct Book: TableRecord { +/// static let authorForeignKey = ForeignKey(["authorId"], to: ["id"])) +/// static let author = belongsTo(Person.self, using: authorForeignKey) +/// } +public struct ForeignKey { + var originColumns: [String] + var destinationColumns: [String]? + + /// Creates a ForeignKey intended to define a record association. + /// + /// 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) + /// } + /// + /// - parameter originColumns: The columns at the origin of the foreign key. + /// - parameter destinationColumns: The columns at the destination of the + /// foreign key. When nil (the default), GRDB automatically uses the + /// primary key. + public init(_ originColumns: [String], to destinationColumns: [String]? = nil) { + self.originColumns = originColumns + self.destinationColumns = destinationColumns + } + + /// Creates a ForeignKey intended to define a record association. + /// + /// struct Book: TableRecord { + /// // Define columns + /// enum Columns: String, ColumnExpression { + /// case id, title, authorId, translatorId + /// } + /// + /// // Define foreign keys + /// static let authorForeignKey = ForeignKey([Columns.authorId])) + /// static let translatorForeignKey = ForeignKey([Columns.translatorId])) + /// + /// // Use foreign keys to define associations: + /// static let author = belongsTo(Person.self, using: authorForeignKey) + /// static let translator = belongsTo(Person.self, using: translatorForeignKey) + /// } + /// + /// - parameter originColumns: The columns at the origin of the foreign key. + /// - parameter destinationColumns: The columns at the destination of the + /// foreign key. When nil (the default), GRDB automatically uses the + /// primary key. + public init(_ originColumns: [ColumnExpression], to destinationColumns: [ColumnExpression]? = 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..077581950 --- /dev/null +++ b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift @@ -0,0 +1,82 @@ +/// 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 + } + } + if let destinationColumns = destinationColumns { + // TODO: test + 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 + 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) { + 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. +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..7e0fa6b72 --- /dev/null +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -0,0 +1,178 @@ +/// 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. +/// +/// 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: +/// +/// struct Book: TableRecord { ... } +/// struct Author: TableRecord { +/// static let books = hasMany(Book.self) +/// ... +/// } +/// +/// HasMany associations should be supported by an SQLite foreign key. +/// +/// Foreign keys are the recommended way to declare relationships between +/// database tables because not only will SQLite guarantee the integrity of your +/// data, but GRDB will be able to use those foreign keys to automatically +/// configure your association. +/// +/// You define the foreign key when you create database tables. For example: +/// +/// 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 https://sqlite.org/foreignkeys.html#fk_actions for more information. +/// +/// The example above uses auto-incremented primary keys. But generally +/// speaking, all primary keys are supported. +/// +/// If the database schema does not define foreign keys between tables, you can +/// still use HasMany associations. But your help is needed to define the +/// missing foreign key: +/// +/// struct Author: TableRecord { +/// static let books = hasMany(Book.self, using: ForeignKey(...)) +/// } +/// +/// See ForeignKey for more information. +public struct HasManyAssociation: Association { + fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest + + /// :nodoc: + public typealias OriginRowDecoder = Origin + + /// :nodoc: + public typealias RowDecoder = Destination + + public var key: String + + /// :nodoc: + public var request: AssociationRequest + + public func forKey(_ key: String) -> HasManyAssociation { + var association = self + association.key = key + return association + } + + /// :nodoc: + public func joinCondition(_ db: Database) throws -> JoinCondition { + return try joinConditionRequest.fetch(db) + } + + /// :nodoc: + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasManyAssociation { + var association = self + association.request = transform(request) + return association + } +} + +// Allow HasManyAssociation(...).filter(key: ...) +extension HasManyAssociation: TableRequest where Destination: TableRecord { + /// :nodoc: + public var databaseTableName: String { return Destination.databaseTableName } +} + +extension TableRecord { + /// Creates a "Has many" association between Self and the + /// destination type. + /// + /// struct Book: TableRecord { ... } + /// struct Author: TableRecord { + /// static let books = hasMany(Book.self) + /// } + /// + /// The association will let you define requests that load both the source + /// and the destination type: + /// + /// // A request for all (author, book) pairs: + /// let request = Author.including(required: Author.books) + /// + /// To consume those requests, define a type that adopts both the + /// FetchableRecord and Decodable protocols: + /// + /// struct Authorship: FetchableRecord, Decodable { + /// var author: Author + /// var book: Book + /// } + /// + /// let authorships = try dbQueue.read { db in + /// return try Authorship.fetchAll(db, request) + /// } + /// for authorship in authorships { + /// print("\(authorship.author.name) wrote \(authorship.book.title)") + /// } + /// + /// It is recommended that you define, alongside the association, a property + /// with the same name: + /// + /// struct Author: TableRecord { + /// static let books = hasMany(Book.self) + /// var books: QueryInterfaceRequest { + /// return request(for: Author.books) + /// } + /// } + /// + /// This property will let you navigate from the source type to the + /// destination type: + /// + /// try dbQueue.read { db in + /// let author: Author = ... + /// let books = try author.books.fetchAll(db) // [Book] + /// } + /// + /// - parameters: + /// - destination: The record type at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key from the destination table, or when the schema defines several + /// foreign keys from the destination table. + public static func hasMany( + _ destination: Destination.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + where Destination: TableRecord + { + let foreignKeyRequest = ForeignKeyRequest( + originTable: Destination.databaseTableName, + destinationTable: databaseTableName, + foreignKey: foreignKey) + + let joinConditionRequest = ForeignKeyJoinConditionRequest( + foreignKeyRequest: foreignKeyRequest, + originIsLeft: false) + + return HasManyAssociation( + joinConditionRequest: joinConditionRequest, + key: key ?? Destination.databaseTableName, + request: AssociationRequest(Destination.all())) + } +} diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift new file mode 100644 index 000000000..58bb5eea6 --- /dev/null +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -0,0 +1,180 @@ +/// The HasOne association indicates a one-to-one connection between two +/// record types, such as each instance of the declaring record "has one" +/// instances of the other record. +/// +/// For example, if your application has one database table for countries, and +/// another for their demographic profiles, you'd declare the association +/// this way: +/// +/// struct Demographics: TableRecord { ... } +/// struct Country: TableRecord { +/// static let demographics = hasOne(Demographics.self) +/// ... +/// } +/// +/// HasOne associations should be supported by an SQLite foreign key. +/// +/// Foreign keys are the recommended way to declare relationships between +/// database tables because not only will SQLite guarantee the integrity of your +/// data, but GRDB will be able to use those foreign keys to automatically +/// configure your association. +/// +/// You define the foreign key when you create database tables. For example: +/// +/// 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 https://sqlite.org/foreignkeys.html#fk_actions for more information. +/// +/// The example above uses a string primary for the country table. But generally +/// speaking, all primary keys are supported. +/// +/// 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: +/// +/// struct Country: FetchableRecord, TableRecord { +/// static let demographics = hasOne(Demographics.self, using: ForeignKey(...)) +/// } +/// +/// See ForeignKey for more information. +public struct HasOneAssociation : Association { + fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest + + /// :nodoc: + public typealias OriginRowDecoder = Origin + + /// :nodoc: + public typealias RowDecoder = Destination + + public var key: String + + /// :nodoc: + public var request: AssociationRequest + + public func forKey(_ key: String) -> HasOneAssociation { + var association = self + association.key = key + return association + } + + /// :nodoc: + public func joinCondition(_ db: Database) throws -> JoinCondition { + return try joinConditionRequest.fetch(db) + } + + /// :nodoc: + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasOneAssociation { + var association = self + association.request = transform(request) + return association + } +} + +// Allow HasOneAssociation(...).filter(key: ...) +extension HasOneAssociation: TableRequest where Destination: TableRecord { + /// :nodoc: + public var databaseTableName: String { return Destination.databaseTableName } +} + +extension TableRecord { + /// Creates a "Has one" association between Self and the + /// destination type. + /// + /// struct Demographics: TableRecord { ... } + /// struct Country: TableRecord { + /// static let demographics = hasOne(Demographics.self) + /// } + /// + /// The association will let you define requests that load both the source + /// and the destination type: + /// + /// // A request for all countries with their demographic profile: + /// let request = Country.including(optional: Country.demographics) + /// + /// To consume those requests, define a type that adopts both the + /// FetchableRecord and Decodable protocols: + /// + /// struct CountryInfo: FetchableRecord, Decodable { + /// var country: Country + /// var demographics: Demographics? + /// } + /// + /// let countryInfos = try dbQueue.read { db in + /// return try CountryInfo.fetchAll(db, request) + /// } + /// for countryInfo in countryInfos { + /// print("\(countryInfo.country.name) has \(countryInfo.demographics.population) citizens") + /// } + /// + /// It is recommended that you define, alongside the association, a property + /// with the same name: + /// + /// struct Country: TableRecord { + /// static let demographics = hasOne(Demographics.self) + /// var demographics: QueryInterfaceRequest { + /// return request(for: Country.demographics) + /// } + /// } + /// + /// This property will let you navigate from the source type to the + /// destination type: + /// + /// try dbQueue.read { db in + /// let country: Country = ... + /// let demographics = try country.demographics.fetchOne(db) // Demographics? + /// } + /// + /// - parameters: + /// - destination: The record type at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key from the destination table, or when the schema defines several + /// foreign keys from the destination table. + public static func hasOne( + _ destination: Destination.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + where Destination: TableRecord + { + let foreignKeyRequest = ForeignKeyRequest( + originTable: Destination.databaseTableName, + destinationTable: databaseTableName, + foreignKey: foreignKey) + + let joinConditionRequest = ForeignKeyJoinConditionRequest( + foreignKeyRequest: foreignKeyRequest, + originIsLeft: false) + + return HasOneAssociation( + joinConditionRequest: joinConditionRequest, + key: key ?? Destination.databaseTableName, + request: AssociationRequest(Destination.all())) + } +} diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index 5740c0464..e66ca6ba4 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -1,40 +1,111 @@ -/// A column in the database +/// Adopt the ColumnExpression protocol when you define a column type. +/// +/// You can, for example, define a String-based column enum: +/// +/// enum Columns: String, ColumnExpression { +/// case id, name, score +/// } +/// let arthur = try Player.filter(Columns.name == "Arthur").fetchOne(db) +/// +/// You can also define a genuine column type: +/// +/// struct MyColumn: ColumnExpression { +/// var name: String +/// var sqlType: String +/// } +/// let nameColumn = MyColumn(name: "name", sqlType: "VARCHAR") +/// let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) /// /// See https://github.com/groue/GRDB.swift#the-query-interface -public struct Column : SQLExpression { +public protocol ColumnExpression: SQLExpression { + /// The unqualified name of a database column. + /// + /// "score" is a valid unqualified name. "player.score" is not. + var name: String { get } +} + +extension ColumnExpression { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + 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 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 + } +} + +/// A column in a database table. +/// +/// When you need to introduce your own column type, don't wrap a Column. +/// Instead, adopt the ColumnExpression protocol. +/// +/// See https://github.com/groue/GRDB.swift#the-query-interface +public struct Column: ColumnExpression { /// The hidden rowID column public static let rowID = Column("rowid") /// The name of the column - public let name: String - - private var qualifier: SQLTableQualifier? + public var name: String /// Creates a column given its name. public init(_ name: String) { self.name = name } +} + +/// A qualified column in the database, as in `SELECT t.a FROM t` +struct QualifiedColumn: ColumnExpression { + var name: String + private let alias: TableAlias - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// :nodoc: - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { - if let qualifierName = qualifier?.name { - return qualifierName.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier + /// Creates a column given its name. + init(_ name: String, alias: TableAlias) { + self.name = name + self.alias = alias + } + + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + if let qualifier = context.qualifier(for: alias) { + return qualifier.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier } return name.quotedDatabaseIdentifier } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// :nodoc: - public func qualified(by qualifier: SQLTableQualifier) -> Column { - if self.qualifier != nil { - // Never requalify + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + // Never requalify + return self + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + guard + let container = context[alias], + let value = container.value(forCaseInsensitiveColumn: name) else + { return self } - var column = self - column.qualifier = qualifier - return column + return value + } +} + +/// Support for column enums: +/// +/// struct Player { +/// enum Columns: ColumnExpression { +/// case id, name, score +/// } +/// } +extension ColumnExpression where Self: RawRepresentable, Self.RawValue == String { + public var name: String { + return rawValue } } diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index aa1229783..0c1d56aaa 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -2,47 +2,47 @@ extension QueryInterfaceRequest { // MARK: Full Text Search - /// Returns a new QueryInterfaceRequest with a matching predicate added - /// to the eventual set of already applied predicates. + /// 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) } } -extension TableMapping { +extension TableRecord { // MARK: Full Text Search /// 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 /// database row. /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest { return all().matching(pattern) } } -extension Column { +extension ColumnExpression { /// A matching SQL expression with the `MATCH` SQL operator. /// /// // content MATCH '...' diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index bb0191eae..2affcfe44 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -3,10 +3,10 @@ // MARK: Full Text Search - /// Returns a new QueryInterfaceRequest with a matching predicate added - /// to the eventual set of already applied predicates. + /// 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) /// @@ -14,30 +14,26 @@ /// database row. /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// 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) } } - extension TableMapping { + extension TableRecord { // MARK: Full Text Search /// 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 new file mode 100644 index 000000000..abb790818 --- /dev/null +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -0,0 +1,588 @@ +struct DatabasePromise { + let resolve: (Database) throws -> T + + init(value: T) { + self.resolve = { _ in value } + } + + init(_ resolve: @escaping (Database) throws -> T) { + self.resolve = resolve + } + + func map(_ transform: @escaping (Database, T) throws -> T) -> DatabasePromise { + return DatabasePromise { db in + try transform(db, self.resolve(db)) + } + } +} + +struct QueryInterfaceQuery { + var source: SQLSource + var selection: [SQLSelectable] + var isDistinct: Bool + var filterPromise: DatabasePromise + var groupByExpressions: [SQLExpression] + var ordering: QueryOrdering + var havingExpression: SQLExpression? + var limit: SQLLimit? + var joins: [AssociationJoin] + + init( + source: SQLSource, + selection: [SQLSelectable] = [], + isDistinct: Bool = false, + 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.filterPromise = filterPromise + self.groupByExpressions = groupByExpressions + self.ordering = ordering + self.havingExpression = havingExpression + self.limit = limit + self.joins = joins + } + + 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.selection = selection + return query + } + + 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: @escaping (Database) throws -> [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" + } + + let selection = finalizedSelection + GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") + sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") + + sql += try " FROM " + source.sourceSQL(db, &context) + + for join in joins { + sql += try " " + join.joinSQL(db, &context, leftAlias: alias!, isRequiredAllowed: true) + } + + if let filter = try filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&context) + } + + if !groupByExpressions.isEmpty { + sql += " GROUP BY " + sql += groupByExpressions.map { $0.expressionSQL(&context) } + .joined(separator: ", ") + } + + if let havingExpression = havingExpression { + sql += " HAVING " + havingExpression.expressionSQL(&context) + } + + let orderings = try finalizedOrdering.resolve(db) + if !orderings.isEmpty { + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") + } + + if let limit = limit { + sql += " LIMIT " + limit.sql + } + + 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 clause") + } + + guard havingExpression == nil else { + // Programmer error + fatalError("Can't delete query with HAVING clause") + } + + guard joins.isEmpty else { + // Programmer error + fatalError("Can't delete query with JOIN clause") + } + + 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 = try finalizedOrdering.resolve(db) + if !orderings.isEmpty { + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") + } + + if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") { + sql += " LIMIT " + limit.sql + } else { + fatalError("Can't delete query with limit") + } + } + + let statement = try db.makeUpdateStatement(sql) + statement.arguments = context.arguments! + return statement + } + + /// precondition: self is the result of finalizedQuery + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (makeSelectStatement(db), finalizedRowAdapter(db)) + } + + func fetchCount(_ db: Database) throws -> Int { + let (statement, adapter) = try countQuery.prepare(db) + return try Int.fetchOne(statement, adapter: adapter)! + } + + /// The database region that the request looks into. + /// precondition: self is the result of finalizedQuery + func databaseRegion(_ db: Database) throws -> DatabaseRegion { + let statement = try makeSelectStatement(db) + let databaseRegion = statement.databaseRegion + + // Can we intersect the region with rowIds? + // + // Give up unless request feeds from a single database table + guard case .table(tableName: let tableName, alias: _) = source else { + // TODO: try harder + return databaseRegion + } + + // Give up unless primary key is rowId + let primaryKeyInfo = try db.primaryKey(tableName) + guard primaryKeyInfo.isRowID else { + return databaseRegion + } + + // Give up unless there is a where clause + guard let filter = try filterPromise.resolve(db) else { + return databaseRegion + } + + // The filter knows better + guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { + return databaseRegion + } + + // Database regions are case-insensitive: use the canonical table name + let canonicalTableName = try db.canonicalTableName(tableName) + return databaseRegion.tableIntersection(canonicalTableName, rowIds: rowIds) + } + + private var countQuery: QueryInterfaceQuery { + guard groupByExpressions.isEmpty && limit == nil else { + // SELECT ... GROUP BY ... + // SELECT ... LIMIT ... + return trivialCountQuery + } + + guard joins.isEmpty, case .table = source else { + // SELECT ... FROM (something which is not a plain table) + return trivialCountQuery + } + + 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 = self.unordered() + countQuery.isDistinct = false + countQuery.selection = [count.sqlSelectable] + return countQuery + } else { + // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... + + guard !isDistinct else { + return trivialCountQuery + } + + // SELECT expr1, expr2, ... FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + var countQuery = self.unordered() + countQuery.selection = [SQLExpressionCount(AllColumns())] + return countQuery + } + } + + // SELECT COUNT(*) FROM (self) + private var trivialCountQuery: QueryInterfaceQuery { + return QueryInterfaceQuery( + 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: - SQLSource + +enum SQLSource { + case table(tableName: String, alias: TableAlias?) + indirect case query(QueryInterfaceQuery) + + var alias: TableAlias? { + switch self { + 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 "\(tableName.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.becomeProxy(of: sourceAlias) + return self + } else { + alias.setTableName(tableName) + return .table(tableName: tableName, alias: alias) + } + case .query(let query): + return .query(query.qualified(with: alias)) + } + } +} + +struct SQLLimit { + let limit: Int + let offset: Int? + + var sql: String { + if let offset = offset { + return "\(limit) OFFSET \(offset)" + } else { + return "\(limit)" + } + } +} + +extension SQLCount { + var sqlSelectable: SQLSelectable { + switch self { + case .all: + return SQLExpressionCount(AllColumns()) + case .distinct(let expression): + return SQLExpressionCountDistinct(expression) + } + } +} diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift new file mode 100644 index 000000000..cf627a845 --- /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.OriginRowDecoder == 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.OriginRowDecoder == 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.OriginRowDecoder == 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.OriginRowDecoder == 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.OriginRowDecoder == 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.OriginRowDecoder == 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.OriginRowDecoder == 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.OriginRowDecoder == 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.OriginRowDecoder == 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.OriginRowDecoder == Self { + return all().joining(required: association) + } +} diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 8cd1c29fc..bf08c5157 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -2,370 +2,197 @@ /// /// See https://github.com/groue/GRDB.swift#the-query-interface public struct QueryInterfaceRequest { - let query: QueryInterfaceSelectQueryDefinition + let query: QueryInterfaceQuery - init(query: QueryInterfaceSelectQueryDefinition) { + init(query: QueryInterfaceQuery) { self.query = query } + + init(_ request: AssociationRequest) { + self.query = QueryInterfaceQuery(request.query) + } } -extension QueryInterfaceRequest : TypedRequest { +extension QueryInterfaceRequest : FetchRequest { public typealias RowDecoder = T - /// A tuple that contains a prepared statement that is ready to be + /// Returns a tuple that contains a prepared statement that is ready to be /// executed, and an eventual row adapter. /// /// - parameter db: A database connection. - /// + /// - 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) } - /// The number of rows fetched by the request. + /// Returns the number of rows fetched by the request. /// /// - parameter db: A database connection. - /// /// :nodoc: public func fetchCount(_ db: Database) throws -> Int { return try query.fetchCount(db) } - /// The database region that the request looks into. + /// Returns the database region that the request looks into. /// + /// - parameter db: A database connection. /// :nodoc: - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try query.fetchedRegion(db) + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + return try query.finalizedQuery.databaseRegion(db) } } -extension QueryInterfaceRequest { +extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { // MARK: Request Derivation - - /// A new QueryInterfaceRequest with a new net of selected columns. + + /// Creates a request with a new set of selected columns. /// - /// // SELECT id, email FROM players - /// var request = Player.all() - /// request = request.select(Column("id"), Column("email")) - /// - /// Any previous selection is replaced: - /// - /// // SELECT email FROM players - /// request - /// .select(Column("id")) - /// .select(Column("email")) - public func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { - return select(selection) - } - - /// A new QueryInterfaceRequest 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)) } - /// A new QueryInterfaceRequest with a new net of selected columns. + /// Creates a request which returns distinct rows. /// - /// // SELECT id, email FROM players - /// var request = Player.all() - /// request = request.select(sql: "id, email") - /// - /// Any previous selection is replaced: - /// - /// // SELECT email FROM players - /// request - /// .select(sql: "id") - /// .select(sql: "email") - public func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return select(SQLExpressionLiteral(sql, arguments: arguments)) - } - - /// A new QueryInterfaceRequest 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()) } - /// A new QueryInterfaceRequest 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 - } - }) + /// request = request.filter { db in true } + public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { + return QueryInterfaceRequest(query: query.filter(predicate)) } - /// A new QueryInterfaceRequest with the provided *predicate* added to the - /// eventual set of already applied predicates. - /// - /// // SELECT * FROM players 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) -> QueryInterfaceRequest { - return filter(SQLExpressionLiteral(sql, arguments: arguments)) - } - - /// A new QueryInterfaceRequest grouped according to *expressions*. - public func group(_ expressions: SQLExpressible...) -> QueryInterfaceRequest { - return group(expressions) - } - - /// A new QueryInterfaceRequest grouped according to *expressions*. + /// 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)) } - /// A new QueryInterfaceRequest with a new grouping. - public func group(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return group(SQLExpressionLiteral(sql, arguments: arguments)) - } - - /// A new QueryInterfaceRequest with the provided *predicate* added to the + /// 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)) } - /// A new QueryInterfaceRequest with the provided *sql* added to the - /// eventual set of already applied predicates. - public func having(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return having(SQLExpressionLiteral(sql, arguments: arguments)) - } - - /// A new QueryInterfaceRequest with the provided *orderings*. + /// Creates a request with the provided *orderings promise*. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// var request = Player.all() - /// request = request.order(Column("name")) + /// request = request.order { _ in [Column("name")] } /// /// Any previous ordering is replaced: /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// request - /// .order(Column("email")) + /// .order{ _ in [Column("email")] } /// .reversed() - /// .order(Column("name")) - public func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { - return order(orderings) + /// .order{ _ in [Column("name")] } + public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest { + return QueryInterfaceRequest(query: query.order(orderings)) } - /// A new QueryInterfaceRequest with the provided *orderings*. + /// Creates a request that reverses applied orderings. /// - /// // SELECT * FROM players ORDER BY name - /// var request = Player.all() - /// request = request.order([Column("name")]) - /// - /// Any previous ordering is replaced: - /// - /// // SELECT * FROM players ORDER BY name - /// request - /// .order([Column("email")]) - /// .reversed() - /// .order([Column("name")]) - public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { - var query = self.query - query.orderings = orderings - query.isReversed = false - return QueryInterfaceRequest(query: query) - } - - /// A new QueryInterfaceRequest with the provided *sql* used for sorting. - /// - /// // SELECT * FROM players ORDER BY name - /// var request = Player.all() - /// request = request.order(sql: "name") - /// - /// Any previous ordering is replaced: - /// - /// // SELECT * FROM players ORDER BY name - /// request - /// .order(sql: "email") - /// .order(sql: "name") - public func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return order([SQLExpressionLiteral(sql, arguments: arguments)]) - } - - /// A new QueryInterfaceRequest sorted in reversed order. - /// - /// // 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.isReversed = !query.isReversed - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.reversed()) } - /// A QueryInterfaceRequest which fetches *limit* rows, starting - /// at *offset*. + /// 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: TableMapping { - - /// Creates a QueryInterfaceRequest 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 `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. - public func filter(key: PrimaryKeyType?) -> QueryInterfaceRequest { - guard let key = key else { - return T.none() - } - - return filter(keys: [key]) - } - - /// Creates a QueryInterfaceRequest 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 `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.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 QueryInterfaceRequest 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 `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. - public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { - guard let key = key else { - return T.none() - } - - return filter(keys: [key]) - } - - /// Creates a QueryInterfaceRequest 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 `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.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(db, keys: [[:]]) - GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary") - - // 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 SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty - } - - let keysPredicate = SQLBinaryOperator.or.join(keyPredicates)! // not nil because keyPredicates is not empty - - 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 } } -extension QueryInterfaceRequest where RowDecoder: MutablePersistable { +extension QueryInterfaceRequest where T: MutablePersistableRecord { // MARK: Deleting @@ -381,177 +208,215 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistable { } } -extension TableMapping { +extension TableRecord { // MARK: Request Derivation - /// Creates a QueryInterfaceRequest which fetches all records. + /// 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 - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func all() -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: QueryInterfaceSelectQueryDefinition(select: databaseSelection, from: .table(name: databaseTableName, alias: nil))) + let query = QueryInterfaceQuery( + source: .table(tableName: databaseTableName, alias: nil), + selection: databaseSelection) + return QueryInterfaceRequest(query: query) } - /// Creates a QueryInterfaceRequest which fetches no record. + /// Creates a request which fetches no record. public static func none() -> QueryInterfaceRequest { - return filter(false) + return all().none() // don't laugh } - /// Creates a QueryInterfaceRequest which selects *selection*. + /// 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) } - /// Creates a QueryInterfaceRequest which selects *selection*. + /// 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) } - /// Creates a QueryInterfaceRequest which selects *sql*. + /// 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) } - /// Creates a QueryInterfaceRequest with the provided *predicate*. + /// 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 - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest { return all().filter(predicate) } - /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// 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 - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func filter(key: PrimaryKeyType?) -> QueryInterfaceRequest { return all().filter(key: key) } - /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// 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 - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func filter(keys: Sequence) -> QueryInterfaceRequest where Sequence.Element: DatabaseValueConvertible { return all().filter(keys: keys) } - /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// 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 /// index on the key columns. /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { return all().filter(key: key) } - /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// 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 /// index on the key columns. /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { return all().filter(keys: keys) } - /// Creates a QueryInterfaceRequest with the provided *predicate*. + /// 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 - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { return all().filter(sql: sql, arguments: arguments) } - /// Creates a QueryInterfaceRequest sorted according to the + /// 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 - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { return all().order(orderings) } - /// Creates a QueryInterfaceRequest sorted according to the + /// 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 - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { return all().order(orderings) } - /// Creates a QueryInterfaceRequest sorted according to *sql*. + /// Creates a request sorted by primary key. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY id + /// let request = Player.orderByPrimaryKey() + /// + /// // SELECT * FROM country ORDER BY code + /// let request = Country.orderByPrimaryKey() + /// + /// 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 static func orderByPrimaryKey() -> QueryInterfaceRequest { + return all().orderByPrimaryKey() + } + + /// Creates a request sorted according to *sql*. + /// + /// // SELECT * FROM player ORDER BY name /// let request = Player.order(sql: "name") /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { return all().order(sql: sql, arguments: arguments) } - /// Creates a QueryInterfaceRequest which fetches *limit* rows, starting at + /// 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 - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. 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/QueryInterfaceSelectQueryDefinition.swift b/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift deleted file mode 100644 index a15c19729..000000000 --- a/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift +++ /dev/null @@ -1,309 +0,0 @@ -// MARK: - QueryInterfaceSelectQueryDefinition - -struct DatabasePromise { - let resolve: (Database) throws -> T - - init(value: T) { - self.resolve = { _ in value } - } - - init(_ resolve: @escaping (Database) throws -> T) { - self.resolve = resolve - } - - func map(_ transform: @escaping (Database, T) throws -> T) -> DatabasePromise { - return DatabasePromise { db in - try transform(db, self.resolve(db)) - } - } -} - -struct QueryInterfaceSelectQueryDefinition { - var selection: [SQLSelectable] - var isDistinct: Bool - var source: SQLSource? - var wherePromise: DatabasePromise - var groupByExpressions: [SQLExpression] - var orderings: [SQLOrderingTerm] - var isReversed: Bool - var havingExpression: SQLExpression? - var limit: SQLLimit? - - init( - select selection: [SQLSelectable], - isDistinct: Bool = false, - from source: SQLSource? = nil, - filter whereExpression: SQLExpression? = nil, - groupBy groupByExpressions: [SQLExpression] = [], - orderBy orderings: [SQLOrderingTerm] = [], - isReversed: Bool = false, - having havingExpression: SQLExpression? = nil, - limit: SQLLimit? = nil) - { - self.selection = selection - self.isDistinct = isDistinct - self.source = source - self.wherePromise = DatabasePromise(value: whereExpression) - self.groupByExpressions = groupByExpressions - self.orderings = orderings - self.isReversed = isReversed - self.havingExpression = havingExpression - self.limit = limit - } - - func mapWhereExpression(_ transform: @escaping (Database, SQLExpression?) throws -> SQLExpression?) -> QueryInterfaceSelectQueryDefinition { - var query = self - query.wherePromise = query.wherePromise.map(transform) - return query - } - - func sql(_ db: Database, _ arguments: inout StatementArguments?) throws -> String { - var sql = "SELECT" - - if isDistinct { - sql += " DISTINCT" - } - - assert(!selection.isEmpty) - sql += " " + selection.map { $0.resultColumnSQL(&arguments) }.joined(separator: ", ") - - if let source = source { - sql += try " FROM " + source.sourceSQL(db, &arguments) - } - - if let whereExpression = try wherePromise.resolve(db) { - sql += " WHERE " + whereExpression.expressionSQL(&arguments) - } - - if !groupByExpressions.isEmpty { - sql += " GROUP BY " + groupByExpressions.map { $0.expressionSQL(&arguments) }.joined(separator: ", ") - } - - if let havingExpression = havingExpression { - sql += " HAVING " + havingExpression.expressionSQL(&arguments) - } - - let orderings = self.queryOrderings - if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") - } - - if let limit = limit { - sql += " LIMIT " + limit.sql - } - - return sql - } - - func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { - guard groupByExpressions.isEmpty else { - // Programmer error - fatalError("Can't delete query with GROUP BY expression") - } - - guard havingExpression == nil else { - // Programmer error - fatalError("Can't delete query with GROUP BY expression") - } - - var sql = "DELETE" - var arguments: StatementArguments? = StatementArguments() - - if let source = source { - sql += try " FROM " + source.sourceSQL(db, &arguments) - } - - if let whereExpression = try wherePromise.resolve(db) { - sql += " WHERE " + whereExpression.expressionSQL(&arguments) - } - - if let limit = limit { - let orderings = self.queryOrderings - if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") - } - - if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") { - sql += " LIMIT " + limit.sql - } else { - fatalError("Can't delete query with limit") - } - } - - let statement = try db.makeUpdateStatement(sql) - statement.arguments = arguments! - return statement - } - - private var queryOrderings: [SQLOrderingTerm] { - if isReversed { - if orderings.isEmpty { - // https://www.sqlite.org/lang_createtable.html#rowid - // - // > The rowid value can be accessed using one of the special - // > case-independent names "rowid", "oid", or "_rowid_" in - // > place of a column name. If a table contains a user defined - // > column named "rowid", "oid" or "_rowid_", then that name - // > always refers the explicitly declared column and cannot be - // > used to retrieve the integer rowid value. - // - // Here we assume that rowid is not a custom column. - // TODO: support for user-defined rowid column. - // TODO: support for WITHOUT ROWID tables. - return [Column.rowID.desc] - } else { - return orderings.map { $0.reversed } - } - } else { - return orderings - } - } - - /// Remove ordering - var unorderedQuery: QueryInterfaceSelectQueryDefinition { - var query = self - query.isReversed = false - query.orderings = [] - return query - } -} - -extension QueryInterfaceSelectQueryDefinition : Request { - 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) - } - - func fetchCount(_ db: Database) throws -> Int { - return try Int.fetchOne(db, countQuery)! - } - - /// The database region that the request looks into. - func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - let (statement, _) = try prepare(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 { - return region - } - - // Give up unless primary key is rowId - let primaryKeyInfo = try db.primaryKey(tableName) - guard primaryKeyInfo.isRowID else { - return region - } - - // Give up unless there is a where clause - guard let whereExpression = try wherePromise.resolve(db) else { - return region - } - - // The whereExpression knows better - guard let rowIds = whereExpression.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { - return region - } - - // Database regions are case-insensitive: use the canonical table name - let canonicalTableName = try db.canonicalName(table: tableName) - return region.tableIntersection(canonicalTableName, rowIds: rowIds) - } - - private var countQuery: QueryInterfaceSelectQueryDefinition { - guard groupByExpressions.isEmpty && limit == nil else { - // SELECT ... GROUP BY ... - // SELECT ... LIMIT ... - return trivialCountQuery - } - - guard let source = source, case .table = source else { - // SELECT ... FROM (something which is not a table) - return trivialCountQuery - } - - assert(!selection.isEmpty) - if selection.count == 1 { - guard let count = self.selection[0].count(distinct: isDistinct) else { - return trivialCountQuery - } - var countQuery = unorderedQuery - countQuery.isDistinct = false - countQuery.selection = [count.sqlSelectable] - return countQuery - } else { - // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... - - guard !isDistinct else { - return trivialCountQuery - } - - // SELECT expr1, expr2, ... FROM tableName ... - // -> - // SELECT COUNT(*) FROM tableName ... - var countQuery = unorderedQuery - countQuery.selection = [SQLExpressionCount(AllColumns())] - return countQuery - } - } - - // SELECT COUNT(*) FROM (self) - private var trivialCountQuery: QueryInterfaceSelectQueryDefinition { - return QueryInterfaceSelectQueryDefinition( - select: [SQLExpressionCount(AllColumns())], - from: .query(query: unorderedQuery, alias: nil)) - } -} - -indirect enum SQLSource { - case table(name: String, alias: String?) - case query(query: QueryInterfaceSelectQueryDefinition, alias: String?) - - func sourceSQL(_ db: Database, _ arguments: inout StatementArguments?) throws -> String { - switch self { - case .table(let table, let alias): - if let alias = alias { - return table.quotedDatabaseIdentifier + " AS " + alias.quotedDatabaseIdentifier - } else { - return table.quotedDatabaseIdentifier - } - case .query(let query, let alias): - if let alias = alias { - return try "(" + query.sql(db, &arguments) + ") AS " + alias.quotedDatabaseIdentifier - } else { - return try "(" + query.sql(db, &arguments) + ")" - } - } - } -} - -struct SQLLimit { - let limit: Int - let offset: Int? - - var sql: String { - if let offset = offset { - return "\(limit) OFFSET \(offset)" - } else { - return "\(limit)" - } - } -} - -extension SQLCount { - var sqlSelectable: SQLSelectable { - switch self { - case .all: - return SQLExpressionCount(AllColumns()) - case .distinct(let expression): - return SQLExpressionCountDistinct(expression) - } - } -} diff --git a/GRDB/QueryInterface/QueryOrdering.swift b/GRDB/QueryInterface/QueryOrdering.swift new file mode 100644 index 000000000..9d8822f01 --- /dev/null +++ b/GRDB/QueryInterface/QueryOrdering.swift @@ -0,0 +1,81 @@ +/// QueryOrdering provides the order clause to QueryInterfaceQuery +/// and AssociationQuery. +struct QueryOrdering { + private var elements: [Element] = [] + var isReversed: Bool + + private enum Element { + case orderingTerms((Database) throws -> [SQLOrderingTerm]) + case queryOrdering(QueryOrdering) + + var reversed: Element { + switch self { + case .orderingTerms(let orderings): + return .orderingTerms { db in try orderings(db).map { $0.reversed } } + case .queryOrdering(let queryOrdering): + return .queryOrdering(queryOrdering.reversed) + } + } + + func qualified(with alias: TableAlias) -> Element { + switch self { + case .orderingTerms(let orderings): + return .orderingTerms { db in try orderings(db).map { $0.qualifiedOrdering(with: alias) } } + case .queryOrdering(let queryOrdering): + return .queryOrdering(queryOrdering.qualified(with: alias)) + } + } + + func resolve(_ db: Database) throws -> [SQLOrderingTerm] { + switch self { + case .orderingTerms(let orderings): + return try orderings(db) + case .queryOrdering(let queryOrdering): + return try queryOrdering.resolve(db) + } + } + } + + private init(elements: [Element], isReversed: Bool) { + self.elements = elements + self.isReversed = isReversed + } + + init() { + self.init( + elements: [], + isReversed: false) + } + + init(orderings: @escaping (Database) throws -> [SQLOrderingTerm]) { + self.init( + elements: [.orderingTerms(orderings)], + isReversed: false) + } + + var reversed: QueryOrdering { + return QueryOrdering( + elements: elements, + isReversed: !isReversed) + } + + func qualified(with alias: TableAlias) -> QueryOrdering { + return QueryOrdering( + elements: elements.map { $0.qualified(with: alias) }, + isReversed: isReversed) + } + + func appending(_ ordering: QueryOrdering) -> QueryOrdering { + return QueryOrdering( + elements: elements + [.queryOrdering(ordering)], + isReversed: isReversed) + } + + func resolve(_ db: Database) throws -> [SQLOrderingTerm] { + if isReversed { + return try elements.flatMap { try $0.reversed.resolve(db) } + } else { + return try elements.flatMap { try $0.resolve(db) } + } + } +} diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift new file mode 100644 index 000000000..9182a9eb7 --- /dev/null +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -0,0 +1,357 @@ +// MARK: - SelectionRequest + +/// The protocol for all requests that can refine their selection. +public protocol SelectionRequest { + /// Creates a request with a new set of selected columns. + /// + /// // SELECT id, email FROM player + /// var request = Player.all() + /// request = request.select([Column("id"), Column("email")]) + /// + /// Any previous selection is replaced: + /// + /// // SELECT email FROM player + /// request + /// .select([Column("id")]) + /// .select([Column("email")]) + func select(_ selection: [SQLSelectable]) -> Self +} + +extension SelectionRequest { + /// Creates a request with a new set of selected columns. + /// + /// // SELECT id, email FROM player + /// var request = Player.all() + /// request = request.select(Column("id"), Column("email")) + /// + /// Any previous selection is replaced: + /// + /// // SELECT email FROM player + /// request + /// .select(Column("id")) + /// .select(Column("email")) + public func select(_ selection: SQLSelectable...) -> Self { + return select(selection) + } + + /// Creates a request with a new set of selected columns. + /// + /// // SELECT id, email FROM player + /// var request = Player.all() + /// request = request.select(sql: "id, email") + /// + /// Any previous selection is replaced: + /// + /// // SELECT email FROM player + /// request + /// .select(sql: "id") + /// .select(sql: "email") + public func select(sql: String, arguments: StatementArguments? = nil) -> Self { + return select(SQLSelectionLiteral(sql, arguments: arguments)) + } +} + +// MARK: - FilteredRequest + +/// The protocol for all requests that can be filtered. +public protocol FilteredRequest { + /// Creates a request with the provided *predicate promise* added to the + /// eventual set of already applied predicates. + /// + /// // SELECT * FROM player WHERE 1 + /// var request = Player.all() + /// 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 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 columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { + fatalError("table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))") + } + + let lowercaseColumns = columns.map { $0.lowercased() } + return key + // Preserve ordering of columns in the unique index + .sorted { (kv1, kv2) in + let index1 = lowercaseColumns.index(of: kv1.key.lowercased())! + let index2 = lowercaseColumns.index(of: kv2.key.lowercased())! + return index1 < index2 + } + .map { (column, value) in Column(column) == value } + .joined(operator: .and) + } + .joined(operator: .or) + } + } +} + +extension TableRequest where Self: OrderedRequest { + /// Creates a request ordered by primary key. + public func orderByPrimaryKey() -> Self { + let tableName = self.databaseTableName + return order { db in + try db.primaryKey(tableName).columns.map { Column($0) } + } + } +} + +// MARK: - AggregatingRequest + +/// The protocol for all requests that can aggregate. +public protocol AggregatingRequest { + /// Creates a request grouped according to *expressions*. + func group(_ expressions: [SQLExpressible]) -> Self + + /// Creates a request with the provided *predicate* added to the + /// eventual set of already applied predicates. + func having(_ predicate: SQLExpressible) -> Self +} + +extension AggregatingRequest { + /// Creates a request grouped according to *expressions*. + public func group(_ expressions: SQLExpressible...) -> Self { + return group(expressions) + } + + /// Creates a request with a new grouping. + public func group(sql: String, arguments: StatementArguments? = nil) -> Self { + // This "expression" is not a real expression. We support raw sql which + // actually contains several expressions: + // + // request = Player.group(sql: "teamId, level") + // + // This is why we use the "unsafe" flag, so that the SQLExpressionLiteral + // does not output its safe wrapping parenthesis, and generates + // invalid SQL. + var expression = SQLExpressionLiteral(sql, arguments: arguments) + expression.unsafeRaw = true + return group(expression) + } + + /// Creates a request with the provided *sql* added to the + /// eventual set of already applied predicates. + public func having(sql: String, arguments: StatementArguments? = nil) -> Self { + return having(SQLExpressionLiteral(sql, arguments: arguments)) + } +} + +// MARK: - OrderedRequest + +/// The protocol for all requests that be ordered. +public protocol OrderedRequest { + /// Creates a request with the provided *orderings promise*. + /// + /// // SELECT * FROM player ORDER BY name + /// var request = Player.all() + /// request = request.order { _ in [Column("name")] } + /// + /// Any previous ordering is replaced: + /// + /// // SELECT * FROM player ORDER BY name + /// request + /// .order{ _ in [Column("email")] } + /// .reversed() + /// .order{ _ in [Column("name")] } + func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self + + /// Creates a request that reverses applied orderings. + /// + /// // 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() + func reversed() -> Self +} + +extension OrderedRequest { + /// Creates a request with the provided *orderings*. + /// + /// // SELECT * FROM player ORDER BY name + /// var request = Player.all() + /// request = request.order(Column("name")) + /// + /// Any previous ordering is replaced: + /// + /// // SELECT * FROM player ORDER BY name + /// request + /// .order(Column("email")) + /// .reversed() + /// .order(Column("name")) + public func order(_ orderings: SQLOrderingTerm...) -> Self { + return order { _ in orderings } + } + + /// Creates a request with the provided *orderings*. + /// + /// // SELECT * FROM player ORDER BY name + /// var request = Player.all() + /// request = request.order(Column("name")) + /// + /// Any previous ordering is replaced: + /// + /// // SELECT * FROM player ORDER BY name + /// request + /// .order(Column("email")) + /// .reversed() + /// .order(Column("name")) + public func order(_ orderings: [SQLOrderingTerm]) -> Self { + return order { _ in orderings } + } + + /// Creates a request with the provided *sql* used for sorting. + /// + /// // SELECT * FROM player ORDER BY name + /// var request = Player.all() + /// request = request.order(sql: "name") + /// + /// Any previous ordering is replaced: + /// + /// // SELECT * FROM player ORDER BY name + /// request + /// .order(sql: "email") + /// .order(sql: "name") + public func order(sql: String, arguments: StatementArguments? = nil) -> Self { + // This "expression" is not a real expression. We support raw sql which + // actually contains several expressions: + // + // request = Player.order(sql: "teamId, level") + // + // This is why we use the "unsafe" flag, so that the SQLExpressionLiteral + // does not output its safe wrapping parenthesis, and generates + // invalid SQL. + var expression = SQLExpressionLiteral(sql, arguments: arguments) + expression.unsafeRaw = true + return order([expression]) + } +} + +// MARK: - DerivableRequest + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// The base protocol for all requests that can be refined. +public protocol DerivableRequest: SelectionRequest, FilteredRequest, OrderedRequest { + associatedtype RowDecoder +} diff --git a/GRDB/QueryInterface/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQLCollatedExpression.swift index 492f625cc..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 { @@ -51,16 +51,20 @@ public struct SQLCollatedExpression { extension SQLCollatedExpression : SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public var reversed: SQLOrderingTerm { return desc } /// [**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 1991a8a66..f90778684 100644 --- a/GRDB/QueryInterface/SQLExpressible.swift +++ b/GRDB/QueryInterface/SQLExpressible.swift @@ -57,17 +57,15 @@ public protocol SQLSpecificExpressible : SQLExpressible { extension SQLExpressible where Self: SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public var reversed: SQLOrderingTerm { return SQLOrdering.desc(sqlExpression) } /// [**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) } } @@ -76,28 +74,24 @@ extension SQLExpressible where Self: SQLOrderingTerm { 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) - /// /// :nodoc: public func count(distinct: Bool) -> SQLCount? { return sqlExpression.count(distinct: distinct) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func columnCount(_ db: Database) throws -> Int { return 1 diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index ce34318f3..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) } } @@ -46,6 +46,12 @@ public struct SQLExpressionLiteral : SQLExpression { /// SQL literal public let arguments: StatementArguments? + /// If safe, an SQLExpressionLiteral("foo") wraps itself in parenthesis, + /// and outputs "(foo)" in SQL queries. This avoids any bug due to operator + /// precedence. When unsafe, the expression literal does not wrap itself + /// in parenthesis and outputs its raw sql. + var unsafeRaw: Bool = false + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Creates an SQL literal expression. @@ -59,24 +65,31 @@ 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 } - return sql + if unsafeRaw { + return sql + } else { + return "(" + sql + ")" + } } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: - public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionLiteral { + 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 } } @@ -129,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) @@ -156,17 +167,21 @@ 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 qualified(by qualifier: SQLTableQualifier) -> SQLExpressionUnary { - return SQLExpressionUnary(op, expression.qualified(by: 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)) } } @@ -221,30 +236,6 @@ public struct SQLBinaryOperator : Hashable { public static func == (lhs: SQLBinaryOperator, rhs: SQLBinaryOperator) -> Bool { return lhs.sql == rhs.sql } - - // TODO: make it an extension of Sequence (like joined(separator:)) when Swift can better handle existentials - // TODO: make it public eventually - /// Return nil if expressions is empty. - func join(_ expressions: [SQLExpression]) -> SQLExpression? { - switch expressions.count { - case 0: - return nil - case 1: - return expressions[0] - default: - let literals = expressions.map { $0.literal } - let firstLiteral = literals[0] - var sql = firstLiteral.sql - var arguments = firstLiteral.arguments ?? StatementArguments() - for literal in literals.suffix(from: 1) { - sql += " \(self.sql) \(literal.sql)" - if let args = literal.arguments { - arguments += args - } - } - return SQLExpressionLiteral("(\(sql))", arguments: arguments.isEmpty ? nil : arguments) - } - } } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -285,11 +276,13 @@ public struct SQLExpressionBinary : SQLExpression { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return "(" + lhs.expressionSQL(&arguments) + " " + op.sql + " " + rhs.expressionSQL(&arguments) + ")" + /// :nodoc: + 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) + /// :nodoc: public var negated: SQLExpression { if let negatedOp = op.negated { return SQLExpressionBinary(negatedOp, lhs, rhs) @@ -297,63 +290,187 @@ 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) - public func matchedRowIds(rowIdName: String?) -> Set? { + /// :nodoc: + 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 == 1` or `id IS 1`? - switch (lhs, rhs) { - case (let column as Column, let dbValue as DatabaseValue), - (let dbValue as DatabaseValue, let column as Column): - // Look for `id == 1`, `rowid == 1`, `1 == id`, `1 == rowid` - + // Look for `id ==/IS 1`, `rowid ==/IS 1`, `1 ==/IS id`, `1 ==/IS rowid` + func matchedRowIds(column: ColumnExpression, dbValue: DatabaseValue) -> Set? { var rowIdNames = [Column.rowID.name.lowercased()] if let rowIdName = rowIdName { rowIdNames.append(rowIdName.lowercased()) } - guard rowIdNames.contains(column.name.lowercased()) else { return nil } - if let rowId = Int64.fromDatabaseValue(dbValue) { return [rowId] } else { return [] } + } + switch (lhs, rhs) { + case (let column as ColumnExpression, let dbValue as DatabaseValue): + return matchedRowIds(column: column, dbValue: dbValue) + case (let dbValue as DatabaseValue, let column as ColumnExpression): + return matchedRowIds(column: column, dbValue: dbValue) default: return nil } - case .and: - let lids = lhs.matchedRowIds(rowIdName: rowIdName) - let rids = rhs.matchedRowIds(rowIdName: rowIdName) - switch (lids, rids) { - case (nil, nil): return nil - case let (ids?, nil), let (nil, ids?): return ids - case let (lids?, rids?): return lids.intersection(rids) - } - - case .or: - let lids = lhs.matchedRowIds(rowIdName: rowIdName) - let rids = rhs.matchedRowIds(rowIdName: rowIdName) - switch (lids, rids) { - case let (lids?, rids?): return lids.union(rids) - default: return nil - } - - default: + case .notEqual, .isNot: return nil } } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// :nodoc: - public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionBinary { - return SQLExpressionBinary(op, lhs.qualified(by: qualifier), rhs.qualified(by: qualifier)) - } } // MARK: - SQLExpressionContains @@ -374,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) + "))" } @@ -386,10 +503,18 @@ 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 aliases // Look for `id IN (1, 2, 3)` - guard let column = expression as? Column, + guard let column = expression as? ColumnExpression, let array = collection as? SQLExpressionsArray else { return nil @@ -399,7 +524,7 @@ struct SQLExpressionContains : SQLExpression { if let rowIdName = rowIdName { rowIdNames.append(rowIdName.lowercased()) } - + guard rowIdNames.contains(column.name.lowercased()) else { return nil } @@ -413,10 +538,6 @@ struct SQLExpressionContains : SQLExpression { } return rowIDs } - - func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionContains { - return SQLExpressionContains(expression.qualified(by: qualifier), collection, negated: isNegated) - } } // MARK: - SQLExpressionBetween @@ -439,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) + ")" } @@ -453,11 +574,19 @@ struct SQLExpressionBetween : SQLExpression { return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) } - func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionBetween { + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return SQLExpressionBetween( - expression.qualified(by: qualifier), - lowerBound.qualified(by: qualifier), - upperBound.qualified(by: 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) } } @@ -473,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) /// @@ -485,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) @@ -544,15 +657,21 @@ public struct SQLExpressionFunction : SQLExpression { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return functionName.sql + "(" + (self.arguments.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") + ")" + /// :nodoc: + 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 qualified(by qualifier: SQLTableQualifier) -> SQLExpressionFunction { - return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualified(by: 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) }) } } @@ -570,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 qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCount { - return SQLExpressionCount(counted.qualified(by: qualifier)) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionCount(counted.qualifiedSelectable(with: alias)) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return self } } @@ -592,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 qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCountDistinct { - return SQLExpressionCountDistinct(counted.qualified(by: 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)) } } @@ -616,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 { @@ -625,7 +775,11 @@ struct SQLExpressionCollate : SQLExpression { } } - func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCollate { - return SQLExpressionCollate(expression.qualified(by: 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 9922a669c..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,7 +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 alias: TableAlias) -> SQLExpression + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression } extension SQLExpression { @@ -84,6 +75,24 @@ extension SQLExpression { public func matchedRowIds(rowIdName: String?) -> Set? { return nil } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// The default implementation returns qualifiedExpression(with:) + /// + /// :nodoc: + 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) + } } // SQLExpression: SQLExpressible @@ -91,7 +100,6 @@ extension SQLExpression { extension SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public var sqlExpression: SQLExpression { return self @@ -103,7 +111,6 @@ extension SQLExpression { extension SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func count(distinct: Bool) -> SQLCount? { if distinct { @@ -129,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 qualified(by qualifier: SQLTableQualifier) -> SQLExpressionNot { - return SQLExpressionNot(expression.qualified(by: 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..2fbdbff00 --- /dev/null +++ b/GRDB/QueryInterface/SQLGenerationContext.swift @@ -0,0 +1,306 @@ +/// 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] ?? 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) +/// +/// A TableAlias identifies a table in a request. +public class TableAlias: Hashable { + private var impl: Impl + private enum Impl { + /// A TableAlias is undefined when it is created by the GRDB user: + /// + /// let alias = TableAlias() + /// let alias = TableAlias(name: "custom") + case undefined(userName: String?) + + /// A TableAlias is a table when explicitly specified: + /// + /// let alias = TableAlias(tableName: "player") + /// + /// Or when it qualifies a request that wasn't qualified yet (in which + /// case it turns from undefined to a table): + /// + /// // SELECT custom.* FROM player custom + /// let alias = TableAlias(name: "custom") + /// let request = Player.all().aliased(alias) + case table(tableName: String, userName: String?) + + /// A TableAlias can be a proxy for another table alias. Two different + /// instances for the same table identifier: + /// + /// // Pointless example: make alias2 a proxy for alias1 + /// let alias1 = TableAlias() + /// let alias2 = TableAlias() + /// Player.all() + /// .aliased(alias1) + /// .aliased(alias2) + /// + /// Proxies are useful because queries get implicit aliases as soon + /// as they are joined with associations. In the example below, + /// customAlias becomes a proxy for the request's implicit alias, which + /// gets a custom name. This allows implicit and user aliases to merge + /// into a single "table identifier" that matches the user's expectations: + /// + /// // SELECT custom.*, team.* + /// // FROM player custom + /// // JOIN team ON taem.id = custom.teamId + /// // WHERE custom.name = 'Arthur' + /// let customAlias = TableAlias(name: "custom") + /// let request = Player + /// .including(required: Player.team) + /// .filter(sql: "custom.name = 'Arthur'") + /// .aliased(customAlias) + case proxy(TableAlias) + } + + /// Resolve all proxies + private var root: TableAlias { + if case .proxy(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: + // Likely a GRDB bug + fatalError("Undefined alias has no table name") + case .table(tableName: let tableName, userName: _): + return tableName + case .proxy(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 .proxy(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 becomeProxy(of base: TableAlias) { + switch impl { + case .undefined(let userName): + if let userName = userName { + // rename + base.setUserName(userName) + } + self.impl = .proxy(base) + default: + // Likely a GRDB bug + fatalError("Not implemented") + } + } + + private 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 .proxy(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: _): + // It is a programmer error to reuse the same TableAlias for + // multiple tables. + // + // // Don't do that + // let alias = TableAlias() + // let books = Book.aliased(alias)... + // let authors = Author.aliased(alias)... + GRDBPrecondition( + tableName.lowercased() == initialTableName.lowercased(), + "A TableAlias most not be used to refer to multiple tables") + case .proxy(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 { + return ObjectIdentifier(root).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] { + // It is a programmer error to reuse the same TableAlias for + // multiple tables. + // + // // Don't do that + // let alias = TableAlias() + // let request = Book + // .including(required: Book.author.aliased(alias)...) + // .including(required: Book.author.aliased(alias)...) + GRDBPrecondition(count == Set(self).count, "A TableAlias most not be used to refer to multiple tables") + + let groups = Dictionary(grouping: self) { + $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 78d2da736..411b88829 100644 --- a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift @@ -3,56 +3,39 @@ /// AllColumns is the `*` in `SELECT *`. /// /// You use AllColumns in your custom implementation of -/// TableMapping.databaseSelection. +/// TableRecord.databaseSelection. /// /// For example: /// -/// struct Player : TableMapping { -/// static var databaseTableName = "players" +/// struct Player : TableRecord { +/// 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 { - private var qualifier: SQLTableQualifier? - - /// public init() { } } extension AllColumns : SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: - public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - if let qualifierName = qualifier?.name { - return qualifierName.quotedDatabaseIdentifier + ".*" - } + 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 { - guard qualifier == nil else { - // SELECT COUNT(t.*) is invalid SQL - fatalError("Not implemented, or invalid query") - } + public func countedSQL(_ context: inout SQLGenerationContext) -> String { return "*" } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func count(distinct: Bool) -> SQLCount? { // SELECT DISTINCT * FROM tableName ... - guard !distinct else { - return nil - } - - guard qualifier == nil else { + if distinct { return nil } @@ -63,55 +46,84 @@ extension AllColumns : SQLSelectable { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: - public func qualified(by qualifier: SQLTableQualifier) -> AllColumns { - if self.qualifier != nil { - // Never requalify - return self - } - var allColumns = AllColumns() - allColumns.qualifier = qualifier - return allColumns + 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 { - guard let qualifier = qualifier else { - fatalError("Can't compute number of columns without a qualifier") - } - return try db.columns(in: qualifier.tableName).count + fatalError("Can't compute number of columns without an alias") } } +// MARK: - QualifiedAllColumns + +/// QualifiedAllColumns is the `t.*` in `SELECT t.*`. +struct QualifiedAllColumns { + private let alias: TableAlias + + init(alias: TableAlias) { + self.alias = alias + } +} + +extension QualifiedAllColumns : SQLSelectable { + func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { + if let qualifier = context.qualifier(for: alias) { + return qualifier.quotedDatabaseIdentifier + ".*" + } + return "*" + } + + 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 alias: TableAlias) -> SQLSelectable { + // Never requalify + return self + } + + func columnCount(_ db: Database) throws -> Int { + return try db.columns(in: alias.tableName).count + } +} // MARK: - SQLAliasedExpression 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 qualified(by qualifier: SQLTableQualifier) -> SQLAliasedExpression { - return SQLAliasedExpression(expression.qualified(by: 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 257269eea..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,23 +20,45 @@ public protocol SQLSelectable { func columnCount(_ db: Database) throws -> Int /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func qualified(by qualifier: SQLTableQualifier) -> Self + func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable } -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// :nodoc: -public class SQLTableQualifier { - var tableName: String - private var alias: String? +// MARK: - SQLSelectionLiteral + +struct SQLSelectionLiteral : SQLSelectable { + let sql: String + let arguments: StatementArguments? - init(tableName: String, alias: String?) { - self.tableName = tableName - self.alias = alias + init(_ sql: String, arguments: StatementArguments? = nil) { + self.sql = sql + self.arguments = arguments } - var name: String? { - return alias + 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") + } + } + return sql + } + + func countedSQL(_ context: inout SQLGenerationContext) -> String { + fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.") + } + + func count(distinct: Bool) -> SQLCount? { + fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.") + } + + func columnCount(_ db: Database) throws -> Int { + fatalError("Selection literals don't known how many columns they contain. To resolve this error, select one or several SQLExpressionLiteral instead.") + } + + func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + return self } } 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 4dde080e2..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) } @@ -697,20 +683,12 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE // MARK: - Logical Operators (AND, OR, NOT) -extension SQLBinaryOperator { - /// The `AND` binary operator - static let and = SQLBinaryOperator("AND") - - /// The `OR` binary operator - static let or = SQLBinaryOperator("OR") -} - /// A logical SQL expression with the `AND` SQL operator. /// /// // favorite AND 0 /// Column("favorite") && false public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.and, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -718,7 +696,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 AND favorite /// false && Column("favorite") public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.and, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -726,7 +704,7 @@ public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NOT NULL AND favorite /// Column("email") != nil && Column("favorite") public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.and, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -734,7 +712,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // favorite OR 1 /// Column("favorite") || true public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.or, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -742,7 +720,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 OR favorite /// true || Column("favorite") public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.or, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -750,7 +728,7 @@ public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NULL OR hidden /// Column("email") == nil || Column("hidden") public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.or, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) } /// A negated logical SQL expression with the `NOT` SQL operator. @@ -766,6 +744,43 @@ public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression { return value.sqlExpression.negated } +public enum SQLLogicalBinaryOperator { + case and, or +} + +extension Sequence where Element == SQLExpression { + /// Returns an expression by joining all elements with an SQL + /// logical operator. + /// + /// For example: + /// + /// // SELECT * FROM player + /// // WHERE (registered + /// // AND (score >= 1000) + /// // AND (name IS NOT NULL)) + /// let conditions = [ + /// Column("registered"), + /// Column("score") >= 1000, + /// Column("name") != nil] + /// Player.filter(conditions.joined(operator: .and)) + /// + /// When the sequence is empty, `joined(operator: .and)` returns true, + /// and `joined(operator: .or)` returns false: + /// + /// // SELECT * FROM player WHERE 1 + /// Player.filter([].joined(operator: .and)) + /// + /// // SELECT * FROM player WHERE 0 + /// Player.filter([].joined(operator: .or)) + public func joined(operator: SQLLogicalBinaryOperator) -> SQLExpression { + let expressions = Array(self) + switch `operator` { + case .and: return SQLExpressionAnd(expressions) + case .or: return SQLExpressionOr(expressions) + } + } +} + // MARK: - Like Operator diff --git a/GRDB/QueryInterface/TableDefinition.swift b/GRDB/QueryInterface/TableDefinition.swift index 52b704542..ca8b231df 100644 --- a/GRDB/QueryInterface/TableDefinition.swift +++ b/GRDB/QueryInterface/TableDefinition.swift @@ -5,8 +5,8 @@ extension Database { #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Creates a database table. /// - /// try db.create(table: "pointOfInterests") { t in - /// t.column("id", .integer).primaryKey() + /// try db.create(table: "place") { t in + /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// t.column("favorite", .boolean).notNull().default(false) /// t.column("longitude", .double).notNull() @@ -34,8 +34,8 @@ extension Database { #else /// Creates a database table. /// - /// try db.create(table: "pointOfInterests") { t in - /// t.column("id", .integer).primaryKey() + /// try db.create(table: "place") { t in + /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// t.column("favorite", .boolean).notNull().default(false) /// t.column("longitude", .double).notNull() @@ -66,8 +66,8 @@ extension Database { /// Creates a database table. /// - /// try db.create(table: "pointOfInterests") { t in - /// t.column("id", .integer).primaryKey() + /// try db.create(table: "place") { t in + /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// t.column("favorite", .boolean).notNull().default(false) /// t.column("longitude", .double).notNull() @@ -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(...) /// } /// @@ -248,9 +248,41 @@ public final class TableDefinition { self.withoutRowID = withoutRowID } + /// Defines the auto-incremented primary key. + /// + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// } + /// + /// The auto-incremented primary key is an integer primary key that + /// automatically generates unused values when you do not explicitly + /// provide one, and prevents the reuse of ids over the lifetime of + /// the database. + /// + /// **It is the preferred way to define a numeric primary key**. + /// + /// The fact that an auto-incremented primary key prevents the reuse of + /// ids is an excellent guard against data races that could happen when your + /// application processes ids in an asynchronous way. The auto-incremented + /// primary key provides the guarantee that a given id can't reference a row + /// that is different from the one it used to be at the beginning of the + /// asynchronous process, even if this row gets deleted and a new one is + /// inserted in between. + /// + /// See https://www.sqlite.org/lang_createtable.html#primkeyconst and + /// https://www.sqlite.org/lang_createtable.html#rowid + /// + /// - parameter conflitResolution: An optional conflict resolution + /// (see https://www.sqlite.org/lang_conflict.html). + /// - returns: Self so that you can further refine the column definition. + @discardableResult + public func autoIncrementedPrimaryKey(_ name: String, onConflict conflictResolution: Database.ConflictResolution? = nil) -> ColumnDefinition { + return column(name, .integer).primaryKey(onConflict: conflictResolution, autoincrement: true) + } + /// Appends a table column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("name", .text) /// } /// @@ -269,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"]) @@ -291,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"]) @@ -312,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 @@ -333,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") @@ -350,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") @@ -360,7 +392,9 @@ public final class TableDefinition { /// /// - parameter sql: An SQL snippet public func check(sql: String) { - checkConstraints.append(SQLExpressionLiteral(sql)) + var expression = SQLExpressionLiteral(sql) + expression.unsafeRaw = true // It's safe because this expression can't be composed with others + checkConstraints.append(expression) } fileprivate func sql(_ db: Database) throws -> String { @@ -475,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: ...) /// } /// @@ -490,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) /// } /// @@ -532,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 /// } /// @@ -565,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() /// } /// @@ -585,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() /// } /// @@ -602,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() /// } /// @@ -619,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() /// } /// @@ -636,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 } /// } /// @@ -653,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") /// } /// @@ -663,13 +697,15 @@ public final class ColumnDefinition { /// - returns: Self so that you can further refine the column definition. @discardableResult public func check(sql: String) -> Self { - checkConstraints.append(SQLExpressionLiteral(sql)) + var expression = SQLExpressionLiteral(sql) + expression.unsafeRaw = true // It's safe because this expression can't be composed with others + checkConstraints.append(expression) return self } /// 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") /// } /// @@ -685,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") /// } /// @@ -695,13 +731,15 @@ public final class ColumnDefinition { /// - returns: Self so that you can further refine the column definition. @discardableResult public func defaults(sql: String) -> Self { - defaultExpression = SQLExpressionLiteral(sql) + var expression = SQLExpressionLiteral(sql) + expression.unsafeRaw = true // It's safe because this expression can't be composed with others + defaultExpression = expression return self } // 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) /// } /// @@ -717,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) /// } /// @@ -733,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/RowConvertible+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift similarity index 89% rename from GRDB/Record/RowConvertible+Decodable.swift rename to GRDB/Record/FetchableRecord+Decodable.swift index b8ba94af2..44e510cfa 100644 --- a/GRDB/Record/RowConvertible+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -13,7 +13,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer var allKeys: [Key] { let row = decoder.row let columnNames = Set(row.columnNames) - let scopeNames = row.scopeNames + let scopeNames = Set(row.scopesTree.names) return columnNames.union(scopeNames).compactMap { Key(stringValue: $0) } } @@ -25,7 +25,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - returns: Whether the `Decoder` has an entry for the given key. func contains(_ key: Key) -> Bool { let row = decoder.row - return row.hasColumn(key.stringValue) || (row.scoped(on: key.stringValue) != nil) + return row.hasColumn(key.stringValue) || (row.scopesTree[key.stringValue] != nil) } /// Decodes a null value for the given key. @@ -35,7 +35,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. func decodeNil(forKey key: Key) throws -> Bool { let row = decoder.row - return row[key.stringValue] == nil && (row.scoped(on: key.stringValue) == nil) + return row[key.stringValue] == nil && (row.scopesTree[key.stringValue] == nil) } /// Decodes a value of the given type for the given key. @@ -69,7 +69,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable { let row = decoder.row - // Try column + // Column? if row.hasColumn(key.stringValue) { let dbValue: DatabaseValue = row[key.stringValue] if let type = T.self as? DatabaseValueConvertible.Type { @@ -83,9 +83,15 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer } } - // Fallback on scope - if let scopedRow = row.scoped(on: key.stringValue), scopedRow.containsNonNullValue { - return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key])) + // Scope? + if let scopedRow = row.scopesTree[key.stringValue], scopedRow.containsNonNullValue { + if let type = T.self as? FetchableRecord.Type { + // Prefer FetchableRecord decoding over Decodable. + // This allows custom row decoding + return (type.init(row: scopedRow) as! T) + } else { + return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key])) + } } return nil @@ -102,7 +108,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer func decode(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { let row = decoder.row - // Try column + // Column? if row.hasColumn(key.stringValue) { let dbValue: DatabaseValue = row[key.stringValue] if let type = T.self as? DatabaseValueConvertible.Type { @@ -114,13 +120,25 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer } } - // Fallback on scope - if let scopedRow = row.scoped(on: key.stringValue) { - return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key])) + // Scope? + if let scopedRow = row.scopesTree[key.stringValue] { + if let type = T.self as? FetchableRecord.Type { + // Prefer FetchableRecord decoding over Decodable. + // This allows custom row decoding + return type.init(row: scopedRow) as! T + } else { + return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key])) + } } - let path = (codingPath.map { $0.stringValue } + [key.stringValue]).joined(separator: ".") - fatalError("No such column or scope: \(path)") + // Base row + if let type = T.self as? FetchableRecord.Type { + // Prefer FetchableRecord decoding over Decodable. + // This allows custom row decoding + return type.init(row: row) as! T + } else { + return try T(from: RowDecoder(row: row, codingPath: codingPath + [key])) + } } /// Returns the data stored for the given key as represented in a container keyed by the given key type. @@ -249,7 +267,7 @@ private struct RowDecoder: Decoder { } } -extension RowConvertible where Self: Decodable { +extension FetchableRecord where Self: Decodable { /// Initializes a record from `row`. public init(row: Row) { try! self.init(from: RowDecoder(row: row, codingPath: [])) diff --git a/GRDB/Record/RowConvertible+TableMapping.swift b/GRDB/Record/FetchableRecord+TableRecord.swift similarity index 90% rename from GRDB/Record/RowConvertible+TableMapping.swift rename to GRDB/Record/FetchableRecord+TableRecord.swift index 409ac2709..937736486 100644 --- a/GRDB/Record/RowConvertible+TableMapping.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -1,10 +1,10 @@ -extension RowConvertible where Self: TableMapping { +extension FetchableRecord where Self: TableRecord { // MARK: Fetching All /// 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 /// ... @@ -18,8 +18,8 @@ extension RowConvertible where Self: TableMapping { /// The cursor must be iterated in a protected dispath queue. /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. /// /// - parameter db: A database connection. /// - returns: A cursor over fetched records. @@ -30,12 +30,12 @@ extension RowConvertible where Self: TableMapping { /// 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 - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @@ -45,12 +45,12 @@ extension RowConvertible where Self: TableMapping { /// 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 - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @@ -59,7 +59,7 @@ extension RowConvertible where Self: TableMapping { } } -extension RowConvertible where Self: TableMapping { +extension FetchableRecord where Self: TableRecord { // MARK: Fetching by Single-Column Primary Key @@ -119,7 +119,7 @@ extension RowConvertible where Self: TableMapping { } } -extension RowConvertible where Self: TableMapping { +extension FetchableRecord where Self: TableRecord { // MARK: Fetching by Key diff --git a/GRDB/Record/RowConvertible.swift b/GRDB/Record/FetchableRecord.swift similarity index 69% rename from GRDB/Record/RowConvertible.swift rename to GRDB/Record/FetchableRecord.swift index 3162400e8..fa7db477e 100644 --- a/GRDB/Record/RowConvertible.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -4,7 +4,7 @@ import SQLite3 #endif -/// Types that adopt RowConvertible can be initialized from a database Row. +/// Types that adopt FetchableRecord can be initialized from a database Row. /// /// let row = try Row.fetchOne(db, "SELECT ...")! /// let player = Player(row) @@ -21,8 +21,8 @@ /// try Player.fetchAll(statement, arguments:...) // [Player] /// try Player.fetchOne(statement, arguments:...) // Player? /// -/// RowConvertible is adopted by Record. -public protocol RowConvertible { +/// FetchableRecord is adopted by Record. +public protocol FetchableRecord { /// Creates a record from `row`. /// @@ -34,11 +34,11 @@ public protocol RowConvertible { /// A cursor of records. For example: /// -/// struct Player : RowConvertible { ... } -/// try dbQueue.inDatabase { db in -/// let players: RecordCursor = try Player.fetchCursor(db, "SELECT * FROM players") +/// struct Player : FetchableRecord { ... } +/// try dbQueue.read { db in +/// let players: RecordCursor = try Player.fetchCursor(db, "SELECT * FROM player") /// } -public final class RecordCursor : Cursor { +public final class RecordCursor : Cursor { private let statement: SelectStatement private let row: Row // Reused for performance private let sqliteStatement: SQLiteStatement @@ -67,13 +67,13 @@ public final class RecordCursor : Cursor { } } -extension RowConvertible { +extension FetchableRecord { // MARK: Fetching From SelectStatement /// 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 RowConvertible { /// 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 RowConvertible { /// 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: @@ -125,68 +125,13 @@ extension RowConvertible { } } -extension RowConvertible { - - // MARK: Fetching From Request - - /// Returns a cursor over records fetched from a fetch request. - /// - /// let nameColumn = Column("firstName") - /// let request = Player.order(nameColumn) - /// let identities = try Identity.fetchCursor(db, request) // Cursor of Identity - /// while let identity = try identities.next() { // Identity - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - request: A fetch request. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: Request) throws -> RecordCursor { - let (statement, adapter) = try request.prepare(db) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of records fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.order(nameColumn) - /// let identities = try Identity.fetchAll(db, request) // [Identity] - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] { - let (statement, adapter) = try request.prepare(db) - return try fetchAll(statement, adapter: adapter) - } - - /// Returns a single record fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.order(nameColumn) - /// let identity = try Identity.fetchOne(db, request) // Identity? - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? { - let (statement, adapter) = try request.prepare(db) - return try fetchOne(statement, adapter: adapter) - } -} - -extension RowConvertible { +extension FetchableRecord { // MARK: Fetching From SQL /// 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 /// ... /// } @@ -204,12 +149,12 @@ extension RowConvertible { /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor { - return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// 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. @@ -219,12 +164,12 @@ extension RowConvertible { /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { - return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// 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. @@ -234,6 +179,113 @@ extension RowConvertible { /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { - return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + } +} + +extension FetchableRecord { + + // MARK: Fetching From FetchRequest + + /// Returns a cursor over records fetched from a fetch request. + /// + /// let request = try Player.all() + /// let players = try Player.fetchCursor(db, request) // Cursor of Player + /// while let player = try players.next() { // Player + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameters: + /// - db: A database connection. + /// - sql: a FetchRequest. + /// - returns: A cursor over fetched records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: R) throws -> RecordCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + /// Returns an array of records fetched from a fetch request. + /// + /// let request = try Player.all() + /// let players = try Player.fetchAll(db, request) // [Player] + /// + /// - parameters: + /// - db: A database connection. + /// - sql: a FetchRequest. + /// - returns: An array of records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: R) throws -> [Self] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } + + /// Returns a single record fetched from a fetch request. + /// + /// let request = try Player.filter(key: 1) + /// let player = try Player.fetchOne(db, request) // Player? + /// + /// - parameters: + /// - db: A database connection. + /// - sql: a FetchRequest. + /// - returns: An optional record. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchOne(_ db: Database, _ request: R) throws -> Self? { + let (statement, adapter) = try request.prepare(db) + return try fetchOne(statement, adapter: adapter) + } +} + +extension FetchRequest where RowDecoder: FetchableRecord { + + // MARK: Fetching Records + + /// A cursor over fetched records. + /// + /// let request: ... // Some TypedRequest that fetches Player + /// let players = try request.fetchCursor(db) // Cursor of Player + /// while let player = try players.next() { // Player + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> RecordCursor { + return try RowDecoder.fetchCursor(db, self) + } + + /// An array of fetched records. + /// + /// let request: ... // Some TypedRequest that fetches Player + /// let players = try request.fetchAll(db) // [Player] + /// + /// - parameter db: A database connection. + /// - returns: An array of records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder] { + return try RowDecoder.fetchAll(db, self) + } + + /// The first fetched record. + /// + /// let request: ... // Some TypedRequest that fetches Player + /// let player = try request.fetchOne(db) // Player? + /// + /// - parameter db: A database connection. + /// - returns: An optional record. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder? { + return try RowDecoder.fetchOne(db, self) } } diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 9d23f784b..48dce6b61 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -9,7 +9,7 @@ import Foundation /// /// See https://github.com/groue/GRDB.swift#fetchedrecordscontroller for /// more information. -public final class FetchedRecordsController { +public final class FetchedRecordsController { // MARK: - Initialization @@ -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 }) /// @@ -47,7 +47,7 @@ public final class FetchedRecordsController { { try self.init( databaseWriter, - request: SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self), + request: SQLRequest(sql, arguments: arguments, adapter: adapter), queue: queue, isSameRecord: isSameRecord) } @@ -79,7 +79,7 @@ public final class FetchedRecordsController { request: Request, queue: DispatchQueue = .main, isSameRecord: ((Record, Record) -> Bool)? = nil) throws - where Request: TypedRequest, Request.RowDecoder == Record + where Request: FetchRequest, Request.RowDecoder == Record { let itemsAreIdenticalFactory: ItemComparatorFactory if let isSameRecord = isSameRecord { @@ -100,12 +100,14 @@ public final class FetchedRecordsController { request: Request, queue: DispatchQueue, itemsAreIdenticalFactory: @escaping ItemComparatorFactory) throws - where Request: TypedRequest, Request.RowDecoder == Record + where Request: FetchRequest, Request.RowDecoder == Record { self.itemsAreIdenticalFactory = itemsAreIdenticalFactory - self.request = request + self.request = ItemRequest(request) (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in - try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory) + let region = try request.databaseRegion(db) + let itemsAreIdentical = try itemsAreIdenticalFactory(db) + return (region, itemsAreIdentical) } self.databaseWriter = databaseWriter self.queue = queue @@ -130,7 +132,7 @@ public final class FetchedRecordsController { // observer is added on the same serialized queue as transaction // callbacks. try databaseWriter.write { db in - let initialItems = try Item.fetchAll(db, request) + let initialItems = try request.fetchAll(db) fetchedItems = initialItems if let fetchAndNotifyChanges = fetchAndNotifyChanges { let observer = FetchedRecordsObserver(region: self.region, fetchAndNotifyChanges: fetchAndNotifyChanges) @@ -160,10 +162,12 @@ public final class FetchedRecordsController { /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). - public func setRequest(_ request: Request) throws where Request: TypedRequest, Request.RowDecoder == Record { - self.request = request + public func setRequest(_ request: Request) throws where Request: FetchRequest, Request.RowDecoder == Record { + self.request = ItemRequest(request) (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in - try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory) + let region = try request.databaseRegion(db) + let itemsAreIdentical = try itemsAreIdenticalFactory(db) + return (region, itemsAreIdentical) } // No observer: don't look for changes @@ -178,7 +182,7 @@ public final class FetchedRecordsController { // Replace observer so that it tracks a new set of columns, // and notify eventual changes let initialItems = fetchedItems - databaseWriter.write { db in + databaseWriter.writeWithoutTransaction { db in let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges) self.observer = observer observer.items = initialItems @@ -193,7 +197,7 @@ public final class FetchedRecordsController { /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). public func setRequest(sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - try setRequest(SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self)) + try setRequest(SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Registers changes notification callbacks. @@ -289,7 +293,7 @@ public final class FetchedRecordsController { #endif let initialItems = fetchedItems - databaseWriter.write { db in + databaseWriter.writeWithoutTransaction { db in let fetchAndNotifyChanges = makeFetchAndNotifyChangesFunction( controller: self, fetchAlongside: fetchAlongside, @@ -376,7 +380,8 @@ public final class FetchedRecordsController { private let itemsAreIdenticalFactory: ItemComparatorFactory /// The request - fileprivate var request: Request + fileprivate typealias ItemRequest = AnyFetchRequest> + fileprivate var request: ItemRequest /// The observed database region private var region : DatabaseRegion @@ -386,20 +391,9 @@ public final class FetchedRecordsController { /// The eventual error handler fileprivate var errorHandler: ((FetchedRecordsController, Error) -> ())? - - private static func fetchRegionAndComparator( - _ db: Database, - request: Request, - itemsAreIdenticalFactory: ItemComparatorFactory) throws - -> (DatabaseRegion, ItemComparator) - { - let region = try request.fetchedRegion(db) - let itemsAreIdentical = try itemsAreIdenticalFactory(db) - return (region, itemsAreIdentical) - } } -extension FetchedRecordsController where Record: TableMapping { +extension FetchedRecordsController where Record: TableRecord { // MARK: - Initialization @@ -408,17 +402,17 @@ extension FetchedRecordsController where Record: TableMapping { /// /// 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 }) /// @@ -441,7 +435,7 @@ extension FetchedRecordsController where Record: TableMapping { { try self.init( databaseWriter, - request: SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self), + request: SQLRequest(sql, arguments: arguments, adapter: adapter), queue: queue) } @@ -457,7 +451,7 @@ extension FetchedRecordsController where Record: TableMapping { /// 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, @@ -475,7 +469,7 @@ extension FetchedRecordsController where Record: TableMapping { _ databaseWriter: DatabaseWriter, request: Request, queue: DispatchQueue = .main) throws - where Request: TypedRequest, Request.RowDecoder == Record + where Request: FetchRequest, Request.RowDecoder == Record { // Builds a function that returns true if and only if two items // have the same primary key and primary keys contain at least one @@ -516,7 +510,7 @@ extension FetchedRecordsController where Record: TableMapping { /// FetchedRecordsController adopts TransactionObserverType so that it can /// monitor changes to its fetched records. -private final class FetchedRecordsObserver : TransactionObserver { +private final class FetchedRecordsObserver : TransactionObserver { var isValid: Bool var needsComputeChanges: Bool var items: [Item]! // ought to be not nil when observer has started tracking transactions @@ -620,7 +614,7 @@ private func makeFetchFunction( do { try databaseWriter.readFromCurrentState { db in result = Result { try ( - fetchedItems: Item.fetchAll(db, request), + fetchedItems: request.fetchAll(db), fetchedAlongside: fetchAlongside(db)) } semaphore.signal() } @@ -867,8 +861,8 @@ private func identicalItemArrays(_ lhs: [Item], _ rhs: [Item = (Item, Item) -> Bool -private typealias ItemComparatorFactory = (Database) throws -> ItemComparator +private typealias ItemComparator = (Item, Item) -> Bool +private typealias ItemComparatorFactory = (Database) throws -> ItemComparator extension FetchedRecordsController { @@ -906,7 +900,7 @@ extension FetchedRecordsController { } } -extension FetchedRecordsController where Record: MutablePersistable { +extension FetchedRecordsController where Record: MutablePersistableRecord { /// Returns the indexPath of a given record. /// @@ -921,7 +915,7 @@ extension FetchedRecordsController where Record: MutablePersistable { } } -private enum ItemChange { +private enum ItemChange { case insertion(item: Item, indexPath: IndexPath) case deletion(item: Item, indexPath: IndexPath) case move(item: Item, indexPath: IndexPath, newIndexPath: IndexPath, changes: [String: DatabaseValue]) @@ -1016,7 +1010,7 @@ extension FetchedRecordChange: CustomStringConvertible { } /// A section given by a FetchedRecordsController. -public struct FetchedRecordsSectionInfo { +public struct FetchedRecordsSectionInfo { fileprivate let controller: FetchedRecordsController /// The number of records (rows) in the section. @@ -1041,7 +1035,7 @@ public struct FetchedRecordsSectionInfo { // MARK: - Item -private final class Item : RowConvertible, Equatable { +private final class Item : FetchableRecord, Equatable { let row: Row // Records are lazily loaded @@ -1055,4 +1049,3 @@ private final class Item : RowConvertible, Equatable { return lhs.row == rhs.row } } - diff --git a/GRDB/Record/Persistable+Encodable.swift b/GRDB/Record/PersistableRecord+Encodable.swift similarity index 95% rename from GRDB/Record/Persistable+Encodable.swift rename to GRDB/Record/PersistableRecord+Encodable.swift index 4fa8d7779..135e8a149 100644 --- a/GRDB/Record/Persistable+Encodable.swift +++ b/GRDB/Record/PersistableRecord+Encodable.swift @@ -1,4 +1,4 @@ -private struct PersistableKeyedEncodingContainer : KeyedEncodingContainerProtocol { +private struct PersistableRecordKeyedEncodingContainer : KeyedEncodingContainerProtocol { let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void init(encode: @escaping (_ value: DatabaseValueConvertible?, _ key: String) -> Void) { @@ -40,7 +40,7 @@ private struct PersistableKeyedEncodingContainer : KeyedEncoding // This allows us to encode Date as String, for example. encode((value as! DatabaseValueConvertible), key.stringValue) } else { - try value.encode(to: PersistableEncoder(codingPath: [key], encode: encode)) + try value.encode(to: PersistableRecordEncoder(codingPath: [key], encode: encode)) } } @@ -140,12 +140,12 @@ private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer { // This allows us to encode Date as String, for example. encode(dbValueConvertible.databaseValue, key.stringValue) } else { - try value.encode(to: PersistableEncoder(codingPath: [key], encode: encode)) + try value.encode(to: PersistableRecordEncoder(codingPath: [key], encode: encode)) } } } -private struct PersistableEncoder : Encoder { +private struct PersistableRecordEncoder : Encoder { /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] @@ -171,7 +171,7 @@ private struct PersistableEncoder : Encoder { guard codingPath.isEmpty else { fatalError("unkeyed encoding is not supported") } - return KeyedEncodingContainer(PersistableKeyedEncodingContainer(encode: encode)) + return KeyedEncodingContainer(PersistableRecordKeyedEncodingContainer(encode: encode)) } /// Returns an encoding container appropriate for holding multiple unkeyed values. @@ -194,7 +194,7 @@ private struct PersistableEncoder : Encoder { } } -extension MutablePersistable where Self: Encodable { +extension MutablePersistableRecord where Self: Encodable { public func encode(to container: inout PersistenceContainer) { // The inout container parameter won't enter an escaping closure since // SE-0035: https://github.com/apple/swift-evolution/blob/master/proposals/0035-limit-inout-capture.md @@ -202,7 +202,7 @@ extension MutablePersistable where Self: Encodable { // So let's use it in a non-escaping closure: func encode(_ encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void) { withoutActuallyEscaping(encode) { escapableEncode in - let encoder = PersistableEncoder(codingPath: [], encode: escapableEncode) + let encoder = PersistableRecordEncoder(codingPath: [], encode: escapableEncode) try! self.encode(to: encoder) } } diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/PersistableRecord.swift similarity index 89% rename from GRDB/Record/Persistable.swift rename to GRDB/Record/PersistableRecord.swift index f511f3346..eea99b42d 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -12,12 +12,12 @@ extension Database.ConflictResolution { // MARK: - PersistenceError -/// An error thrown by a type that adopts Persistable. +/// An error thrown by a type that adopts PersistableRecord. public enum PersistenceError: Error, CustomStringConvertible { - /// Thrown by MutablePersistable.update() when no matching row could be + /// Thrown by MutablePersistableRecord.update() when no matching row could be /// found in the database. - case recordNotFound(MutablePersistable) + case recordNotFound(MutablePersistableRecord) } // CustomStringConvertible @@ -25,8 +25,8 @@ extension PersistenceError { /// :nodoc: public var description: String { switch self { - case .recordNotFound(let persistable): - return "Not found: \(persistable)" + case .recordNotFound(let record): + return "Not found: \(record)" } } } @@ -34,9 +34,9 @@ extension PersistenceError { // MARK: - PersistenceContainer /// Use persistence containers in the `encode(to:)` method of your -/// persistable records: +/// encodable records: /// -/// struct Player : MutablePersistable { +/// struct Player : MutablePersistableRecord { /// var id: Int64? /// var name: String? /// @@ -64,7 +64,7 @@ public struct PersistenceContainer { /// It is undefined behavior to set different values for the same column. /// Column names are case insensitive, so defining both "name" and "NAME" /// is considered undefined behavior. - public subscript(_ column: Column) -> DatabaseValueConvertible? { + public subscript(_ column: ColumnExpression) -> DatabaseValueConvertible? { get { return self[column.name] } set { self[column.name] = newValue } } @@ -81,7 +81,7 @@ public struct PersistenceContainer { /// // Meh /// var container = PersistenceContainer() /// record.encode(to: container) - init(_ record: MutablePersistable) { + init(_ record: MutablePersistableRecord) { storage = [:] record.encode(to: &self) } @@ -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 } @@ -137,7 +146,7 @@ public struct PersistenceContainer { } extension Row { - convenience init(_ record: MutablePersistable) { + convenience init(_ record: MutablePersistableRecord) { self.init(PersistenceContainer(record)) } @@ -146,12 +155,12 @@ extension Row { } } -// MARK: - MutablePersistable +// MARK: - MutablePersistableRecord -/// The MutablePersistable protocol uses this type in order to handle SQLite +/// The MutablePersistableRecord protocol uses this type in order to handle SQLite /// conflicts when records are inserted or updated. /// -/// See `MutablePersistable.persistenceConflictPolicy`. +/// See `MutablePersistableRecord.persistenceConflictPolicy`. /// /// See https://www.sqlite.org/lang_conflict.html public struct PersistenceConflictPolicy { @@ -168,8 +177,8 @@ public struct PersistenceConflictPolicy { } } -/// Types that adopt MutablePersistable can be inserted, updated, and deleted. -public protocol MutablePersistable : TableMapping { +/// Types that adopt MutablePersistableRecord can be inserted, updated, and deleted. +public protocol MutablePersistableRecord : TableRecord { /// The policy that handles SQLite conflicts when records are inserted /// or updated. /// @@ -191,7 +200,7 @@ public protocol MutablePersistable : TableMapping { /// /// Primary key columns, if any, must be included. /// - /// struct Player : MutablePersistable { + /// struct Player : MutablePersistableRecord { /// var id: Int64? /// var name: String? /// @@ -214,7 +223,7 @@ public protocol MutablePersistable : TableMapping { /// /// This method is optional: the default implementation does nothing. /// - /// struct Player : MutablePersistable { + /// struct Player : MutablePersistableRecord { /// var id: Int64? /// var name: String? /// @@ -313,14 +322,14 @@ public protocol MutablePersistable : TableMapping { func exists(_ db: Database) throws -> Bool } -extension MutablePersistable { +extension MutablePersistableRecord { /// A dictionary whose keys are the columns encoded in the `encode(to:)` method. public var databaseDictionary: [String: DatabaseValue] { return PersistenceContainer(self).storage.mapValues { $0?.databaseValue ?? .null } } } -extension MutablePersistable { +extension MutablePersistableRecord { /// Describes the conflict policy for insertions and updates. /// /// The default value specifies ABORT policy for both insertions and @@ -362,7 +371,7 @@ extension MutablePersistable { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. - public func update(_ db: Database, columns: Sequence) throws where Sequence.Element == Column { + public func update(_ db: Database, columns: Sequence) throws where Sequence.Element: ColumnExpression { try update(db, columns: Set(columns.map { $0.name })) } @@ -403,7 +412,7 @@ extension MutablePersistable { /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database and record could not be updated. @discardableResult - public func updateChanges(_ db: Database, from record: MutablePersistable) throws -> Bool { + public func updateChanges(_ db: Database, from record: MutablePersistableRecord) throws -> Bool { let changedColumns = Set(databaseChanges(from: record).keys) if changedColumns.isEmpty { return false @@ -437,11 +446,11 @@ extension MutablePersistable { return try performExists(db) } - // MARK: - Changes Tracking + // MARK: - Record Comparison /// Returns a boolean indicating whether this record and the other record /// have the same database representation. - public func databaseEqual(_ record: Self) -> Bool { + public func databaseEquals(_ record: Self) -> Bool { return databaseChangesIterator(from: record).next() == nil } @@ -453,11 +462,11 @@ extension MutablePersistable { /// but also in terms of columns. When the two records don't define the /// same set of columns in their `encode(to:)` method, only the columns /// defined by the receiver record are considered. - public func databaseChanges(from record: MutablePersistable) -> [String: DatabaseValue] { + public func databaseChanges(from record: MutablePersistableRecord) -> [String: DatabaseValue] { return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: record)) } - fileprivate func databaseChangesIterator(from record: MutablePersistable) -> AnyIterator<(String, DatabaseValue)> { + fileprivate func databaseChangesIterator(from record: MutablePersistableRecord) -> AnyIterator<(String, DatabaseValue)> { let oldContainer = PersistenceContainer(record) var newValueIterator = PersistenceContainer(self).makeIterator() return AnyIterator { @@ -490,10 +499,10 @@ extension MutablePersistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistable. + /// that adopt MutablePersistableRecord. /// /// performInsert() provides the default implementation for insert(). Types - /// that adopt MutablePersistable can invoke performInsert() in their + /// that adopt MutablePersistableRecord can invoke performInsert() in their /// implementation of insert(). They should not provide their own /// implementation of performInsert(). public mutating func performInsert(_ db: Database) throws { @@ -507,10 +516,10 @@ extension MutablePersistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistable. + /// that adopt MutablePersistableRecord. /// /// performUpdate() provides the default implementation for update(). Types - /// that adopt MutablePersistable can invoke performUpdate() in their + /// that adopt MutablePersistableRecord can invoke performUpdate() in their /// implementation of update(). They should not provide their own /// implementation of performUpdate(). /// @@ -520,7 +529,7 @@ extension MutablePersistable { /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. public func performUpdate(_ db: Database, columns: Set) throws { - guard let statement = try DAO(db, self).updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { + guard let statement = try DAO(db, self).updateStatement(db, columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { // Nil primary key throw PersistenceError.recordNotFound(self) } @@ -531,10 +540,10 @@ extension MutablePersistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistable. + /// that adopt MutablePersistableRecord. /// /// performSave() provides the default implementation for save(). Types - /// that adopt MutablePersistable can invoke performSave() in their + /// that adopt MutablePersistableRecord can invoke performSave() in their /// implementation of save(). They should not provide their own /// implementation of performSave(). /// @@ -560,10 +569,10 @@ extension MutablePersistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistable. + /// that adopt MutablePersistableRecord. /// /// performDelete() provides the default implementation for deelte(). Types - /// that adopt MutablePersistable can invoke performDelete() in + /// that adopt MutablePersistableRecord can invoke performDelete() in /// their implementation of delete(). They should not provide their own /// implementation of performDelete(). public func performDelete(_ db: Database) throws -> Bool { @@ -576,10 +585,10 @@ extension MutablePersistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistable. + /// that adopt MutablePersistableRecord. /// /// performExists() provides the default implementation for exists(). Types - /// that adopt MutablePersistable can invoke performExists() in + /// that adopt MutablePersistableRecord can invoke performExists() in /// their implementation of exists(). They should not provide their own /// implementation of performExists(). public func performExists(_ db: Database) throws -> Bool { @@ -592,7 +601,7 @@ extension MutablePersistable { } -extension MutablePersistable { +extension MutablePersistableRecord { // MARK: - Deleting All @@ -607,23 +616,23 @@ extension MutablePersistable { } } -extension MutablePersistable { +extension MutablePersistableRecord { // MARK: - Deleting by Single-Column Primary Key /// 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 MutablePersistable { /// 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: @@ -669,7 +678,7 @@ extension MutablePersistable { } } -extension MutablePersistable { +extension MutablePersistableRecord { // MARK: - Deleting by Key @@ -706,15 +715,15 @@ extension MutablePersistable { } } -// MARK: - Persistable +// MARK: - PersistableRecord -/// Types that adopt Persistable can be inserted, updated, and deleted. +/// Types that adopt PersistableRecord can be inserted, updated, and deleted. /// /// This protocol is intented for types that don't have an INTEGER PRIMARY KEY. /// -/// Unlike MutablePersistable, the insert() and save() methods are not +/// Unlike MutablePersistableRecord, the insert() and save() methods are not /// mutating methods. -public protocol Persistable : MutablePersistable { +public protocol PersistableRecord : MutablePersistableRecord { /// Notifies the record that it was succesfully inserted. /// @@ -725,7 +734,7 @@ public protocol Persistable : MutablePersistable { /// This method is optional: the default implementation does nothing. /// /// If you need a mutating variant of this method, adopt the - /// MutablePersistable protocol instead. + /// MutablePersistableRecord protocol instead. /// /// - parameters: /// - rowID: The inserted rowID. @@ -772,7 +781,7 @@ public protocol Persistable : MutablePersistable { func save(_ db: Database) throws } -extension Persistable { +extension PersistableRecord { /// Notifies the record that it was succesfully inserted. /// @@ -801,10 +810,10 @@ extension Persistable { // MARK: - Immutable CRUD Internals /// Don't invoke this method directly: it is an internal method for types - /// that adopt Persistable. + /// that adopt PersistableRecord. /// /// performInsert() provides the default implementation for insert(). Types - /// that adopt Persistable can invoke performInsert() in their + /// that adopt PersistableRecord can invoke performInsert() in their /// implementation of insert(). They should not provide their own /// implementation of performInsert(). public func performInsert(_ db: Database) throws { @@ -818,10 +827,10 @@ extension Persistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt Persistable. + /// that adopt PersistableRecord. /// /// performSave() provides the default implementation for save(). Types - /// that adopt Persistable can invoke performSave() in their + /// that adopt PersistableRecord can invoke performSave() in their /// implementation of save(). They should not provide their own /// implementation of performSave(). /// @@ -849,14 +858,14 @@ extension Persistable { // MARK: - DAO -/// DAO takes care of Persistable CRUD +/// DAO takes care of PersistableRecord CRUD final class DAO { /// The database let db: Database /// The record - let record: MutablePersistable + let record: MutablePersistableRecord /// DAO keeps a copy the record's persistenceContainer, so that this /// dictionary is built once whatever the database operation. It is @@ -869,7 +878,7 @@ final class DAO { /// The table primary key let primaryKey: PrimaryKeyInfo - init(_ db: Database, _ record: MutablePersistable) throws { + init(_ db: Database, _ record: MutablePersistableRecord) throws { let databaseTableName = type(of: record).databaseTableName let primaryKey = try db.primaryKey(databaseTableName) let persistenceContainer = PersistenceContainer(record) @@ -894,7 +903,7 @@ final class DAO { } /// Returns nil if and only if primary key is nil - func updateStatement(columns: Set, onConflict: Database.ConflictResolution) throws -> UpdateStatement? { + func updateStatement(_ db: Database, columns: Set, onConflict: Database.ConflictResolution) throws -> UpdateStatement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { @@ -902,17 +911,17 @@ final class DAO { } guard primaryKeyValues.contains(where: { !$0.isNull }) else { return nil } - let lowercasePersistentColumns = Set(persistenceContainer.columns.map { $0.lowercased() }) - let lowercasePrimaryKeyColumns = Set(primaryKeyColumns.map { $0.lowercased() }) - var updatedColumns: [String] = [] - for column in columns { - let lowercaseColumn = column.lowercased() - // Don't update columns that are not present in the persistenceContainer - guard lowercasePersistentColumns.contains(lowercaseColumn) else { continue } - // Don't update primary key columns - guard !lowercasePrimaryKeyColumns.contains(lowercaseColumn) else { continue } - updatedColumns.append(column) - } + // Don't update columns not present in columns + // Don't update columns not present in the persistenceContainer + // Don't update primary key columns + let lowercaseUpdatedColumns = Set(columns.map { $0.lowercased() }) + .intersection(persistenceContainer.columns.map { $0.lowercased() }) + .subtracting(primaryKeyColumns.map { $0.lowercased() }) + + var updatedColumns: [String] = try db + .columns(in: databaseTableName) + .map { $0.name } + .filter { lowercaseUpdatedColumns.contains($0.lowercased()) } if updatedColumns.isEmpty { // IMPLEMENTATION NOTE @@ -925,6 +934,7 @@ final class DAO { // including tables made of a single primary key column. updatedColumns = primaryKeyColumns } + let updatedValues = updatedColumns.map { persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null } @@ -982,16 +992,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 +1025,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 b2fddac34..30b0f7894 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -2,7 +2,7 @@ /// Record is a class that wraps a table row, or the result of any query. It is /// designed to be subclassed. -open class Record : RowConvertible, TableMapping, Persistable { +open class Record : FetchableRecord, TableRecord, PersistableRecord { // MARK: - Initializers @@ -32,7 +32,7 @@ open class Record : RowConvertible, TableMapping, Persistable { /// /// class Player : Record { /// override class var databaseTableName: String { - /// return "players" + /// return "player" /// } /// } /// @@ -64,7 +64,7 @@ open class Record : RowConvertible, TableMapping, Persistable { /// /// 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 : RowConvertible, TableMapping, Persistable { /// } /// } /// - /// // 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 : RowConvertible, TableMapping, Persistable { /// } /// } /// - /// // SELECT *, rowid FROM players + /// // SELECT *, rowid FROM player /// try ExtendedPlayer.fetchAll(db) open class var databaseSelection: [SQLSelectable] { return [AllColumns()] @@ -150,20 +150,13 @@ open class Record : RowConvertible, TableMapping, Persistable { /// /// - returns: A copy of self. open func copy() -> Self { - let row: Row - #if swift(>=3.1) - row = Row(self) - #else - // workaround weird Swift 3.0 glitch - row = Row(self as! MutablePersistable) - #endif - let copy = type(of: self).init(row: row) + let copy = type(of: self).init(row: Row(self)) copy.referenceRow = referenceRow return copy } - // MARK: - Changes Tracking + // MARK: - Compare with Previous Versions /// A boolean that indicates whether the record has changes that have not /// been saved. @@ -186,13 +179,6 @@ open class Record : RowConvertible, TableMapping, Persistable { set { referenceRow = newValue ? nil : Row(self) } } - /// Deprecated alias for `hasDatabaseChanges`. - @available(*, deprecated, renamed: "hasDatabaseChanges") - public var hasPersistentChangedValues: Bool { - get { return hasDatabaseChanges } - set { hasDatabaseChanges = newValue } - } - /// A dictionary of changes that have not been saved. /// /// Its keys are column names, and values the old values that have been @@ -206,12 +192,6 @@ open class Record : RowConvertible, TableMapping, Persistable { return Dictionary(uniqueKeysWithValues: databaseChangesIterator()) } - /// Deprecated alias for `databaseChanges`. - @available(*, deprecated, renamed: "databaseChanges") - public var persistentChangedValues: [String: DatabaseValue?] { - return databaseChanges - } - // A change iterator that is used by both hasDatabaseChanges and // persistentChangedValues properties. private func databaseChangesIterator() -> AnyIterator<(String, DatabaseValue?)> { @@ -294,7 +274,7 @@ open class Record : RowConvertible, TableMapping, Persistable { // // But this would trigger two calls to `encode(to:)`. let dao = try DAO(db, self) - guard let statement = try dao.updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { + guard let statement = try dao.updateStatement(db, columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { // Nil primary key throw PersistenceError.recordNotFound(self) } @@ -345,6 +325,9 @@ open class Record : RowConvertible, TableMapping, Persistable { /// This method is guaranteed to have inserted or updated a row in the /// database if it returns without error. /// + /// You can't override this method. Instead, override `insert(_:)` + /// or `update(_:columns:)`. + /// /// - parameter db: A database connection. /// - throws: A DatabaseError whenever an SQLite error occurs, or errors /// thrown by update(). diff --git a/GRDB/Record/RecordBox.swift b/GRDB/Record/RecordBox.swift deleted file mode 100644 index cccfa4794..000000000 --- a/GRDB/Record/RecordBox.swift +++ /dev/null @@ -1,101 +0,0 @@ -/// RecordBox is a subclass of Record that aims at giving any record type the -/// changes tracking provided by the Record class. -/// -/// // A Regular record struct -/// struct Player: RowConvertible, MutablePersistable, Codable { -/// static let databaseTableName = "players" -/// var id: Int64? -/// var name: String -/// var score: Int -/// mutating func didInsert(with rowID: Int64, for column: String?) { -/// id = rowID -/// } -/// } -/// -/// try dbQueue.inDatabase { db in -/// // Fetch a player record -/// let playerRecord = try RecordBox.fetchOne(db, key: 1)! -/// -/// // Profit from changes tracking -/// playerRecord.value.score = 300 -/// playerRecord.hasPersistentChangedValues // true -/// playerRecord.persistentChangedValues["score"] // 100 (the old value) -/// } -@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)") -public final class RecordBox: Record { - /// The boxed record - public var value: T - - /// Creates a RecordBox that wraps the given record - public init(value: T) { - self.value = value - super.init() - } - - // MARK: - RowConvertible - - /// Initializes a record from `row`. - public required init(row: Row) { - self.value = T(row: row) - super.init(row: row) - } - - // MARK: - TableMapping - - /// :nodoc: - override public class var databaseTableName: String { - return T.databaseTableName - } - - /// :nodoc: - override public class var databaseSelection: [SQLSelectable] { - return T.databaseSelection - } - - // MARK: - MutablePersistable - - /// :nodoc: - override public class var persistenceConflictPolicy: PersistenceConflictPolicy { - return T.persistenceConflictPolicy - } - - /// :nodoc: - override public func encode(to container: inout PersistenceContainer) { - value.encode(to: &container) - } - - /// :nodoc: - override public func didInsert(with rowID: Int64, for column: String?) { - value.didInsert(with: rowID, for: column) - } - - /// :nodoc: - override public func insert(_ db: Database) throws { - try value.insert(db) - hasPersistentChangedValues = false - } - - /// :nodoc: - override public func update(_ db: Database, columns: Set) throws { - try value.update(db, columns: columns) - hasPersistentChangedValues = false - } - - /// :nodoc: - @discardableResult - override public func delete(_ db: Database) throws -> Bool { - defer { - // Future calls to update() will throw NotFound. Make the user - // a favor and make sure this error is thrown even if she checks the - // hasPersistentChangedValues flag: - hasPersistentChangedValues = true - } - return try value.delete(db) - } - - /// :nodoc: - public func exists(_ db: Database) throws -> Bool { - return try value.exists(db) - } -} - diff --git a/GRDB/Record/TableMapping.swift b/GRDB/Record/TableMapping.swift deleted file mode 100644 index 250ba39aa..000000000 --- a/GRDB/Record/TableMapping.swift +++ /dev/null @@ -1,122 +0,0 @@ -/// Types that adopt TableMapping declare a particular relationship with -/// a database table. -/// -/// Types that adopt both TableMapping and RowConvertible are granted with -/// built-in methods that allow to fetch instances identified by key: -/// -/// try Player.fetchOne(db, key: 123) // Player? -/// try Citizenship.fetchOne(db, key: ["citizenId": 12, "countryId": 45]) // Citizenship? -/// -/// TableMapping is adopted by Record. -public protocol TableMapping { - /// The name of the database table used to build requests. - /// - /// struct Player : TableMapping { - /// static var databaseTableName = "players" - /// } - /// - /// // SELECT * FROM players - /// try Player.fetchAll(db) - static var databaseTableName: String { get } - - /// The default request selection. - /// - /// Unless said otherwise, requests select all columns: - /// - /// // SELECT * FROM players - /// try Player.fetchAll(db) - /// - /// You can provide a custom implementation and provide an explicit list - /// of columns: - /// - /// struct RestrictedPlayer : TableMapping { - /// static var databaseTableName = "players" - /// static var databaseSelection = [Column("id"), Column("name")] - /// } - /// - /// // SELECT id, name FROM players - /// try RestrictedPlayer.fetchAll(db) - /// - /// You can also add extra columns such as the `rowid` column: - /// - /// struct ExtendedPlayer : TableMapping { - /// static var databaseTableName = "players" - /// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] - /// } - /// - /// // SELECT *, rowid FROM players - /// try ExtendedPlayer.fetchAll(db) - static var databaseSelection: [SQLSelectable] { get } -} - -extension TableMapping { - /// Default value: `[AllColumns()]`. - public static var databaseSelection: [SQLSelectable] { - return [AllColumns()] - } -} - -extension TableMapping { - - // MARK: - Counting All - - /// The number of records. - /// - /// - parameter db: A database connection. - public static func fetchCount(_ db: Database) throws -> Int { - return try all().fetchCount(db) - } -} - -extension TableMapping { - - // MARK: - SQL Generation - - /// The selection as an SQL String. - /// - /// For example: - /// - /// struct Player: TableMapping { - /// static let databaseTableName = "players" - /// } - /// - /// // SELECT "players".* FROM players - /// let sql = "SELECT \(Player.selectionSQL()) FROM players" - /// - /// // SELECT "p".* FROM players AS p - /// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM players AS p" - public static func selectionSQL(alias: String? = nil) -> String { - let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: alias ?? databaseTableName) - let selection = databaseSelection.map { $0.qualified(by: qualifier) } - var arguments: StatementArguments? = nil - return selection - .map { $0.resultColumnSQL(&arguments) } - .joined(separator: ", ") - } - - /// Returns the number of selected columns. - /// - /// For example: - /// - /// struct Player: TableMapping { - /// static let databaseTableName = "players" - /// } - /// - /// try dbQueue.inDatabase { db in - /// try db.create(table: "players") { t in - /// t.column("id", .integer).primaryKey() - /// t.column("name", .text) - /// t.column("score", .integer) - /// } - /// - /// // 3 - /// try Player.numberOfSelectedColumns(db) - /// } - public static func numberOfSelectedColumns(_ db: Database) throws -> Int { - let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: nil) - return try databaseSelection - .map { try $0.qualified(by: qualifier).columnCount(db) } - .reduce(0, +) - } -} - diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift new file mode 100644 index 000000000..1c36ce8fe --- /dev/null +++ b/GRDB/Record/TableRecord.swift @@ -0,0 +1,155 @@ +/// Types that adopt TableRecord declare a particular relationship with +/// a database table. +/// +/// Types that adopt both TableRecord and FetchableRecord are granted with +/// built-in methods that allow to fetch instances identified by key: +/// +/// try Player.fetchOne(db, key: 123) // Player? +/// try Citizenship.fetchOne(db, key: ["citizenId": 12, "countryId": 45]) // Citizenship? +/// +/// TableRecord is adopted by Record. +public protocol TableRecord { + /// The name of the database table used to build requests. + /// + /// struct Player : TableRecord { + /// static var databaseTableName = "player" + /// } + /// + /// // SELECT * FROM player + /// try Player.fetchAll(db) + static var databaseTableName: String { get } + + /// The default request selection. + /// + /// Unless said otherwise, requests select all columns: + /// + /// // 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 = "player" + /// static var databaseSelection = [Column("id"), Column("name")] + /// } + /// + /// // 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 = "player" + /// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + /// } + /// + /// // SELECT *, rowid FROM player + /// try ExtendedPlayer.fetchAll(db) + static var databaseSelection: [SQLSelectable] { get } +} + +extension TableRecord { + + /// The default name of the database table used to build requests. + /// + /// - Player -> "player" + /// - Place -> "place" + /// - PostalAddress -> "postalAddress" + /// - HTTPRequest -> "httpRequest" + /// - TOEFL -> "toefl" + internal static var defaultDatabaseTableName: String { + let typeName = "\(Self.self)".replacingOccurrences(of: "(.)\\b.*$", with: "$1", options: [.regularExpression]) + let initial = typeName.replacingOccurrences(of: "^([A-Z]+).*$", with: "$1", options: [.regularExpression]) + switch initial.count { + case typeName.count: + return initial.lowercased() + case 0: + return typeName + case 1: + return initial.lowercased() + typeName.dropFirst() + default: + return initial.dropLast().lowercased() + typeName.dropFirst(initial.count - 1) + } + } + + /// The default name of the database table used to build requests. + /// + /// - Player -> "player" + /// - Place -> "place" + /// - PostalAddress -> "postalAddress" + /// - HTTPRequest -> "httpRequest" + /// - TOEFL -> "toefl" + public static var databaseTableName: String { + return defaultDatabaseTableName + } + + /// Default value: `[AllColumns()]`. + public static var databaseSelection: [SQLSelectable] { + return [AllColumns()] + } +} + +extension TableRecord { + + // MARK: - Counting All + + /// The number of records. + /// + /// - parameter db: A database connection. + public static func fetchCount(_ db: Database) throws -> Int { + return try all().fetchCount(db) + } +} + +extension TableRecord { + + // MARK: - SQL Generation + + /// The selection as an SQL String. + /// + /// For example: + /// + /// struct Player: TableRecord { + /// static let databaseTableName = "player" + /// } + /// + /// // SELECT "player".* FROM player + /// let sql = "SELECT \(Player.selectionSQL()) FROM player" + /// + /// // 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 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(&context) } + .joined(separator: ", ") + } + + /// Returns the number of selected columns. + /// + /// For example: + /// + /// struct Player: TableRecord { + /// static let databaseTableName = "player" + /// } + /// + /// try dbQueue.write { db in + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("name", .text) + /// t.column("score", .integer) + /// } + /// + /// // 3 + /// try Player.numberOfSelectedColumns(db) + /// } + public static func numberOfSelectedColumns(_ db: Database) throws -> Int { + let alias = TableAlias(tableName: databaseTableName) + return try databaseSelection + .map { try $0.qualifiedSelectable(with: alias).columnCount(db) } + .reduce(0, +) + } +} diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 26cbb66d7..8766e852c 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -27,7 +27,6 @@ public func databaseQuestionMarks(count: Int) -> String { /// :nodoc: public protocol _OptionalProtocol { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: associatedtype _Wrapped } @@ -39,7 +38,6 @@ public protocol _OptionalProtocol { /// :nodoc: extension Optional : _OptionalProtocol { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public typealias _Wrapped = Wrapped } diff --git a/GRDBCipher.podspec b/GRDBCipher.podspec index d63ad4227..4262ba38b 100644 --- a/GRDBCipher.podspec +++ b/GRDBCipher.podspec @@ -3,7 +3,7 @@ Pod::Spec.new do |s| s.version = '2.10.0' s.license = { :type => 'MIT', :file => 'LICENSE' } - s.summary = 'A Swift application toolkit for SQLite databases.' + s.summary = 'A toolkit for SQLite databases, with a focus on application development.' s.homepage = 'https://github.com/groue/GRDB.swift' s.author = { 'Gwendal Roué' => 'gr@pierlis.com' } s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" } diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 0593c452d..ca3c50743 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -22,10 +22,10 @@ 560FC52A1CB003810014AA8E /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; }; 560FC52B1CB003810014AA8E /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238751B9C75030082EB20 /* DatabaseValue.swift */; }; 560FC52E1CB003810014AA8E /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; - 560FC5311CB003810014AA8E /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; + 560FC5311CB003810014AA8E /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; 560FC5331CB003810014AA8E /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; - 560FC5341CB003810014AA8E /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 560FC5351CB003810014AA8E /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; }; 560FC5361CB003810014AA8E /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; 560FC5371CB003810014AA8E /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; }; @@ -37,7 +37,7 @@ 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1511C672E4000235C62 /* NSNumber.swift */; }; 560FC53F1CB003810014AA8E /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; }; 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; - 560FC5411CB003810014AA8E /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; + 560FC5411CB003810014AA8E /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; 560FC5421CB003810014AA8E /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; 560FC5611CB00B880014AA8E /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; }; 560FC5621CB00B880014AA8E /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; @@ -59,11 +59,11 @@ 560FC5791CB00B880014AA8E /* RecordPrimaryKeyMultipleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238281B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift */; }; 560FC57C1CB00B880014AA8E /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 560FC57D1CB00B880014AA8E /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; - 560FC57E1CB00B880014AA8E /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - 560FC57F1CB00B880014AA8E /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + 560FC57E1CB00B880014AA8E /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + 560FC57F1CB00B880014AA8E /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 560FC5811CB00B880014AA8E /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; 560FC5821CB00B880014AA8E /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; - 560FC5841CB00B880014AA8E /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + 560FC5841CB00B880014AA8E /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; 560FC5871CB00B880014AA8E /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; }; 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 560FC58B1CB00B880014AA8E /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; @@ -72,14 +72,14 @@ 560FC58F1CB00B880014AA8E /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; 560FC5901CB00B880014AA8E /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; 560FC5911CB00B880014AA8E /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */; }; - 560FC5921CB00B880014AA8E /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + 560FC5921CB00B880014AA8E /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; 560FC5941CB00B880014AA8E /* DatabaseValueConvertibleSubclassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381A1B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift */; }; 560FC5961CB00B880014AA8E /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 560FC5971CB00B880014AA8E /* DatabaseErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */; }; 560FC5991CB00B880014AA8E /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 560FC59B1CB00B880014AA8E /* DatabaseTimestampTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */; }; 560FC59C1CB00B880014AA8E /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; - 560FC59D1CB00B880014AA8E /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + 560FC59D1CB00B880014AA8E /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; 560FC59E1CB00B880014AA8E /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; }; 560FC59F1CB00B880014AA8E /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; }; 560FC5A01CB00B880014AA8E /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; @@ -94,6 +94,8 @@ 561667031D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 561667061D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 561667071D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; + 5616AAF9207CD5A900AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */; }; + 5616AAFA207CD5A900AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */; }; 56176C5F1EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD001DAA8ACA0056AF8C /* FTS5CustomTokenizerTests.swift */; }; 56176C601EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C01DA521450002DA19 /* FTS5PatternTests.swift */; }; 56176C611EACCCC7000F3F2B /* FTS5RecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C11DA521450002DA19 /* FTS5RecordTests.swift */; }; @@ -141,10 +143,6 @@ 562393321DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; 562393351DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; 562393361DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; - 562393461DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; - 562393471DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; - 5623934A1DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; - 5623934B1DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; 5623934F1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; 562393501DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; 562393531DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; @@ -181,8 +179,8 @@ 5634B1091CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; }; 5634B10B1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; }; 5634B10C1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; }; - 5636E9BD1D22574100B9B05F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; - 5636E9C01D22574100B9B05F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; + 5636E9BD1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; + 5636E9C01D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 564448841EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 564448851EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 564448881EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; @@ -197,6 +195,86 @@ 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 */; }; + 5656BF5E20C7248700F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5C20C7248700F98521 /* QueryOrdering.swift */; }; + 5656BF5F20C7248700F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5C20C7248700F98521 /* QueryOrdering.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 */; }; @@ -264,10 +342,10 @@ 566A843120413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; }; 566A843220413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; }; 566A843320413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; }; - 566A84462041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */; }; - 566A84472041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */; }; - 566A84482041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */; }; - 566A84492041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */; }; + 566A84462041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */; }; + 566A84472041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */; }; + 566A84482041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */; }; + 566A84492041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */; }; 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8C71D531BEA002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; }; @@ -310,11 +388,11 @@ 567156371CB16729007DC145 /* RecordPrimaryKeyMultipleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238281B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift */; }; 5671563A1CB16729007DC145 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 5671563B1CB16729007DC145 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; - 5671563C1CB16729007DC145 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - 5671563D1CB16729007DC145 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + 5671563C1CB16729007DC145 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + 5671563D1CB16729007DC145 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 5671563F1CB16729007DC145 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; 567156401CB16729007DC145 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; - 567156411CB16729007DC145 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + 567156411CB16729007DC145 /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; 567156441CB16729007DC145 /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; }; 567156461CB16729007DC145 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 567156481CB16729007DC145 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; @@ -325,14 +403,14 @@ 5671564E1CB16729007DC145 /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; 5671564F1CB16729007DC145 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; 567156501CB16729007DC145 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */; }; - 567156511CB16729007DC145 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + 567156511CB16729007DC145 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; 567156531CB16729007DC145 /* DatabaseValueConvertibleSubclassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381A1B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift */; }; 567156551CB16729007DC145 /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 567156561CB16729007DC145 /* DatabaseErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */; }; 567156571CB16729007DC145 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 567156591CB16729007DC145 /* DatabaseTimestampTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */; }; 5671565A1CB16729007DC145 /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; - 5671565B1CB16729007DC145 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + 5671565B1CB16729007DC145 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; 5671565C1CB16729007DC145 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; }; 5671565D1CB16729007DC145 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; }; 5671565E1CB16729007DC145 /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; @@ -352,18 +430,18 @@ 5672DE6C1CDB751D0022BA81 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */; }; 567404891CEF84C8003ED5CC /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; }; 5674048B1CEF84C8003ED5CC /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; }; - 56741EA91E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; - 56741EAA1E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; - 56741EAD1E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; - 56741EAE1E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; + 56741EA91E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; + 56741EAA1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; + 56741EAD1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; + 56741EAE1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; 5674A6E71F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6EA1F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6EE1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6F11F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; - 5674A6F71F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6FA1F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6FE1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; - 5674A7011F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; + 5674A6F71F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6FA1F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6FE1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; + 5674A7011F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; 5674A7061F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A7091F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A70D1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */; }; @@ -374,14 +452,14 @@ 5674A7181F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A7191F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A71B1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; - 5674A71E1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A7211F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A7221F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A7241F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A7281F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; - 5674A72B1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; - 5674A72C1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; - 5674A72E1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; + 5674A71E1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A7211F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A7221F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A7241F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A7281F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5674A72B1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5674A72C1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5674A72E1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; 567A80541D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567A80581D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; @@ -400,12 +478,6 @@ 567F45AA1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 567F45AD1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 567F45AE1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; - 5680520C2013209300E87861 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680520A2013209300E87861 /* RecordBox.swift */; }; - 5680520D2013209900E87861 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680520A2013209300E87861 /* RecordBox.swift */; }; - 5680521E2013296F00E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680521C2013296800E87861 /* RecordBoxTests.swift */; }; - 5680521F2013296F00E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680521C2013296800E87861 /* RecordBoxTests.swift */; }; - 568052202013297000E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680521C2013296800E87861 /* RecordBoxTests.swift */; }; - 568052212013297000E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680521C2013296800E87861 /* RecordBoxTests.swift */; }; 568068321EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568068331EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568068361EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; @@ -484,8 +556,8 @@ 5698AD251DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; }; 5698AD361DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 5698AD391DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.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 */; }; + 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 */; }; 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 */; }; @@ -527,11 +599,11 @@ 56AFC9FD1CB1A8BB00F48B96 /* NSString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1521C672E4000235C62 /* NSString.swift */; }; 56AFC9FF1CB1A8BB00F48B96 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; }; 56AFCA001CB1A8BB00F48B96 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; - 56AFCA031CB1A8BB00F48B96 /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; + 56AFCA031CB1A8BB00F48B96 /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 56AFCA061CB1A8BB00F48B96 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; }; 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; }; - 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 56AFCA0B1CB1A8BB00F48B96 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; }; 56AFCA0C1CB1A8BB00F48B96 /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; }; @@ -542,7 +614,7 @@ 56AFCA111CB1A8BB00F48B96 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; }; 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1511C672E4000235C62 /* NSNumber.swift */; }; 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; - 56AFCA151CB1A8BB00F48B96 /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; + 56AFCA151CB1A8BB00F48B96 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; 56AFCA181CB1A8BB00F48B96 /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; 56AFCA191CB1A8BB00F48B96 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238751B9C75030082EB20 /* DatabaseValue.swift */; }; @@ -571,12 +643,12 @@ 56AFCA471CB1AA9900F48B96 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; 56AFCA491CB1AA9900F48B96 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 56AFCA4A1CB1AA9900F48B96 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; - 56AFCA4B1CB1AA9900F48B96 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - 56AFCA4C1CB1AA9900F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + 56AFCA4B1CB1AA9900F48B96 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + 56AFCA4C1CB1AA9900F48B96 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 56AFCA4D1CB1AA9900F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 56AFCA4F1CB1AA9900F48B96 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; 56AFCA501CB1AA9900F48B96 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; - 56AFCA521CB1AA9900F48B96 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + 56AFCA521CB1AA9900F48B96 /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; 56AFCA531CB1AA9900F48B96 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; }; 56AFCA551CB1AA9900F48B96 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; 56AFCA561CB1AA9900F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; }; @@ -586,7 +658,7 @@ 56AFCA5B1CB1AA9900F48B96 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; 56AFCA5C1CB1AA9900F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; }; 56AFCA5D1CB1AA9900F48B96 /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; - 56AFCA5E1CB1AA9900F48B96 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + 56AFCA5E1CB1AA9900F48B96 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; 56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */; }; 56AFCA611CB1AA9900F48B96 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; @@ -599,7 +671,7 @@ 56AFCA681CB1AA9900F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 56AFCA6B1CB1AA9900F48B96 /* DatabaseTimestampTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */; }; 56AFCA6C1CB1AA9900F48B96 /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; - 56AFCA6D1CB1AA9900F48B96 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + 56AFCA6D1CB1AA9900F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; 56AFCA6E1CB1AA9900F48B96 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; }; 56AFCA6F1CB1AA9900F48B96 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; }; 56AFCA701CB1AA9900F48B96 /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; @@ -631,12 +703,12 @@ 56AFCAA01CB1ABC800F48B96 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; 56AFCAA21CB1ABC800F48B96 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 56AFCAA31CB1ABC800F48B96 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; - 56AFCAA41CB1ABC800F48B96 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - 56AFCAA51CB1ABC800F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + 56AFCAA41CB1ABC800F48B96 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + 56AFCAA51CB1ABC800F48B96 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 56AFCAA81CB1ABC800F48B96 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; 56AFCAA91CB1ABC800F48B96 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; - 56AFCAAB1CB1ABC800F48B96 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + 56AFCAAB1CB1ABC800F48B96 /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; 56AFCAAC1CB1ABC800F48B96 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; }; 56AFCAAE1CB1ABC800F48B96 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; 56AFCAAF1CB1ABC800F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; }; @@ -646,7 +718,7 @@ 56AFCAB41CB1ABC800F48B96 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; 56AFCAB51CB1ABC800F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; }; 56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; - 56AFCAB71CB1ABC800F48B96 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + 56AFCAB71CB1ABC800F48B96 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; 56AFCAB81CB1ABC800F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 56AFCAB91CB1ABC800F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */; }; 56AFCABA1CB1ABC800F48B96 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; @@ -659,7 +731,7 @@ 56AFCAC11CB1ABC800F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 56AFCAC41CB1ABC800F48B96 /* DatabaseTimestampTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */; }; 56AFCAC51CB1ABC800F48B96 /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; - 56AFCAC61CB1ABC800F48B96 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + 56AFCAC61CB1ABC800F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; 56AFCAC71CB1ABC800F48B96 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; }; 56AFCAC81CB1ABC800F48B96 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; }; 56AFCAC91CB1ABC800F48B96 /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; @@ -670,16 +742,20 @@ 56AFCACF1CB1ABC800F48B96 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; }; 56AFCAD01CB1ABC800F48B96 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; 56AFCAD21CB1ABC800F48B96 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */; }; - 56B021CA1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; - 56B021CB1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; - 56B021CE1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; - 56B021CF1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; + 56B021CA1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021CB1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021CE1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021CF1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E801D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B14E811D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B14E841D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B14E851D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B15D0C1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 56B15D0D1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; + 56B6EF64208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */; }; + 56B6EF65208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */; }; + 56B6EF66208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */; }; + 56B6EF67208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */; }; 56B9649E1DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; 56B964A11DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; 56B964B21DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; }; @@ -714,8 +790,8 @@ 56CC9258201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; }; 56CC9259201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; }; 56CC925A201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; }; - 56CEB4F21EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; - 56CEB4F51EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; + 56CEB4F21EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; + 56CEB4F51EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; 56CEB4FB1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB4FE1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB5021EAA2F4D00BFAF62 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; }; @@ -740,8 +816,8 @@ 56D507601F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507631F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507641F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; - 56D51D011EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; - 56D51D041EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; + 56D51D011EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D51D041EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56DAA2D31DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D41DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D71DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; @@ -750,6 +826,10 @@ 56DAA2DF1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; 56E06F131E859068008AE2A4 /* Fixits-0.102.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */; }; 56E06F161E85906C008AE2A4 /* Fixits-0.102.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */; }; + 56EA63CC209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; }; + 56EA63CD209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; }; + 56EA63CE209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; }; + 56EA63CF209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; }; 56F26C241CEE3F34007969C4 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; 56F3E74A1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; 56F3E74B1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; @@ -757,16 +837,14 @@ 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 /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; - 56FEE7FD1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; - 56FEE8001F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; - 56FEE8011F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; - 56FF45411D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; - 56FF45421D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; - 56FF45451D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; - 56FF45461D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.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 */; }; + 56FEE8011F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; + 56FF45411D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + 56FF45421D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + 56FF45451D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + 56FF45461D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; 56FF45571D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 56FF45581D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 56FF455B1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; @@ -841,7 +919,7 @@ 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; - 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceSelectQueryDefinition.swift; sourceTree = ""; }; + 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceQuery.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; @@ -849,15 +927,15 @@ 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunctionTests.swift; sourceTree = ""; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; - 560D92441C672C4B00F4F92B /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = ""; }; - 560D92461C672C4B00F4F92B /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = ""; }; + 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; + 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 560FC54D1CB003810014AA8E /* GRDBCipher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDBCipher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 560FC5501CB004AD0014AA8E /* sqlcipher.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = sqlcipher.xcodeproj; path = SQLCipher/src/sqlcipher.xcodeproj; sourceTree = ""; }; 560FC5B01CB00B880014AA8E /* GRDBCipherOSXTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipherOSXTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; + 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; - 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IteratorCursorTests.swift; sourceTree = ""; }; 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = ""; }; 562393561DEE013C00A6B01F /* FilterCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FilterCursorTests.swift; sourceTree = ""; }; 5623935F1DEE06D300A6B01F /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = ""; }; @@ -868,25 +946,51 @@ 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = ""; }; 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; - 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExpressionsTests.swift; sourceTree = ""; }; - 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableMapping+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; - 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableTests.swift; sourceTree = ""; }; - 563363AA1C933FF8000BE133 /* PersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableTests.swift; sourceTree = ""; }; + 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordTests.swift; sourceTree = ""; }; + 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecordTests.swift; sourceTree = ""; }; 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueConcurrencyTests.swift; sourceTree = ""; }; 563363BF1C942C04000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = ""; }; 563363C31C942C37000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = ""; }; 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReleaseMemoryTests.swift; sourceTree = ""; }; 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; - 5636E9BB1D22574100B9B05F /* Request.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = ""; }; + 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 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 = ""; }; + 5656BF5C20C7248700F98521 /* QueryOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryOrdering.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 = ""; }; @@ -900,7 +1004,7 @@ 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = ""; }; 5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = ""; }; 5659F49F1EA8D997004A4992 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = ""; }; - 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = ""; }; + 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = ""; }; 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; @@ -913,7 +1017,7 @@ 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; - 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableChangesTests.swift; sourceTree = ""; }; + 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = ""; }; 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = ""; }; 566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = ""; }; @@ -929,22 +1033,20 @@ 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueBackupTests.swift; sourceTree = ""; }; 5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = ""; }; 567404871CEF84C8003ED5CC /* RowAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowAdapter.swift; sourceTree = ""; }; - 56741EA71E66A8B3003E422D /* RequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestTests.swift; sourceTree = ""; }; + 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; - 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RowConvertible+Decodable.swift"; sourceTree = ""; }; - 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Persistable+Encodable.swift"; sourceTree = ""; }; + 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+Decodable.swift"; sourceTree = ""; }; + 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Encodable.swift"; sourceTree = ""; }; 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = ""; }; 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = ""; }; 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; - 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableEncodableTests.swift; sourceTree = ""; }; - 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowConvertibleDecodableTests.swift; sourceTree = ""; }; + 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = ""; }; + 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; - 5680520A2013209300E87861 /* RecordBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordBox.swift; sourceTree = ""; }; - 5680521C2013296800E87861 /* RecordBoxTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordBoxTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = ""; }; @@ -979,7 +1081,7 @@ 5698AD151DAAD16F0056AF8C /* FTS5Tokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5Tokenizer.swift; sourceTree = ""; }; 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 = ""; }; - 569B7FA6201C904C0069DE70 /* Swift4.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; + 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-3.0.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 = ""; }; @@ -1025,9 +1127,10 @@ 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDBCipher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 56AFCA7F1CB1AA9900F48B96 /* GRDBCipheriOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipheriOSTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 56AFCAD71CB1ABC800F48B96 /* GRDBCipheriOSEncryptedTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipheriOSEncryptedTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistablePersistenceConflictPolicyTests.swift; sourceTree = ""; }; + 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 = ""; }; + 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; 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 = ""; }; 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = ""; }; @@ -1049,7 +1152,7 @@ 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; 56CC924B201E059100CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; - 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; + 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecord.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS3+QueryInterfaceRequest.swift"; sourceTree = ""; }; @@ -1061,13 +1164,14 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = ""; }; 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.109.0.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; - 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+TableMapping.swift"; sourceTree = ""; }; + 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.102.0.swift"; sourceTree = ""; }; 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = ""; }; + 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = ""; }; 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = ""; }; 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = ""; }; 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = ""; }; @@ -1076,10 +1180,9 @@ 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 /* TableMappingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableMappingTests.swift; sourceTree = ""; }; - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableDeleteTests.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 = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; @@ -1209,17 +1312,17 @@ name = DatabasePool; sourceTree = ""; }; - 560B3FA41C19DFF800C58EC7 /* Persistable */ = { + 560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = { isa = PBXGroup; children = ( - 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */, - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */, - 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */, - 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */, - 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */, - 563363AA1C933FF8000BE133 /* PersistableTests.swift */, + 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */, + 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, + 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, + 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, + 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, + 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, ); - name = Persistable; + name = PersistableRecord; sourceTree = ""; }; 560FC54F1CB0047D0014AA8E /* GRDBCipher */ = { @@ -1261,12 +1364,12 @@ path = GRDBTests; sourceTree = ""; }; - 56176C9C1EACEA8C000F3F2B /* TableMapping */ = { + 56176C9C1EACEA8C000F3F2B /* TableRecord */ = { isa = PBXGroup; children = ( - 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */, + 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */, ); - name = TableMapping; + name = TableRecord; sourceTree = ""; }; 56176C9E1EACEDF9000F3F2B /* Record */ = { @@ -1319,13 +1422,16 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EBA420961FD300F46237 /* Association */, + 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */, + 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */, + 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, - 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, - 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */, + 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, ); name = QueryInterface; @@ -1334,16 +1440,21 @@ 56300B6D1C53F592005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EB8420961FBF00F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, + 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, - 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */, + 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */, + 5656BF5C20C7248700F98521 /* QueryOrdering.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 +1479,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 = ( @@ -1388,13 +1535,13 @@ path = Support; sourceTree = ""; }; - 5674A7251F30A8EF0095F066 /* RowConvertible */ = { + 5674A7251F30A8EF0095F066 /* FetchableRecord */ = { isa = PBXGroup; children = ( - 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */, - 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */, + 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */, + 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */, ); - name = RowConvertible; + name = FetchableRecord; sourceTree = ""; }; 5698AC291D9E5A480056AF8C /* FTS */ = { @@ -1471,10 +1618,10 @@ 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */, 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */, 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */, + 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */, 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */, 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */, 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */, - 56741EA71E66A8B3003E422D /* RequestTests.swift */, 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */, 56A2381D1B9C74A90082EB20 /* Row */, 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */, @@ -1534,13 +1681,12 @@ 56A238251B9C74A90082EB20 /* Record */ = { isa = PBXGroup; children = ( + 5674A7251F30A8EF0095F066 /* FetchableRecord */, 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73EB203DA29B000C443C /* JoinSupportTests.swift */, - 560B3FA41C19DFF800C58EC7 /* Persistable */, + 560B3FA41C19DFF800C58EC7 /* PersistableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, - 5680521C2013296800E87861 /* RecordBoxTests.swift */, - 5674A7251F30A8EF0095F066 /* RowConvertible */, - 56176C9C1EACEA8C000F3F2B /* TableMapping */, + 56176C9C1EACEA8C000F3F2B /* TableRecord */, ); name = Record; sourceTree = ""; @@ -1565,7 +1711,7 @@ 56A238751B9C75030082EB20 /* DatabaseValue.swift */, 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, - 5636E9BB1D22574100B9B05F /* Request.swift */, + 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, @@ -1591,15 +1737,14 @@ 56A2389F1B9C753B0082EB20 /* Record */ = { isa = PBXGroup; children = ( + 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */, + 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */, + 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, - 560D92441C672C4B00F4F92B /* Persistable.swift */, - 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */, + 560D92441C672C4B00F4F92B /* PersistableRecord.swift */, + 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, - 5680520A2013209300E87861 /* RecordBox.swift */, - 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */, - 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */, - 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */, - 560D92461C672C4B00F4F92B /* TableMapping.swift */, + 560D92461C672C4B00F4F92B /* TableRecord.swift */, ); path = Record; sourceTree = ""; @@ -1614,7 +1759,7 @@ 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */, 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, - 569B7FA6201C904C0069DE70 /* Swift4.1.swift */, + 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */, ); path = Legacy; sourceTree = ""; @@ -1630,7 +1775,6 @@ 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */, 562393561DEE013C00A6B01F /* FilterCursorTests.swift */, 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */, - 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */, 562393711DEE104400A6B01F /* MapCursorTests.swift */, 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */, 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */, @@ -1993,25 +2137,30 @@ files = ( 56873BED1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D3E1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, - 5636E9BD1D22574100B9B05F /* Request.swift in Sources */, + 5616AAF9207CD5A900AC3664 /* RequestProtocols.swift in Sources */, + 5636E9BD1D22574100B9B05F /* FetchRequest.swift in Sources */, 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 /* RowConvertible.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 */, @@ -2021,13 +2170,14 @@ 5698AC381D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */, 5659F4991EA8D989004A4992 /* Pool.swift in Sources */, - 569B7FA8201C904C0069DE70 /* Swift4.1.swift in Sources */, - 5674A6FA1F307F600095F066 /* Persistable+Encodable.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 */, @@ -2039,24 +2189,25 @@ 56CEB55B1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D301DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 560FC52A1CB003810014AA8E /* DatabaseError.swift in Sources */, - 56D51D011EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */, + 5656BF5E20C7248700F98521 /* QueryOrdering.swift in Sources */, + 56D51D011EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BB1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 560FC52B1CB003810014AA8E /* DatabaseValue.swift in Sources */, 5671FC211DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 560FC52E1CB003810014AA8E /* Record.swift in Sources */, 56CEB5461EAA359A00BFAF62 /* Column.swift in Sources */, 5657AB101D10899D006283EF /* URL.swift in Sources */, - 560FC5311CB003810014AA8E /* TableMapping.swift in Sources */, + 560FC5311CB003810014AA8E /* TableRecord.swift in Sources */, 56DAA2DC1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6F11F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */, 560FC5331CB003810014AA8E /* Migration.swift in Sources */, - 560FC5341CB003810014AA8E /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + 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 */, @@ -2066,20 +2217,24 @@ 560FC5391CB003810014AA8E /* DatabaseReader.swift in Sources */, 560FC53A1CB003810014AA8E /* NSNull.swift in Sources */, 56CEB51A1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A7011F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, + 5674A7011F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5698AC791DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 560FC53B1CB003810014AA8E /* Database.swift in Sources */, 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 */, - 5680520C2013209300E87861 /* RecordBox.swift in Sources */, - 560FC5411CB003810014AA8E /* Persistable.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 */, @@ -2093,17 +2248,17 @@ files = ( 560FC5611CB00B880014AA8E /* DatabaseValueConversionTests.swift in Sources */, 560FC5B31CB031EA0014AA8E /* DataMemoryTests.swift in Sources */, - 56FF45411D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, + 56FF45411D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, 560FC5621CB00B880014AA8E /* Record+QueryInterfaceRequestTests.swift in Sources */, 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 */, 560FC5B21CB031E30014AA8E /* StatementColumnConvertibleFetchTests.swift in Sources */, 561667021D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, - 5680521E2013296F00E87861 /* RecordBoxTests.swift in Sources */, 562EA8271F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 569C1EB31CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */, 560FC5651CB00B880014AA8E /* RecordPrimaryKeyNoneTests.swift in Sources */, @@ -2117,19 +2272,24 @@ 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 */, + 56EA63CC209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 560FC5701CB00B880014AA8E /* DatabasePoolCollationTests.swift in Sources */, 560FC5711CB00B880014AA8E /* RecordPrimaryKeySingleTests.swift in Sources */, 560FC5721CB00B880014AA8E /* StatementColumnConvertibleTests.swift in Sources */, 5674A7191F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, - 56B021CA1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 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 */, @@ -2137,7 +2297,6 @@ 566AD8C71D531BEA002EC1A8 /* TableDefinitionTests.swift in Sources */, 560FC5781CB00B880014AA8E /* RowFromStatementTests.swift in Sources */, 560FC5791CB00B880014AA8E /* RecordPrimaryKeyMultipleTests.swift in Sources */, - 562393461DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 56CC9257201E094F00CB597E /* PrefixCursorTests.swift in Sources */, 5698AC971DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 5657AB4F1D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, @@ -2151,12 +2310,14 @@ 560FC57D1CB00B880014AA8E /* RecordInitializersTests.swift in Sources */, 56176C5F1EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 565F03C31CE5D3AA00DE108F /* RowAdapterTests.swift in Sources */, + 56B6EF64208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */, 5657AB3F1D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, - 560FC57E1CB00B880014AA8E /* MutablePersistableTests.swift in Sources */, + 560FC57E1CB00B880014AA8E /* MutablePersistableRecordTests.swift in Sources */, 5657AB5F1D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, - 560FC57F1CB00B880014AA8E /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + 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,14 +2326,16 @@ 560FC5811CB00B880014AA8E /* RecordCopyTests.swift in Sources */, 560FC5821CB00B880014AA8E /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 567E55ED1D2BDD3D00CC6F79 /* EncryptionTests.swift in Sources */, - 56741EA91E66A8B3003E422D /* RequestTests.swift in Sources */, + 56741EA91E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56176C641EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, - 560FC5841CB00B880014AA8E /* PersistableTests.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 /* RowConvertibleDecodableTests.swift in Sources */, + 5674A72C1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 56C3F7541CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, - 56FEE7FC1F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE7FC1F47253700D930EA /* TableRecordTests.swift in Sources */, 56F3E74A1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 567A80541D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 560FC58B1CB00B880014AA8E /* DatabaseValueTests.swift in Sources */, @@ -2181,18 +2344,23 @@ 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 */, 562393311DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, - 560FC5921CB00B880014AA8E /* RowConvertibleTests.swift in Sources */, + 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 */, @@ -2205,9 +2373,9 @@ 5623936A1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, 560FC59C1CB00B880014AA8E /* StatementArguments+FoundationTests.swift in Sources */, 5657AB671D108BA9006283EF /* FoundationURLTests.swift in Sources */, - 560FC59D1CB00B880014AA8E /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + 560FC59D1CB00B880014AA8E /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 562205F51E420E48005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, - 566A84462041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84462041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 562393581DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 560FC59E1CB00B880014AA8E /* FoundationNSDateTests.swift in Sources */, 568068321EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, @@ -2216,7 +2384,7 @@ 5698ACCF1DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 560FC5A21CB00B880014AA8E /* DatabaseFunctionTests.swift in Sources */, 560FC5A41CB00B880014AA8E /* RecordWithColumnNameManglingTests.swift in Sources */, - 5674A7221F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A7221F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 5690C3271D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, 560FC5A51CB00B880014AA8E /* CGFloatTests.swift in Sources */, 56FF45571D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, @@ -2224,6 +2392,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 */, @@ -2241,17 +2410,17 @@ files = ( 5671561D1CB16729007DC145 /* DatabaseValueConversionTests.swift in Sources */, 5671561E1CB16729007DC145 /* DataMemoryTests.swift in Sources */, - 56FF45421D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, + 56FF45421D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, 5671561F1CB16729007DC145 /* Record+QueryInterfaceRequestTests.swift in Sources */, 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 */, 567156241CB16729007DC145 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 567156251CB16729007DC145 /* RowFromDictionaryTests.swift in Sources */, - 5680521F2013296F00E87861 /* RecordBoxTests.swift in Sources */, 562EA8281F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 565F03C41CE5D3AA00DE108F /* RowAdapterTests.swift in Sources */, 567156261CB16729007DC145 /* SelectStatementTests.swift in Sources */, @@ -2265,19 +2434,24 @@ 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 */, + 56EA63CD209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 56C3F7551CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, - 56B021CB1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021CB1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 5674A71B1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 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 */, @@ -2287,7 +2461,6 @@ 567156371CB16729007DC145 /* RecordPrimaryKeyMultipleTests.swift in Sources */, 5657AB401D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56CC9258201E094F00CB597E /* PrefixCursorTests.swift in Sources */, - 562393471DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 5698AC981DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56CC9237201E009800CB597E /* DropWhileCursorTests.swift in Sources */, 56D507601F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, @@ -2299,28 +2472,32 @@ 5671563B1CB16729007DC145 /* RecordInitializersTests.swift in Sources */, 56176C651EACCCC8000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 5657AB681D108BA9006283EF /* FoundationURLTests.swift in Sources */, - 5671563C1CB16729007DC145 /* MutablePersistableTests.swift in Sources */, - 5671563D1CB16729007DC145 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + 56B6EF65208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */, + 5671563C1CB16729007DC145 /* MutablePersistableRecordTests.swift in Sources */, + 5671563D1CB16729007DC145 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 567E55F31D2BDDFE00CC6F79 /* EncryptionTests.swift in Sources */, 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 */, - 567156411CB16729007DC145 /* PersistableTests.swift in Sources */, + 567156411CB16729007DC145 /* PersistableRecordTests.swift in Sources */, 5665F86D203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */, 5657AB501D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, 567156441CB16729007DC145 /* RecordSubClassTests.swift in Sources */, 5690C3391D23E7D200E59934 /* FoundationDateTests.swift in Sources */, - 56741EAA1E66A8B3003E422D /* RequestTests.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 /* RowConvertibleDecodableTests.swift in Sources */, + 5674A72E1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 5671564A1CB16729007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */, - 56FEE7FD1F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE7FD1F47253700D930EA /* TableRecordTests.swift in Sources */, 56F3E74B1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 5671564B1CB16729007DC145 /* Row+FoundationTests.swift in Sources */, 56A8C2431D1918EE0096E9D4 /* FoundationNSUUIDTests.swift in Sources */, @@ -2329,18 +2506,23 @@ 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 */, - 567156511CB16729007DC145 /* RowConvertibleTests.swift in Sources */, + 5653EBD120961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, + 567156511CB16729007DC145 /* FetchableRecordTests.swift in Sources */, 56A8C2441D1918EE0096E9D4 /* FoundationUUIDTests.swift in Sources */, 56CC924D201E059100CB597E /* DropFirstCursorTests.swift in Sources */, 562393321DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 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 */, @@ -2355,16 +2537,16 @@ 5671565A1CB16729007DC145 /* StatementArguments+FoundationTests.swift in Sources */, 5657AB581D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 562205F81E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, - 566A84472041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84472041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 562393591DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, - 5671565B1CB16729007DC145 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + 5671565B1CB16729007DC145 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 568068331EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 5671565C1CB16729007DC145 /* FoundationNSDateTests.swift in Sources */, 5671565D1CB16729007DC145 /* DatabaseTests.swift in Sources */, 5671565E1CB16729007DC145 /* QueryInterfaceRequestTests.swift in Sources */, 5698ACD01DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 569178481CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */, - 5674A7241F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A7241F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 5634B1091CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 567156601CB16729007DC145 /* DatabaseFunctionTests.swift in Sources */, 567156611CB16729007DC145 /* RecordWithColumnNameManglingTests.swift in Sources */, @@ -2372,6 +2554,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 */, @@ -2389,25 +2572,30 @@ files = ( 56873BF01F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D411DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, - 5636E9C01D22574100B9B05F /* Request.swift in Sources */, + 5616AAFA207CD5A900AC3664 /* RequestProtocols.swift in Sources */, + 5636E9C01D22574100B9B05F /* FetchRequest.swift in Sources */, 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 /* RowConvertible.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 */, @@ -2417,13 +2605,14 @@ 5698AC3B1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */, 5659F49C1EA8D989004A4992 /* Pool.swift in Sources */, - 569B7FA9201C904C0069DE70 /* Swift4.1.swift in Sources */, - 5674A6F71F307F600095F066 /* Persistable+Encodable.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 */, @@ -2435,11 +2624,12 @@ 56CEB55E1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D331DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 56AFC9FF1CB1A8BB00F48B96 /* DatabaseValueConvertible.swift in Sources */, - 56D51D041EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */, + 5656BF5F20C7248700F98521 /* QueryOrdering.swift in Sources */, + 56D51D041EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BE1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56AFCA001CB1A8BB00F48B96 /* Record.swift in Sources */, 5671FC241DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, - 56AFCA031CB1A8BB00F48B96 /* TableMapping.swift in Sources */, + 56AFCA031CB1A8BB00F48B96 /* TableRecord.swift in Sources */, 56CEB5491EAA359A00BFAF62 /* Column.swift in Sources */, 5657AB131D10899D006283EF /* URL.swift in Sources */, 56AFCA061CB1A8BB00F48B96 /* Configuration.swift in Sources */, @@ -2447,12 +2637,12 @@ 5674A6EE1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */, 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */, - 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + 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 */, @@ -2462,20 +2652,24 @@ 56AFCA0F1CB1A8BB00F48B96 /* NSNull.swift in Sources */, 56AFCA101CB1A8BB00F48B96 /* DatabaseQueue.swift in Sources */, 56CEB51D1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A6FE1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, + 5674A6FE1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5698AC7C1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56AFCA111CB1A8BB00F48B96 /* DatabaseError.swift in Sources */, 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 */, - 56AFCA151CB1A8BB00F48B96 /* Persistable.swift in Sources */, 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */, - 5680520D2013209900E87861 /* RecordBox.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 */, @@ -2489,17 +2683,17 @@ files = ( 56AFCA301CB1AA9900F48B96 /* Record+QueryInterfaceRequestTests.swift in Sources */, 562393771DEE104400A6B01F /* MapCursorTests.swift in Sources */, - 56B021CE1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021CE1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 56F26C241CEE3F34007969C4 /* RowAdapterTests.swift in Sources */, 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 */, 56AFCA341CB1AA9900F48B96 /* RowFromDictionaryTests.swift in Sources */, 569C1EB61CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */, - 568052202013297000E87861 /* RecordBoxTests.swift in Sources */, 562EA82B1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 56DAA2D71DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, 5698AC4E1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, @@ -2513,7 +2707,9 @@ 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 */, + 56EA63CE209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 56AFCA3F1CB1AA9900F48B96 /* RecordPrimaryKeySingleTests.swift in Sources */, 56AFCA411CB1AA9900F48B96 /* StatementColumnConvertibleTests.swift in Sources */, 56AFCA421CB1AA9900F48B96 /* DatabasePoolFunctionTests.swift in Sources */, @@ -2521,11 +2717,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 */, @@ -2533,10 +2732,10 @@ 56B15D0C1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56AFCA4A1CB1AA9900F48B96 /* RecordInitializersTests.swift in Sources */, 566AD8CB1D531BED002EC1A8 /* TableDefinitionTests.swift in Sources */, - 56AFCA4B1CB1AA9900F48B96 /* MutablePersistableTests.swift in Sources */, + 56AFCA4B1CB1AA9900F48B96 /* MutablePersistableRecordTests.swift in Sources */, 56CC9259201E094F00CB597E /* PrefixCursorTests.swift in Sources */, 5657AB431D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, - 56AFCA4C1CB1AA9900F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + 56AFCA4C1CB1AA9900F48B96 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56CC9238201E009900CB597E /* DropWhileCursorTests.swift in Sources */, 56D507631F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C751EACCCCA000F3F2B /* FTS5TokenizerTests.swift in Sources */, @@ -2546,12 +2745,14 @@ 5657AB6B1D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56AFCA4F1CB1AA9900F48B96 /* DataMemoryTests.swift in Sources */, 56176C711EACCCCA000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, + 56B6EF66208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */, 5672DE5D1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56AFCA501CB1AA9900F48B96 /* RecordCopyTests.swift in Sources */, - 56FF45451D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, - 56AFCA521CB1AA9900F48B96 /* PersistableTests.swift in Sources */, + 56FF45451D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 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 */, @@ -2561,14 +2762,16 @@ 5698ACBB1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 56AFCA561CB1AA9900F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */, 56AFCA571CB1AA9900F48B96 /* TransactionObserverTests.swift in Sources */, - 56741EAD1E66A8B3003E422D /* RequestTests.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 /* RowConvertibleDecodableTests.swift in Sources */, + 5674A72B1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 56AF74701D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, - 56FEE8001F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE8001F47253700D930EA /* TableRecordTests.swift in Sources */, 56F3E74E1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 5690C33C1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 56AFCA581CB1AA9900F48B96 /* Row+FoundationTests.swift in Sources */, @@ -2576,18 +2779,23 @@ 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 */, - 56AFCA5E1CB1AA9900F48B96 /* RowConvertibleTests.swift in Sources */, + 5653EBD220961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, + 56AFCA5E1CB1AA9900F48B96 /* FetchableRecordTests.swift in Sources */, 56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56CC924E201E059100CB597E /* DropFirstCursorTests.swift in Sources */, 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 */, @@ -2597,22 +2805,21 @@ 56176C741EACCCCA000F3F2B /* FTS5TableBuilderTests.swift in Sources */, 5657AB3B1D108BA9006283EF /* FoundationDataTests.swift in Sources */, 5698AC081D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, - 5623934A1DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 56AFCA661CB1AA9900F48B96 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 561667061D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, 565EFAF31D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, 56AFCA671CB1AA9900F48B96 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56AFCA681CB1AA9900F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, - 566A84482041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84482041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 56B14E841D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 56AFCA6B1CB1AA9900F48B96 /* DatabaseTimestampTests.swift in Sources */, 568068361EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56AFCA6C1CB1AA9900F48B96 /* StatementArguments+FoundationTests.swift in Sources */, 562393651DEE06D300A6B01F /* CursorTests.swift in Sources */, 5657AB5B1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, - 56AFCA6D1CB1AA9900F48B96 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + 56AFCA6D1CB1AA9900F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCA6E1CB1AA9900F48B96 /* FoundationNSDateTests.swift in Sources */, - 5674A7211F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A7211F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56AFCA6F1CB1AA9900F48B96 /* DatabaseTests.swift in Sources */, 56AFCA701CB1AA9900F48B96 /* QueryInterfaceRequestTests.swift in Sources */, 5634B10B1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, @@ -2620,6 +2827,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 */, @@ -2637,17 +2845,17 @@ files = ( 56C3F7581CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 562393781DEE104400A6B01F /* MapCursorTests.swift in Sources */, - 56B021CF1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021CF1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 56AFCA891CB1ABC800F48B96 /* Record+QueryInterfaceRequestTests.swift in Sources */, 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 */, 56AFCA8D1CB1ABC800F48B96 /* RowFromDictionaryTests.swift in Sources */, 5657AB541D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, - 568052212013297000E87861 /* RecordBoxTests.swift in Sources */, 562EA82C1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 56DAA2D81DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, 5698AC4F1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, @@ -2661,7 +2869,9 @@ 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 */, + 56EA63CF209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 5657AB641D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 56FF455C1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56AFCA971CB1ABC800F48B96 /* DatabasePoolCollationTests.swift in Sources */, @@ -2669,11 +2879,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 */, @@ -2689,17 +2902,19 @@ 56D507641F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C7B1EACCCCB000F3F2B /* FTS5TokenizerTests.swift in Sources */, 566AD8CC1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */, - 56AFCAA41CB1ABC800F48B96 /* MutablePersistableTests.swift in Sources */, + 56AFCAA41CB1ABC800F48B96 /* MutablePersistableRecordTests.swift in Sources */, 567F45AE1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, - 56AFCAA51CB1ABC800F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + 56AFCAA51CB1ABC800F48B96 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */, 56176C771EACCCCB000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, + 56B6EF67208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */, 5657AB6C1D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56AFCAA81CB1ABC800F48B96 /* DataMemoryTests.swift in Sources */, 56AFCAA91CB1ABC800F48B96 /* RecordCopyTests.swift in Sources */, 56A8C24B1D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */, - 56AFCAAB1CB1ABC800F48B96 /* PersistableTests.swift in Sources */, - 56FF45461D2C23BA00F21EF9 /* MutablePersistableDeleteTests.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 */, @@ -2709,14 +2924,16 @@ 5698ACBC1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5657AB441D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 5623935D1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, - 56741EAE1E66A8B3003E422D /* RequestTests.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 /* RowConvertibleDecodableTests.swift in Sources */, + 5674A7281F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 56AFCAAE1CB1ABC800F48B96 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, - 56FEE8011F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE8011F47253700D930EA /* TableRecordTests.swift in Sources */, 56F3E74F1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 56AFCAAF1CB1ABC800F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */, 56AFCAB01CB1ABC800F48B96 /* TransactionObserverTests.swift in Sources */, @@ -2724,18 +2941,23 @@ 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 */, 56CC924F201E059100CB597E /* DropFirstCursorTests.swift in Sources */, - 56AFCAB71CB1ABC800F48B96 /* RowConvertibleTests.swift in Sources */, + 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 */, @@ -2745,22 +2967,21 @@ 56176C7A1EACCCCB000F3F2B /* FTS5TableBuilderTests.swift in Sources */, 561667071D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, 5698AC091D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, - 5623934B1DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 56AFCABD1CB1ABC800F48B96 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56AFCABE1CB1ABC800F48B96 /* DatabaseErrorTests.swift in Sources */, 56AFCABF1CB1ABC800F48B96 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 56AFCAC01CB1ABC800F48B96 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56AFCAC11CB1ABC800F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, - 566A84492041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84492041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 56B14E851D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 56AFCAC41CB1ABC800F48B96 /* DatabaseTimestampTests.swift in Sources */, 568068371EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56AFCAC51CB1ABC800F48B96 /* StatementArguments+FoundationTests.swift in Sources */, 562393661DEE06D300A6B01F /* CursorTests.swift in Sources */, - 56AFCAC61CB1ABC800F48B96 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + 56AFCAC61CB1ABC800F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCAC71CB1ABC800F48B96 /* FoundationNSDateTests.swift in Sources */, 56AFCAC81CB1ABC800F48B96 /* DatabaseTests.swift in Sources */, - 5674A71E1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A71E1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56AFCAC91CB1ABC800F48B96 /* QueryInterfaceRequestTests.swift in Sources */, 5691784B1CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */, 56AFCACB1CB1ABC800F48B96 /* DatabaseFunctionTests.swift in Sources */, @@ -2768,6 +2989,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 */, @@ -2853,7 +3075,6 @@ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2890,7 +3111,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipherOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2927,7 +3147,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipherOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2978,7 +3197,6 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -3016,7 +3234,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipheriOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -3053,7 +3270,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipheriOSEncryptedTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -3153,7 +3369,6 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 4.0; VALIDATE_PRODUCT = YES; diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index f0a987832..1880e4601 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -10,6 +10,8 @@ 56071A501DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 561667041D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 561667081D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; + 5616AAF6207CD59400AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */; }; + 5616AAF7207CD59400AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */; }; 56176C7E1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; 56176C801EACCD31000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; 562205FA1E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; }; @@ -23,8 +25,6 @@ 5623931F1DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; }; 562393331DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; 562393371DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; - 562393481DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; - 5623934C1DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; 562393511DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; 562393551DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; 5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393561DEE013C00A6B01F /* FilterCursorTests.swift */; }; @@ -41,8 +41,8 @@ 562EA82D1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; }; 562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 562EA8361F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; - 5636E9BE1D22574100B9B05F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; - 5636E9C11D22574100B9B05F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; + 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; + 5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; @@ -51,6 +51,56 @@ 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 */; }; + 5656BF5A20C7247100F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5820C7247100F98521 /* QueryOrdering.swift */; }; + 5656BF5B20C7247100F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5820C7247100F98521 /* QueryOrdering.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 */; }; @@ -95,8 +145,8 @@ 566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */; }; 566A843520413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */; }; 566A843620413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */; }; - 566A84432041AB2D00E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutablePersistableChangesTests.swift */; }; - 566A84442041AB2D00E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutablePersistableChangesTests.swift */; }; + 566A84432041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */; }; + 566A84442041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */; }; 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8C91D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; }; @@ -115,26 +165,26 @@ 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; }; 5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; 5671FC251DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; - 56741EAB1E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; - 56741EAF1E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; + 56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; + 56741EAF1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; 5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6ED1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; - 5674A6F51F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6F61F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6FC1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; - 5674A6FD1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; + 5674A6F51F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6F61F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; + 5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; 5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A7051F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A70C1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */; }; 5674A70E1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */; }; 5674A7141F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A7161F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; - 5674A71D1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A71F1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A7271F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; - 5674A7291F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; + 5674A71D1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A71F1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567DAF1E1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; @@ -143,10 +193,6 @@ 567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; 567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; - 568052092013207000E87861 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568052072013206F00E87861 /* RecordBox.swift */; }; - 5680520E201320A200E87861 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568052072013206F00E87861 /* RecordBox.swift */; }; - 5680521A2013295600E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568052182013295100E87861 /* RecordBoxTests.swift */; }; - 5680521B2013295700E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568052182013295100E87861 /* RecordBoxTests.swift */; }; 568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 56873BEE1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; @@ -191,8 +237,8 @@ 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; }; 5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.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 */; }; + 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 */; }; 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 */; }; @@ -207,10 +253,12 @@ 56A8C24E1D1918F30096E9D4 /* FoundationUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C21E1D1914110096E9D4 /* FoundationUUIDTests.swift */; }; 56AF746E1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; - 56B021CC1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; - 56B021D01D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; + 56B021CC1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021D01D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E821D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; + 56B6EF60208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */; }; + 56B6EF61208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */; }; 56B9649F1DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; 56B964A21DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; }; @@ -240,8 +288,8 @@ 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9248201E058900CB597E /* DropFirstCursorTests.swift */; }; 56CC9254201E094600CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9253201E094600CB597E /* PrefixCursorTests.swift */; }; 56CC9255201E094600CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9253201E094600CB597E /* PrefixCursorTests.swift */; }; - 56CEB4F31EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; - 56CEB4F61EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; + 56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; + 56CEB4F61EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB5031EAA2F4D00BFAF62 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; }; @@ -264,14 +312,16 @@ 56D1215F1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */; }; 56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; - 56D51D021EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; - 56D51D051EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; + 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; 56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; 56E06F141E859069008AE2A4 /* Fixits-0.102.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */; }; 56E06F171E85906D008AE2A4 /* Fixits-0.102.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */; }; + 56EA63C9209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */; }; + 56EA63CA209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */; }; 56ED8A7F1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; }; 56ED8A801DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; }; 56F3E74C1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; @@ -280,10 +330,10 @@ 56F3E7681E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */; }; 56FC987A1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FC987D1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; - 56FEE7FE1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; - 56FEE8021F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; - 56FF45431D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; - 56FF45471D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; + 56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; + 56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; + 56FF45431D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + 56FF45471D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; 56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 56FF455D1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; @@ -315,13 +365,13 @@ F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA802B1CFB289B003DC1BA /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - F3BA802F1CFB289B003DC1BA /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + F3BA802F1CFB289B003DC1BA /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; - F3BA80331CFB28A4003DC1BA /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; + F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; - F3BA80361CFB28A4003DC1BA /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; + F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; F3BA80381CFB2932003DC1BA /* GRDBCustomSQLite.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF11CFB23D3003DC1BA /* GRDBCustomSQLite.h */; settings = {ATTRIBUTES = (Public, ); }; }; F3BA80391CFB2936003DC1BA /* GRDBCustomSQLite-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF21CFB23DA003DC1BA /* GRDBCustomSQLite-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; F3BA803A1CFB293A003DC1BA /* sqlite3.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF01CFB23C9003DC1BA /* sqlite3.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -359,13 +409,13 @@ F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA80871CFB2E70003DC1BA /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - F3BA808B1CFB2E70003DC1BA /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + F3BA808B1CFB2E70003DC1BA /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; - F3BA808F1CFB2E7A003DC1BA /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; + F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; - F3BA80921CFB2E7A003DC1BA /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; + F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; F3BA80931CFB2F13003DC1BA /* GRDBCustomSQLite.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF11CFB23D3003DC1BA /* GRDBCustomSQLite.h */; settings = {ATTRIBUTES = (Public, ); }; }; F3BA80941CFB2F15003DC1BA /* GRDBCustomSQLite-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF21CFB23DA003DC1BA /* GRDBCustomSQLite-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; F3BA80951CFB2F18003DC1BA /* sqlite3.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF01CFB23C9003DC1BA /* sqlite3.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -401,10 +451,10 @@ F3BA80CE1CFB2FDE003DC1BA /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 5687359E1CEDE16C009B9116 /* Betty.jpeg */; }; F3BA80CF1CFB2FEA003DC1BA /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; F3BA80D01CFB2FEC003DC1BA /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; - F3BA80D11CFB2FF3003DC1BA /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - F3BA80D21CFB2FF3003DC1BA /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; - F3BA80D31CFB2FF4003DC1BA /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - F3BA80D41CFB2FF4003DC1BA /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + F3BA80D11CFB2FF3003DC1BA /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + F3BA80D21CFB2FF3003DC1BA /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; + F3BA80D31CFB2FF4003DC1BA /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + F3BA80D41CFB2FF4003DC1BA /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; F3BA80D51CFB2FFB003DC1BA /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; F3BA80D71CFB300A003DC1BA /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; @@ -425,12 +475,12 @@ F3BA80E81CFB3016003DC1BA /* RowFromDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381E1B9C74A90082EB20 /* RowFromDictionaryTests.swift */; }; F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; F3BA80EA1CFB3016003DC1BA /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; - F3BA80EB1CFB3016003DC1BA /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + F3BA80EB1CFB3016003DC1BA /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; F3BA80EC1CFB3017003DC1BA /* RowCopiedFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381F1B9C74A90082EB20 /* RowCopiedFromStatementTests.swift */; }; F3BA80ED1CFB3017003DC1BA /* RowFromDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381E1B9C74A90082EB20 /* RowFromDictionaryTests.swift */; }; F3BA80EE1CFB3017003DC1BA /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; F3BA80EF1CFB3017003DC1BA /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; - F3BA80F01CFB3017003DC1BA /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; F3BA80F11CFB3019003DC1BA /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; }; F3BA80F21CFB301A003DC1BA /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; }; F3BA80F31CFB301D003DC1BA /* StatementColumnConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EE573C1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift */; }; @@ -459,14 +509,14 @@ F3BA81131CFB305B003DC1BA /* DatabaseMigratorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238241B9C74A90082EB20 /* DatabaseMigratorTests.swift */; }; F3BA81141CFB305E003DC1BA /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; F3BA81151CFB305E003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; - F3BA81161CFB305E003DC1BA /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + F3BA81161CFB305E003DC1BA /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; - F3BA81181CFB305E003DC1BA /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + F3BA81181CFB305E003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; F3BA811A1CFB305F003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; - F3BA811B1CFB305F003DC1BA /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + F3BA811B1CFB305F003DC1BA /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; F3BA811C1CFB305F003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; - F3BA811D1CFB305F003DC1BA /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + F3BA811D1CFB305F003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238261B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift */; }; F3BA811F1CFB3063003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; F3BA81201CFB3063003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238281B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift */; }; @@ -543,7 +593,7 @@ 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; - 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceSelectQueryDefinition.swift; sourceTree = ""; }; + 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceQuery.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; @@ -551,12 +601,12 @@ 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunctionTests.swift; sourceTree = ""; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; - 560D92441C672C4B00F4F92B /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = ""; }; - 560D92461C672C4B00F4F92B /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = ""; }; + 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; + 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; + 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; - 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IteratorCursorTests.swift; sourceTree = ""; }; 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = ""; }; 562393561DEE013C00A6B01F /* FilterCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FilterCursorTests.swift; sourceTree = ""; }; 5623935F1DEE06D300A6B01F /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = ""; }; @@ -567,25 +617,50 @@ 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = ""; }; 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; - 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExpressionsTests.swift; sourceTree = ""; }; - 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableMapping+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; - 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableTests.swift; sourceTree = ""; }; - 563363AA1C933FF8000BE133 /* PersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableTests.swift; sourceTree = ""; }; + 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordTests.swift; sourceTree = ""; }; + 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecordTests.swift; sourceTree = ""; }; 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueConcurrencyTests.swift; sourceTree = ""; }; 563363BF1C942C04000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = ""; }; 563363C31C942C37000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = ""; }; 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReleaseMemoryTests.swift; sourceTree = ""; }; 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; - 5636E9BB1D22574100B9B05F /* Request.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = ""; }; + 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 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 = ""; }; + 5656BF5820C7247100F98521 /* QueryOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryOrdering.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 = ""; }; @@ -599,7 +674,7 @@ 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = ""; }; 5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = ""; }; 5659F49F1EA8D997004A4992 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = ""; }; - 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = ""; }; + 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = ""; }; 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; @@ -612,7 +687,7 @@ 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; - 566A84422041AB2D00E50BFD /* MutablePersistableChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableChangesTests.swift; sourceTree = ""; }; + 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = ""; }; 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = ""; }; 566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = ""; }; @@ -627,22 +702,20 @@ 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueBackupTests.swift; sourceTree = ""; }; 5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = ""; }; 567404871CEF84C8003ED5CC /* RowAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowAdapter.swift; sourceTree = ""; }; - 56741EA71E66A8B3003E422D /* RequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestTests.swift; sourceTree = ""; }; + 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; - 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RowConvertible+Decodable.swift"; sourceTree = ""; }; - 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Persistable+Encodable.swift"; sourceTree = ""; }; + 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+Decodable.swift"; sourceTree = ""; }; + 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Encodable.swift"; sourceTree = ""; }; 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = ""; }; 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = ""; }; 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; - 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableEncodableTests.swift; sourceTree = ""; }; - 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowConvertibleDecodableTests.swift; sourceTree = ""; }; + 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = ""; }; + 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; - 568052072013206F00E87861 /* RecordBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordBox.swift; sourceTree = ""; }; - 568052182013295100E87861 /* RecordBoxTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordBoxTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = ""; }; @@ -672,7 +745,7 @@ 5698AD151DAAD16F0056AF8C /* FTS5Tokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5Tokenizer.swift; sourceTree = ""; }; 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 = ""; }; - 569B7FA2201C90430069DE70 /* Swift4.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; + 569A98F62039B716008D7DBF /* Fixits-3.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-3.0.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 = ""; }; @@ -715,9 +788,10 @@ 56A8C22F1D1914540096E9D4 /* UUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUID.swift; sourceTree = ""; }; 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = ""; }; 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; - 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistablePersistenceConflictPolicyTests.swift; sourceTree = ""; }; + 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 = ""; }; + 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; 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 = ""; }; 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = ""; }; @@ -739,7 +813,7 @@ 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; 56CC9248201E058900CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; 56CC9253201E094600CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; - 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; + 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecord.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS3+QueryInterfaceRequest.swift"; sourceTree = ""; }; @@ -751,13 +825,14 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = ""; }; 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.109.0.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; - 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+TableMapping.swift"; sourceTree = ""; }; + 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.102.0.swift"; sourceTree = ""; }; 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = ""; }; + 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = ""; }; 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = ""; }; 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = ""; }; 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = ""; }; @@ -768,8 +843,8 @@ 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 /* TableMappingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableMappingTests.swift; sourceTree = ""; }; - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableDeleteTests.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 = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; @@ -896,17 +971,17 @@ name = DatabasePool; sourceTree = ""; }; - 560B3FA41C19DFF800C58EC7 /* Persistable */ = { + 560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = { isa = PBXGroup; children = ( - 566A84422041AB2D00E50BFD /* MutablePersistableChangesTests.swift */, - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */, - 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */, - 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */, - 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */, - 563363AA1C933FF8000BE133 /* PersistableTests.swift */, + 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */, + 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, + 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, + 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, + 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, + 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, ); - name = Persistable; + name = PersistableRecord; sourceTree = ""; }; 5614DEEE1BA9D6F9003163B3 /* Frameworks */ = { @@ -933,12 +1008,12 @@ path = GRDBTests; sourceTree = ""; }; - 56176C9C1EACEA8C000F3F2B /* TableMapping */ = { + 56176C9C1EACEA8C000F3F2B /* TableRecord */ = { isa = PBXGroup; children = ( - 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */, + 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */, ); - name = TableMapping; + name = TableRecord; sourceTree = ""; }; 56176C9E1EACEDF9000F3F2B /* Record */ = { @@ -991,13 +1066,16 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EB5620961F8900F46237 /* Association */, + 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */, + 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */, + 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, - 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, - 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */, + 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, ); name = QueryInterface; @@ -1006,16 +1084,21 @@ 56300B6D1C53F592005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EB3620961F6000F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, + 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, - 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */, + 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */, + 5656BF5820C7247100F98521 /* QueryOrdering.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 */, @@ -1040,6 +1123,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 = ( @@ -1060,13 +1179,13 @@ path = Support; sourceTree = ""; }; - 5674A7251F30A8EF0095F066 /* RowConvertible */ = { + 5674A7251F30A8EF0095F066 /* FetchableRecord */ = { isa = PBXGroup; children = ( - 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */, - 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */, + 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */, + 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */, ); - name = RowConvertible; + name = FetchableRecord; sourceTree = ""; }; 5698AC291D9E5A480056AF8C /* FTS */ = { @@ -1142,11 +1261,11 @@ 56A238191B9C74A90082EB20 /* DatabaseValueConvertible */, 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */, 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */, + 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */, 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */, 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */, 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */, 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */, - 56741EA71E66A8B3003E422D /* RequestTests.swift */, 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */, 56A2381D1B9C74A90082EB20 /* Row */, 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */, @@ -1206,13 +1325,12 @@ 56A238251B9C74A90082EB20 /* Record */ = { isa = PBXGroup; children = ( + 5674A7251F30A8EF0095F066 /* FetchableRecord */, 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73E7203DA278000C443C /* JoinSupportTests.swift */, - 560B3FA41C19DFF800C58EC7 /* Persistable */, + 560B3FA41C19DFF800C58EC7 /* PersistableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, - 568052182013295100E87861 /* RecordBoxTests.swift */, - 5674A7251F30A8EF0095F066 /* RowConvertible */, - 56176C9C1EACEA8C000F3F2B /* TableMapping */, + 56176C9C1EACEA8C000F3F2B /* TableRecord */, ); name = Record; sourceTree = ""; @@ -1237,7 +1355,7 @@ 56A238751B9C75030082EB20 /* DatabaseValue.swift */, 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, - 5636E9BB1D22574100B9B05F /* Request.swift */, + 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, @@ -1263,15 +1381,14 @@ 56A2389F1B9C753B0082EB20 /* Record */ = { isa = PBXGroup; children = ( + 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */, + 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */, + 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, - 560D92441C672C4B00F4F92B /* Persistable.swift */, - 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */, + 560D92441C672C4B00F4F92B /* PersistableRecord.swift */, + 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, - 568052072013206F00E87861 /* RecordBox.swift */, - 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */, - 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */, - 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */, - 560D92461C672C4B00F4F92B /* TableMapping.swift */, + 560D92461C672C4B00F4F92B /* TableRecord.swift */, ); path = Record; sourceTree = ""; @@ -1286,7 +1403,7 @@ 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */, 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, - 569B7FA2201C90430069DE70 /* Swift4.1.swift */, + 569A98F62039B716008D7DBF /* Fixits-3.0.swift */, ); path = Legacy; sourceTree = ""; @@ -1302,7 +1419,6 @@ 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */, 562393561DEE013C00A6B01F /* FilterCursorTests.swift */, 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */, - 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */, 562393711DEE104400A6B01F /* MapCursorTests.swift */, 56CC9253201E094600CB597E /* PrefixCursorTests.swift */, 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */, @@ -1694,19 +1810,23 @@ files = ( 56873BF11F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D421DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, - 5636E9C11D22574100B9B05F /* Request.swift in Sources */, + 5616AAF7207CD59400AC3664 /* RequestProtocols.swift in Sources */, + 5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */, 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 /* RowConvertible.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 */, @@ -1722,26 +1842,28 @@ F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */, 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */, 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */, - 569B7FA5201C90430069DE70 /* Swift4.1.swift in Sources */, - 5674A6F61F307F600095F066 /* Persistable+Encodable.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 */, F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */, 56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */, - F3BA802F1CFB289B003DC1BA /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + F3BA802F1CFB289B003DC1BA /* QueryInterfaceQuery.swift in Sources */, 56CEB5061EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55F1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, F3BA80201CFB288C003DC1BA /* Date.swift in Sources */, 56A8C2351D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D341DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, - 56D51D051EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */, + 5656BF5B20C7247100F98521 /* QueryOrdering.swift in Sources */, + 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80151CFB2876003DC1BA /* DatabaseWriter.swift in Sources */, F3BA800A1CFB286A003DC1BA /* Configuration.swift in Sources */, 566475BF1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, @@ -1755,6 +1877,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 */, @@ -1762,25 +1885,29 @@ 56FC987D1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, F3BA80111CFB2876003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */, - F3BA80331CFB28A4003DC1BA /* Persistable.swift in Sources */, + F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */, 56BF6D3B1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, 56CEB51E1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A6FD1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, + 5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5698AC7D1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 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 */, - F3BA80361CFB28A4003DC1BA /* TableMapping.swift in Sources */, F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, - 5680520E201320A200E87861 /* RecordBox.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 */, @@ -1794,22 +1921,21 @@ files = ( F3BA80D71CFB300A003DC1BA /* DatabaseValueTests.swift in Sources */, F3BA80C81CFB2FD8003DC1BA /* DatabaseQueueTests.swift in Sources */, - 56FF45471D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, + 56FF45471D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, F3BA810C1CFB3056003DC1BA /* StatementArguments+FoundationTests.swift in Sources */, F3BA80B91CFB2FD1003DC1BA /* DatabasePoolBackupTests.swift in Sources */, F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 562EA8361F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, - 5623934C1DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, + 5653EB6D20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, F3BA80DD1CFB300E003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, F3BA80521CFB2B59003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */, F3BA80BE1CFB2FD1003DC1BA /* DatabasePoolReadOnlyTests.swift in Sources */, - 5680521B2013295700E87861 /* RecordBoxTests.swift in Sources */, 562EA82D1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, F3BA80C61CFB2FD8003DC1BA /* DatabaseQueueConcurrencyTests.swift in Sources */, - F3BA81161CFB305E003DC1BA /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + F3BA81161CFB305E003DC1BA /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA80F41CFB301D003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */, - F3BA81181CFB305E003DC1BA /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + F3BA81181CFB305E003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA810A1CFB3056003DC1BA /* FoundationNSDateTests.swift in Sources */, 5657AB4D1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 5627564A1E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, @@ -1819,22 +1945,27 @@ 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 */, + 56EA63CA209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */, F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */, 562393371DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 5674A7161F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, - 56B021D01D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021D01D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 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 /* MutablePersistableTests.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 /* PersistableTests.swift in Sources */, + F3BA80D21CFB2FF3003DC1BA /* PersistableRecordTests.swift in Sources */, 5698AC501DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, F3BA80FD1CFB3024003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */, F3BA811F1CFB3063003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, @@ -1852,12 +1983,14 @@ 5698ACBD1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5623931F1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 562393701DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, + 56B6EF61208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */, F3BA81121CFB3059003DC1BA /* DatabaseMigratorTests.swift in Sources */, 56176C801EACCD31000F3F2B /* EncryptionTests.swift in Sources */, - F3BA80EB1CFB3016003DC1BA /* RowConvertibleTests.swift in Sources */, + F3BA80EB1CFB3016003DC1BA /* FetchableRecordTests.swift in Sources */, 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,12 +2001,14 @@ 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 /* RowConvertibleDecodableTests.swift in Sources */, - 56FEE8021F47253700D930EA /* TableMappingTests.swift in Sources */, + 5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, + 56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */, F3BA81211CFB3063003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */, F3BA80F71CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, 56F3E7501E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, @@ -1882,8 +2017,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 +2028,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 */, @@ -1908,16 +2048,16 @@ F3BA81231CFB3063003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */, F3BA80541CFB2B59003DC1BA /* DatabaseRegionTests.swift in Sources */, 567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, - 566A84442041AB2D00E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84442041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */, F3BA810B1CFB3056003DC1BA /* Row+FoundationTests.swift in Sources */, 5698AC901DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, F3BA80DB1CFB300E003DC1BA /* DatabaseValueConversionTests.swift in Sources */, - 56741EAF1E66A8B3003E422D /* RequestTests.swift in Sources */, + 56741EAF1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 5657AB5D1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, F3BA81241CFB3063003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, - 5674A71F1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A71F1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, F3BA80E81CFB3016003DC1BA /* RowFromDictionaryTests.swift in Sources */, 562393671DEE06D300A6B01F /* CursorTests.swift in Sources */, F3BA80B41CFB2FC9003DC1BA /* DatabaseQueueReadOnlyTests.swift in Sources */, @@ -1925,6 +2065,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 */, @@ -1942,19 +2083,23 @@ files = ( 56873BEE1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D3F1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, - 5636E9BE1D22574100B9B05F /* Request.swift in Sources */, + 5616AAF6207CD59400AC3664 /* RequestProtocols.swift in Sources */, + 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */, 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 /* RowConvertible.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 */, @@ -1970,26 +2115,28 @@ F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */, 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */, 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */, - 569B7FA4201C90430069DE70 /* Swift4.1.swift in Sources */, - 5674A6F51F307F600095F066 /* Persistable+Encodable.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 */, F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */, 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */, - F3BA808B1CFB2E70003DC1BA /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + F3BA808B1CFB2E70003DC1BA /* QueryInterfaceQuery.swift in Sources */, 56CEB5031EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55C1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */, 56A8C2321D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D311DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, - 56D51D021EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */, + 5656BF5A20C7247100F98521 /* QueryOrdering.swift in Sources */, + 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80711CFB2E55003DC1BA /* DatabaseWriter.swift in Sources */, F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */, 566475BC1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, @@ -2003,6 +2150,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 */, @@ -2010,25 +2158,29 @@ 56FC987A1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */, - F3BA808F1CFB2E7A003DC1BA /* Persistable.swift in Sources */, + F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */, 56BF6D381DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, 56CEB51B1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A6FC1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, + 5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5698AC7A1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 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 */, - F3BA80921CFB2E7A003DC1BA /* TableMapping.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, - 568052092013207000E87861 /* RecordBox.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 */, @@ -2047,15 +2199,15 @@ 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 */, 5698ACCB1DA62A2D0056AF8C /* FTS5TokenizerTests.swift in Sources */, 56B14E821D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, - 5680521A2013295600E87861 /* RecordBoxTests.swift in Sources */, 562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, - 56B021CC1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021CC1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 561667041D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, F3BA80E31CFB300F003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 566AD8C91D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */, @@ -2066,26 +2218,30 @@ 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 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + 56EA63C9209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */, + F3BA811D1CFB305F003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA80AD1CFB2FA6003DC1BA /* DataMemoryTests.swift in Sources */, 5698ACB91DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5674A7141F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 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 */, - F3BA80D31CFB2FF4003DC1BA /* MutablePersistableTests.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 /* PersistableTests.swift in Sources */, + F3BA80D41CFB2FF4003DC1BA /* PersistableRecordTests.swift in Sources */, 6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, F3BA80FF1CFB3025003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */, 5698AC4C1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, F3BA80EF1CFB3017003DC1BA /* RowFromStatementTests.swift in Sources */, - 562393481DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 5657AB511D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, 56CC9254201E094600CB597E /* PrefixCursorTests.swift in Sources */, 562393331DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, @@ -2100,28 +2256,32 @@ 5657AB411D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56B964C61DA521450002DA19 /* FTS5PatternTests.swift in Sources */, 562205FA1E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, + 56B6EF60208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */, 562205FD1E420EA2005860AC /* DatabasePoolBackupTests.swift in Sources */, 562206091E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, 56176C7E1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */, 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 */, 5698AC8C1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */, F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, - 56FF45431D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, - F3BA80F01CFB3017003DC1BA /* RowConvertibleTests.swift in Sources */, + 56FF45431D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 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 /* RowConvertibleDecodableTests.swift in Sources */, - 56FEE7FE1F47253700D930EA /* TableMappingTests.swift in Sources */, + 5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, + 56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */, F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */, F3BA812F1CFB3064003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */, 5690C33A1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, @@ -2130,8 +2290,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 +2301,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 */, @@ -2156,23 +2321,24 @@ 565EFAF11D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, F3BA812E1CFB3064003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */, F3BA81021CFB3032003DC1BA /* CGFloatTests.swift in Sources */, - 566A84432041AB2D00E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84432041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, F3BA81131CFB305B003DC1BA /* DatabaseMigratorTests.swift in Sources */, F3BA81381CFB3064003DC1BA /* RecordSubClassTests.swift in Sources */, F3BA81351CFB3064003DC1BA /* RecordEditedTests.swift in Sources */, 568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 5657AB691D108BA9006283EF /* FoundationURLTests.swift in Sources */, - 56741EAB1E66A8B3003E422D /* RequestTests.swift in Sources */, + 56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */, - 5674A71D1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A71D1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 562393511DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, F3BA812D1CFB3064003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 5698AC831DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, - F3BA811B1CFB305F003DC1BA /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + F3BA811B1CFB305F003DC1BA /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 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 */, @@ -2305,7 +2471,6 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 4.0; VALIDATE_PRODUCT = YES; @@ -2362,7 +2527,6 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -2400,7 +2564,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCustomSQLite.GRDBCustomSQLiteiOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2449,7 +2612,6 @@ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2488,7 +2650,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCustomSQLiteOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; diff --git a/Makefile b/Makefile index 847fc35ac..560b77bba 100644 --- a/Makefile +++ b/Makefile @@ -44,26 +44,15 @@ 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) +ifeq ($(XCODEVERSION),9.4) + MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.4" + MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=9.0" +else 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/Package.swift b/Package.swift index af21e70db..76aa827c5 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:4.0 +// swift-tools-version:4.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription diff --git a/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift new file mode 100644 index 000000000..2b1a387ba --- /dev/null +++ b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift @@ -0,0 +1,456 @@ +//: # Customized Decoding of Database Rows +//: +//: To run this playground: +//: +//: - Open GRDB.xcworkspace +//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX +//: - Build: menu Product > Build +//: - Select the playground in the Playgrounds Group +//: - Run the playground + +import GRDB + +//: This playground demonstrates how one can implement **customized decoding of +//: database rows**. +//: +//: Customized row decoding allows you to go beyong the built-in support for +//: requests of raw rows, values, or types that adopt the +//: FetchableRecord protocol. +//: +//: For example: +//: +//: - Your application needs polymorphic row decoding: it decodes some class or +//: another, depending on the values contained in a database row. +//: +//: - Your application needs to decode rows with a context: each decoded value +//: should be initialized with some extra value that does not come from +//: the database. +//: +//: - Your application needs a record type that supports untrusted databases, +//: and may fail at decoding database rows (throw an error when a row contains +//: invalid values). +//: +//: None of those use cases can be handled by the built-in `FetchableRecord` +//: protocol and its `init(row:)` initializer. They need *customized +//: row decoding*. +//: +//: ## An Example: Polymorphic Decoding +//: +//: In this playground, we will provide some sample code that performs +//: polymorphic row decoding. Given a base class, `Base`, and two subclasses +//: `Foo` and `Bar`, we'd like to fetch Foo or Bar instances, depending on the +//: value found in the `type` column of the `base` database table. +//: +//: From this sample code, we hope that you will be able to derive your own +//: customized decoding. +//: +//: Everything starts from our class hierarchy: + +class Base { + var description: String { return "Base" } + init() { } +} + +class Foo: Base { + var name: String + override var description: String { return "Foo: \(name)" } + init(name: String) { + self.name = name + super.init() + } +} + +class Bar: Base { + var score: Int + override var description: String { return "Bar: \(score)" } + init(score: Int) { + self.score = score + super.init() + } +} + +//: We need a database, a table, and a few values so that we can do a real demo: + +// An in-memory database is good enough +let dbQueue = DatabaseQueue() + +try dbQueue.write { db in + // Database table + try db.create(table: "base") { t in + t.column("type", .text).notNull() // Contains "Foo" or "Bar" + t.column("fooName", .text) // Contains a Foo's name + t.column("barScore", .integer) // Contains a Bar's score + } + + // Demo values: two Foo and one Bar + try db.execute(""" + INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?); + INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?); + INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?); + """, arguments: [ + "Foo", "Arthur", nil, + "Bar", nil, 100, + "Foo", "Barbara", nil, + ]) +} + +//: We also need a method that decodes database rows into `Foo` or `Bar` +//: instances: let's call it `Base.decode(row:)`: + +extension Base { + static func decode(row: Row) -> Base { + switch row["type"] as String { + case "Foo": + return Foo(name: row["fooName"]) + case "Bar": + return Bar(score: row["barScore"]) + case let type: + fatalError("Unknown Base type: \(type)") + } + } +} + +//: Now we are able to express the kind of request we'd like to write. For +//: example, we could fetch all Base values from the database: +//: +//: try dbQueue.read { db in +//: // An array [Base] that constains Foo and Bar instances +//: let bases = try Base.fetchAll(db) +//: } +//: +//: But so far, we have a compiler error: + +// Compiler error: Type 'Base' has no member 'fetchAll' +//try dbQueue.read { db in +// let bases = try Base.fetchAll(db) +//} + +//: We'll see that this goal can be achieved by declaring a protocol, writing a +//: few extensions that guarantee the most efficient use of GRDB, and have the +//: Base class adopt this protocol. +//: +//: ### Keep It Simple, Stupid! +//: +//: But first, let's see how polymorphic decoding can be done as simply as +//: possible. After all, it is useless to design a full-fledged protocol unless +//: we need to use this protocol several times, or write code that is as +//: streamlined as possible. +//: +//: Can we fetch Foo and Bar values from an SQL request? Sure: + +try dbQueue.read { db in + print("> KISS: Fetch from SQL") + let rows = try Row.fetchAll(db, "SELECT * FROM base") // Fetch database rows + let bases = rows.map { row in // Decode database rows + Base.decode(row: row) + } + for base in bases { // Use fetched values + print(base.description) + } +} + +//: Can we have GRDB generate SQL for us? Sure, we just need to adopt the +//: `TableRecord` protocol: + +extension Base: TableRecord { + static let databaseTableName = "base" +} + +try dbQueue.read { db in + print("> KISS: Fetch from query interface request") + let request = Base.filter(Column("type") == "Foo") // Define a request + let rows = try Row.fetchAll(db, request) // Fetch database rows + let bases = rows.map { row in // Decode database rows + Base.decode(row: row) + } + for base in bases { // Use fetched values + print(base.description) + } +} + +//: As seen above, we can perform polymorphic requests with the standard GRDB, +//: by fetching raw rows and mapping them through a decoding method. +//: +//: The resulting code is not as streamlined as usual GRDB code, but we could +//: already do what we needed without much effort. +//: +//: ### Custom Protocol: MyDatabaseDecoder +//: +//: In the rest of this playground, we will define a **new realm of requests**. +//: +//: GRDB ships with three built-in realms of requests: requests of raw rows, +//: requests of values, and requests of record types that adopt the +//: `FetchableRecord` protocol. +//: +//: We'll define requests of record types that adopt the custom +//: `MyDatabaseDecoder` protocol: + +protocol MyDatabaseDecoder { + associatedtype DecodedType + static func decode(row: Row) -> DecodedType +} + +//: Types that adopt the MyDatabaseDecoder protocol are able, among other +//: things, to perform polymorphic decoding. Our Base class, for example: + +extension Base: MyDatabaseDecoder { + // Already declared above: + // static func decode(row: Row) -> Base { ... } +} + +//: Now let's see how we can define a new realm of requests based on the +//: `MyDatabaseDecoder` protocol. Our goal is to make them just as powerful as +//: ready-made requests of rows, values and FetchableRecord. +//: +//: All we need is a set of *extensions* that define the classic GRDB fetching +//: methods: `fetchOne`, `fetchAll`, and `fetchCursor`. The most fundamental one +//: is `fetchCursor`, because from it we can derive the two others. +//: +//: The first extension is the most low-level one: fetching from SQLite +//: **prepared statement**: +//: +//: try dbQueue.read { db in +//: let statement = try db.makeSelectStatement("SELECT ...") +//: try Base.fetchCursor(statement) // Cursor of Base +//: try Base.fetchAll(statement) // [Base] +//: try Base.fetchOne(statement) // Base? +//: } + +extension MyDatabaseDecoder { + // SelectStatement, StatementArguments, and RowAdapter are the fundamental + // fetching parameters of GRDB. Make sure to accept them all: + static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor { + // Turn the cursor of raw rows into a cursor of decoded rows + return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map { + self.decode(row: $0) + } + } + + static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] { + // Turn the cursor into an Array + return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) + } + + static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? { + // Consume the first value of the cursor + return try fetchCursor(statement, arguments: arguments, adapter: adapter).next() + } +} + +try dbQueue.read { db in + print("> Fetch from prepared statement") + let statement = try db.makeSelectStatement("SELECT * FROM base") + let bases = try Base.fetchAll(statement) + for base in bases { + print(base.description) + } +} + +//: Now that we can fetch from prepared statements, we can fetch when given a +//: **request**, as defined by the `FetchRequest` protocol. This is the +//: protocol for query interface requests such as `Base.all()`, or +//: `SQLRequest`, etc. +//: +//: try dbQueue.read { db in +//: let request = Base.all() +//: try Base.fetchCursor(db, request) // Cursor of Base +//: try Base.fetchAll(db, request) // [Base] +//: try Base.fetchOne(db, request) // Base? +//: } +extension MyDatabaseDecoder { + static func fetchCursor(_ db: Database, _ request: R) throws -> MapCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + static func fetchAll(_ db: Database, _ request: R) throws -> [DecodedType] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } + + static func fetchOne(_ db: Database, _ request: R) throws -> DecodedType? { + let (statement, adapter) = try request.prepare(db) + return try fetchOne(statement, adapter: adapter) + } +} + +try dbQueue.read { db in + print("> Fetch given a request") + let request = Base.all() + let bases = try Base.fetchAll(db, request) + for base in bases { + print(base.description) + } +} + +//: When it's fine to fetch given a request, it's even better when requests can +//: fetch, too: +//: +//: try dbQueue.read { db in +//: let request = Base.all() +//: try request.fetchCursor(db) // Cursor of Base +//: try request.fetchAll(db) // [Base] +//: try request.fetchOne(db) // Base? +//: } +extension FetchRequest where RowDecoder: MyDatabaseDecoder { + func fetchCursor(_ db: Database) throws -> MapCursor { + return try RowDecoder.fetchCursor(db, self) + } + + func fetchAll(_ db: Database) throws -> [RowDecoder.DecodedType] { + return try RowDecoder.fetchAll(db, self) + } + + func fetchOne(_ db: Database) throws -> RowDecoder.DecodedType? { + return try RowDecoder.fetchOne(db, self) + } +} + +try dbQueue.read { db in + print("> Fetch from request") + let request = Base.all() + let bases = try request.fetchAll(db) + for base in bases { + print(base.description) + } +} + +//: Types that adopt both FetchableRecord and TableRecord are able to fetch +//: right from the base type. Let's allow this as well for MyDatabaseDecoder: +//: +//: try dbQueue.read { db in +//: try Base.fetchCursor(db) // Cursor of Base +//: try Base.fetchAll(db) // [Base] +//: try Base.fetchOne(db) // Base? +//: } +extension MyDatabaseDecoder where Self: TableRecord { + static func fetchCursor(_ db: Database) throws -> MapCursor { + return try all().fetchCursor(db) + } + + static func fetchAll(_ db: Database) throws -> [DecodedType] { + return try all().fetchAll(db) + } + + static func fetchOne(_ db: Database) throws -> DecodedType? { + return try all().fetchOne(db) + } +} + +try dbQueue.read { db in + print("> Fetch from base type") + let bases = try Base.fetchAll(db) + for base in bases { + print(base.description) + } +} + +//: Finally, you don't have a true GRDB record unless it allows fetching from +//: raw SQL: +//: +//: try dbQueue.read { db in +//: try Base.fetchCursor(db, "SELECT ...") // Cursor of Base +//: try Base.fetchAll(db, "SELECT ...") // [Base] +//: try Base.fetchOne(db, "SELECT ...") // Base? +//: } +extension MyDatabaseDecoder { + static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor { + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + } + + static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] { + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + } + + static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? { + return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + } +} + +try dbQueue.read { db in + print("> Fetch from SQL") + let bases = try Base.fetchAll(db, "SELECT * FROM base") + for base in bases { + print(base.description) + } +} + +//: Voilà! Our `MyDatabaseDecoder` protocol is now as able as the built-in +//: `FetchableRecord` protocol. +//: +//: To sum up, you have learned: +//: +//: - how to keep things simple: as long as you can fetch rows, you can decode +//: them the way you want. +//: - how to define a whole new realm of requests based on a custom protocol. +//: This involves writing a few extensions that give your protocol the same +//: fluent interface that is ready-made for the built-in FetchableRecord +//: protocol. This is more work, but you are granted with the full +//: customization freedom. +//: +//: To end this tour, let's quickly look at two other possible customized +//: row decoding strategies. +//: +//: ## An Example: Contextualized Records +//: +//: Your application needs to decode rows with a context: each decoded value +//: should be initialized with some extra value that does not come from +//: the database. +//: +//: In this case, you may define a `ContextFetchableRecord` protocol, and +//: derive all other fetching methods from the most fundamental one, which +//: fetches a cursor from a prepared statement (as we did for the +//: MyDatabaseDecoder protocol, above): + +protocol ContextFetchableRecord { + associatedtype Context + init(row: Row, context: Context) +} + +extension ContextFetchableRecord { + static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil, + context: Context) + throws -> MapCursor + { + // Turn the cursor of raw rows into a cursor of decoded rows + return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map { + self.init(row: $0, context: context) + } + } + + // Define fetchAll, fetchOne, and other extensions... +} + +//: ## An Example: Failable Records +//: +//: Your application needs a record type that supports untrusted databases, +//: and may fail at decoding database rows (throw an error when a row contains +//: invalid values). +//: +//: In this case, you may define a `FailableFetchableRecord` protocol, and +//: derive all other fetching methods from the most fundamental one, which +//: fetches a cursor from a prepared statement (as we did for the +//: MyDatabaseDecoder protocol, above): + +protocol FailableFetchableRecord { + init(row: Row) throws +} + +extension FailableFetchableRecord { + static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> MapCursor + { + // Turn the cursor of raw rows into a cursor of decoded rows + return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map { + try self.init(row: $0) + } + } + + // Define fetchAll, fetchOne, and other extensions... +} diff --git a/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/contents.xcplayground b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/contents.xcplayground new file mode 100644 index 000000000..3a493ef23 --- /dev/null +++ b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Playgrounds/Issue156.playground/Contents.swift b/Playgrounds/Issue156.playground/Contents.swift index f07131dcf..60c89dbc7 100644 --- a/Playgrounds/Issue156.playground/Contents.swift +++ b/Playgrounds/Issue156.playground/Contents.swift @@ -76,7 +76,7 @@ class TestDeleteAll: NSObject { } -struct MyRecord: RowConvertible, TableMapping, Persistable { +struct MyRecord: FetchableRecord, TableRecord, PersistableRecord { static let MyColumn = Column("MyColumn") static var databaseTableName: String { return String(describing: self) } diff --git a/Playgrounds/JSONSynchronization.playground/Contents.swift b/Playgrounds/JSONSynchronization.playground/Contents.swift index fb3b7eef2..0a3184746 100644 --- a/Playgrounds/JSONSynchronization.playground/Contents.swift +++ b/Playgrounds/JSONSynchronization.playground/Contents.swift @@ -1,11 +1,17 @@ -// To run this playground, select and build the GRDBOSX scheme. -// -// This sample code shows how to use GRDB to synchronize a database table -// with a JSON payload. We use as few SQL queries as possible: -// -// - Only one SELECT query. -// - One query per insert, delete, and update. -// - Useless UPDATE statements are avoided. +//: To run this playground: +//: +//: - Open GRDB.xcworkspace +//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX +//: - Build: menu Product > Build +//: - Select the playground in the Playgrounds Group +//: - Run the playground +//: +//: This sample code shows how to use GRDB to synchronize a database table +//: with a JSON payload. We use as few SQL queries as possible: +//: +//: - Only one SELECT query. +//: - One query per insert, delete, and update. +//: - Useless UPDATE statements are avoided. import Foundation import GRDB @@ -31,7 +37,7 @@ try dbQueue.inDatabase { db in // Define the Player subclass of GRDB's Record. // -// Record provides change tracking that helps avoiding useless UPDATE statements. +// Record can compare against itself, and that helps avoiding useless UPDATE statements. class Player : Record { var id: Int64 var name: String diff --git a/Playgrounds/JSONSynchronization.playground/contents.xcplayground b/Playgrounds/JSONSynchronization.playground/contents.xcplayground index 16f9952aa..dd3ff35de 100644 --- a/Playgrounds/JSONSynchronization.playground/contents.xcplayground +++ b/Playgrounds/JSONSynchronization.playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/Playgrounds/Record.playground/Contents.swift b/Playgrounds/Record.playground/Contents.swift index 258191d82..bb8ad7265 100644 --- a/Playgrounds/Record.playground/Contents.swift +++ b/Playgrounds/Record.playground/Contents.swift @@ -1,4 +1,10 @@ -//: To run this playground, select and build the GRDBOSX scheme. +//: To run this playground: +//: +//: - Open GRDB.xcworkspace +//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX +//: - Build: menu Product > Build +//: - Select the playground in the Playgrounds Group +//: - Run the playground //: //: Record //: ====== diff --git a/Playgrounds/Record.playground/contents.xcplayground b/Playgrounds/Record.playground/contents.xcplayground index 3de2b51ba..fd676d5b4 100644 --- a/Playgrounds/Record.playground/contents.xcplayground +++ b/Playgrounds/Record.playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/Playgrounds/Tour.playground/Contents.swift b/Playgrounds/Tour.playground/Contents.swift index defcf6d6f..a87fe0aff 100644 --- a/Playgrounds/Tour.playground/Contents.swift +++ b/Playgrounds/Tour.playground/Contents.swift @@ -1,4 +1,10 @@ -//: To run this playground, select and build the GRDBOSX scheme. +//: To run this playground: +//: +//: - Open GRDB.xcworkspace +//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX +//: - Build: menu Product > Build +//: - Select the playground in the Playgrounds Group +//: - Run the playground //: //: Tour //: ====== @@ -64,8 +70,8 @@ struct PointOfInterest { var coordinate: CLLocationCoordinate2D } -// Adopt RowConvertible -extension PointOfInterest : RowConvertible { +// Adopt FetchableRecord +extension PointOfInterest : FetchableRecord { init(row: Row) { id = row["id"] title = row["title"] @@ -76,13 +82,13 @@ extension PointOfInterest : RowConvertible { } } -// Adopt TableMapping -extension PointOfInterest : TableMapping { +// Adopt TableRecord +extension PointOfInterest : TableRecord { static let databaseTableName = "pointOfInterests" } -// Adopt MutablePersistable -extension PointOfInterest : MutablePersistable { +// Adopt MutablePersistableRecord +extension PointOfInterest : MutablePersistableRecord { func encode(to container: inout PersistenceContainer) { container["id"] = id container["title"] = title diff --git a/Playgrounds/Tour.playground/contents.xcplayground b/Playgrounds/Tour.playground/contents.xcplayground index 3de2b51ba..fd676d5b4 100644 --- a/Playgrounds/Tour.playground/contents.xcplayground +++ b/Playgrounds/Tour.playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/Playgrounds/TransactionObserver.playground/Contents.swift b/Playgrounds/TransactionObserver.playground/Contents.swift index 9a151b925..05553a55e 100644 --- a/Playgrounds/TransactionObserver.playground/Contents.swift +++ b/Playgrounds/TransactionObserver.playground/Contents.swift @@ -1,13 +1,17 @@ -// To run this playground, select and build the GRDBOSX scheme. +//: To run this playground: +//: +//: - Open GRDB.xcworkspace +//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX +//: - Build: menu Product > Build +//: - Select the playground in the Playgrounds Group +//: - Run the playground import GRDB // Create the databsae -var configuration = Configuration() -configuration.trace = { print($0) } -let dbQueue = DatabaseQueue(configuration: configuration) // Memory database +let dbQueue = DatabaseQueue() // Memory database var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute( @@ -80,6 +84,7 @@ try dbQueue.inTransaction { db in print("-- Changes 3") -try dbQueue.inDatabase { db in +try dbQueue.write { db in try db.execute("DELETE FROM persons") + try db.execute("DELETE FROM pets") } diff --git a/Playgrounds/TransactionObserver.playground/contents.xcplayground b/Playgrounds/TransactionObserver.playground/contents.xcplayground index 06828af92..3de2b51ba 100644 --- a/Playgrounds/TransactionObserver.playground/contents.xcplayground +++ b/Playgrounds/TransactionObserver.playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/README.md b/README.md index e884f1812..a4afe6a7c 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) +**Latest release**: March 30, 2018 • version 3.0.0-beta.1 • [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.1+ / Xcode 9.3+ | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | -| **Swift 4+** | **v2.10.0** | +| **Swift 4.1** | **v3.0.0-beta.1** | +| 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) | @@ -25,12 +26,9 @@ GRDB provides raw access to SQL and advanced SQLite features, because one someti Compared to [SQLite.swift](http://github.com/stephencelis/SQLite.swift) or [FMDB](http://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications. -It comes with [up-to-date documentation](#documentation), [general articles](https://medium.com/@gwendal.roue), [sample code](#sample-code), and a lot of interesting resolved issues that may answer your eventual [questions](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion) and foster [best practices](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22). +It comes with [up-to-date documentation](#documentation), [general guides](#general-guides--good-practices), and it is [fast](https://github.com/groue/GRDB.swift/wiki/Performance). -For more information, check out: - -- [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) The reasons why GRDB could become your favorite database library. -- [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) The architecture of a GRDB-powered application. +See [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) if you are looking for your favorite database library. --- @@ -65,15 +63,11 @@ Companion libraries that enhance and extend GRDB: - [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): track database changes in a reactive way, with [RxSwift](https://github.com/ReactiveX/RxSwift). - [GRDBObjc](https://github.com/groue/GRDBObjc): FMDB-compatible bindings to GRDB. -More than a set of tools that leverage SQLite abilities, GRDB is also: - -- **Safer**: read the blog post [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e) -- **Faster**: see [Comparing the Performances of Swift SQLite libraries](https://github.com/groue/GRDB.swift/wiki/Performance) for a comparison between raw SQLite, FMDB, SQLite.swift, Core Data, Realm, and GRDB. - ## Usage -Open a [connection](#database-connections) to the database: +
+ Connect to an SQLite database ```swift import GRDB @@ -84,14 +78,19 @@ let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") // Enhanced multithreading based on SQLite's WAL mode let dbPool = try DatabasePool(path: "/path/to/database.sqlite") ``` + +See [Database Connections](#database-connections) -[Execute SQL statements](#executing-updates): +
+ +
+ Execute SQL statements ```swift -try dbQueue.inDatabase { db in +try dbQueue.write { db in try db.execute(""" - CREATE TABLE places ( - id INTEGER PRIMARY KEY, + CREATE TABLE place ( + id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, favorite BOOLEAN NOT NULL DEFAULT 0, latitude DOUBLE NOT NULL, @@ -99,7 +98,7 @@ try dbQueue.inDatabase { 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]) @@ -107,11 +106,17 @@ try dbQueue.inDatabase { db in } ``` -[Fetch database rows and values](#fetch-queries): +See [Executing Updates](#executing-updates) + +
+ +
+ Fetch database rows and values ```swift -try dbQueue.inDatabase { db in - let rows = try Row.fetchCursor(db, "SELECT * FROM places") +try dbQueue.read { db in + // Fetch database rows + 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"] @@ -119,18 +124,23 @@ try dbQueue.inDatabase { db in latitude: row["latitude"], longitude: row["longitude"]) } - - let placeCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM places")! // Int - let placeTitles = try String.fetchAll(db, "SELECT title FROM places") // [String] + + // Fetch values + let placeCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM place")! // Int + let placeTitles = try String.fetchAll(db, "SELECT title FROM place") // [String] } -// Extraction -let placeCount = try dbQueue.inDatabase { db in - try Int.fetchOne(db, "SELECT COUNT(*) FROM places")! +let placeCount = try dbQueue.read { db in + try Int.fetchOne(db, "SELECT COUNT(*) FROM place")! } ``` -Insert and fetch [records](#records): +See [Fetch Queries](#fetch-queries) + +
+ +
+ Store custom models aka "records" ```swift struct Place { @@ -143,7 +153,16 @@ struct Place { // snip: turn Place into a "record" by adopting the protocols that // provide fetching and persistence methods. -try dbQueue.inDatabase { db in +try dbQueue.write { db in + // Create database table + try db.create(table: "place") { t in + t.autoIncrementedPrimaryKey("id") + t.column("title", .text).notNull() + t.column("favorite", .boolean).notNull().defaults(to: false) + t.column("longitude", .double).notNull() + t.column("latitude", .double).notNull() + } + var berlin = Place( id: nil, title: "Berlin", @@ -155,65 +174,92 @@ try dbQueue.inDatabase { db in berlin.isFavorite = true try berlin.update(db) - - // Fetch [Place] from SQL - let places = try Place.fetchAll(db, "SELECT * FROM places") } ``` -Avoid SQL with the [query interface](#the-query-interface): +See [Records](#records) + +
+ +
+ Fetch records and values with the Swift query interface ```swift -try dbQueue.inDatabase { db in - try db.create(table: "places") { t in - t.column("id", .integer).primaryKey() - t.column("title", .text).notNull() - t.column("favorite", .boolean).notNull().defaults(to: false) - t.column("longitude", .double).notNull() - t.column("latitude", .double).notNull() - } - +try dbQueue.write { db in // Place? let paris = try Place.fetchOne(db, key: 1) // Place? - let titleColumn = Column("title") - let berlin = try Place.filter(titleColumn == "Berlin").fetchOne(db) + let berlin = try Place.filter(Column("title") == "Berlin").fetchOne(db) // [Place] - let favoriteColumn = Column("favorite") let favoritePlaces = try Place - .filter(favoriteColumn) - .order(titleColumn) + .filter(Column("favorite") == true) + .order(Column("title")) .fetchAll(db) + + // Int + let favoriteCount = try Place.filter(Column("favorite")).fetchCount(db) + + // SQL is always welcome + let places = try Place.fetchAll(db, "SELECT * FROM place") } ``` +See the [Query Interface](#the-query-interface) + +
+ +
+ Be notified of database changes + +```swift +// Track query interface requests +Place.filter(key: 1) + .rx + .fetchOne(in: dbQueue) + .subscribe(onNext: { place: Place? in + print("Place 1 has changed") + }) + +// Track SQL requests +SQLRequest("SELECT * FROM place WHERE favorite ORDER BY title") + .rx + .fetchAll(in: dbQueue) + .subscribe(onNext: { places: [Place] in + print("Favorite places have changed") + }) +``` + +See [Database Changes Observation](#database-changes-observation), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) + +
+ Documentation ============= **GRDB runs on top of SQLite**: you should get familiar with the [SQLite FAQ](http://www.sqlite.org/faq.html). For general and detailed information, jump to the [SQLite Documentation](http://www.sqlite.org/docs.html). -**Reference** +#### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/2.10/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) -**Getting Started** +#### Getting Started - [Installation](#installation) - [Database Connections](#database-connections): Connect to SQLite databases -**SQLite and SQL** +#### SQLite and SQL - [SQLite API](#sqlite-api): The low-level SQLite API • [executing updates](#executing-updates) • [fetch queries](#fetch-queries) -**Records and the Query Interface** +#### Records and the Query Interface - [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies. - [Query Interface](#the-query-interface): A swift way to generate SQL • [table creation](#database-schema) • [requests](#requests) -**Application Tools** +#### Application Tools - [Migrations](#migrations): Transform your database as your application evolves. - [Full-Text Search](#full-text-search): Perform efficient and customizable full-text searches. @@ -223,7 +269,7 @@ Documentation - [Encryption](#encryption): Encrypt your database with SQLCipher. - [Backup](#backup): Dump the content of a database to another. -**Good to Know** +#### Good to Know - [Avoiding SQL Injection](#avoiding-sql-injection) - [Error Handling](#error-handling) @@ -233,9 +279,21 @@ Documentation - [Concurrency](#concurrency) - [Performance](#performance) -[FAQ](#faq) +#### General Guides & Good Practices -[Sample Code](#sample-code) +- :bulb: [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) +- :bulb: [Migrating From GRDB 2 to GRDB 3](Documentation/GRDB2MigrationGuide.md) +- :bulb: [Issues tagged "best practices"](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22) +- :question: [Issues tagged "question"](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion) +- :blue_book: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) +- :blue_book: [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) +- :blue_book: [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e) +- :blue_book: [Unexpected SQLite with Swift](https://hackernoon.com/unexpected-sqlite-with-swift-ddc6343bcbfc) + + +**[FAQ](#faq)** + +**[Sample Code](#sample-code)** Installation @@ -265,7 +323,7 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di ```swift let package = Package( dependencies: [ - .package(url: "https://github.com/groue/GRDB.swift.git", from: "2.10.0") + .package(url: "https://github.com/groue/GRDB.swift.git", from: "3.0.0-beta.1") ] ) ``` @@ -282,7 +340,7 @@ If you decide to use Carthage despite this warning, and get any Carthage-related ## Manually -1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.10.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.10.0` command. +1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v3.0.0-beta.1) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v3.0.0-beta.1` command. 2. Embed the `GRDB.xcodeproj` project in your own project. @@ -309,7 +367,7 @@ let dbPool = try DatabasePool(path: "/path/to/database.sqlite") The differences are: - Database pools allow concurrent database accesses (this can improve the performance of multithreaded applications). -- Unless read-only, database pools open your SQLite database in the [WAL mode](https://www.sqlite.org/wal.html). +- Database pools open your SQLite database in the [WAL mode](https://www.sqlite.org/wal.html) (unless read-only). - Database queues support [in-memory databases](https://www.sqlite.org/inmemorydb.html). **If you are not sure, choose DatabaseQueue.** You will always be able to switch to DatabasePool later. @@ -331,40 +389,46 @@ let inMemoryDBQueue = DatabaseQueue() SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated. - -**A database queue can be used from any thread.** The `inDatabase` and `inTransaction` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue. They safely serialize the database accesses: +**A database queue can be used from any thread.** The `write` and `read` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue: ```swift -// Execute database statements: -try dbQueue.inDatabase { db in - try db.create(table: "places") { ... } +// Modify the database: +try dbQueue.write { db in + try db.create(table: "place") { ... } try Place(...).insert(db) } -// Wrap database statements in a transaction: -try dbQueue.inTransaction { db in - if let place = try Place.fetchOne(db, key: 1) { - try place.delete(db) - } - return .commit -} - // Read values: -try dbQueue.inDatabase { db in +try dbQueue.read { db in let places = try Place.fetchAll(db) let placeCount = try Place.fetchCount(db) } +``` -// Extract a value from the database: -let placeCount = try dbQueue.inDatabase { db in +Database access methods can return values: + +```swift +let placeCount = try dbQueue.read { db in try Place.fetchCount(db) } + +let newPlaceCount = try dbQueue.write { db -> Int in + try Place(...).insert(db) + return try Place.fetchCount(db) +} ``` **A database queue needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency](#concurrency) chapter. See [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift) for a sample code that sets up a database queue on iOS. +> :muscle: **Note to database experts**: The `write` and `read` database access methods generally help enforcing the [GRDB concurrency guarantees](#concurrency), and are highly recommended, even for skilled developers, because they lift most of the mental burden related to explicit SQLite transactions: +> +> - `DatabaseQueue.write` wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, the whole transaction is rollbacked, and the error is rethrown. +> - `DatabaseQueue.read` does not open any transaction, but enforces read-only access. +> +> When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints). + ### DatabaseQueue Configuration @@ -379,14 +443,12 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/2.10/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/Configuration.html) for more details. ## Database Pools -**A Database Pool allows concurrent database accesses.** - -When more efficient than [database queues](#database-queues), database pools also inherit the subtleties of SQLite's [WAL mode](https://www.sqlite.org/wal.html). If you don't feel comfortable with improving your SQLite skills, use a [database queue](#database-queues) instead. +**A database pool allows concurrent database accesses.** ```swift import GRDB @@ -397,55 +459,59 @@ SQLite creates the database file if it does not already exist. The connection is > :point_up: **Note**: unless read-only, a database pool opens your database in the SQLite "WAL mode". The WAL mode does not fit all situations. Please have a look at https://www.sqlite.org/wal.html. - -**A database pool can be used from any thread.** The `read`, `write` and `writeInTransaction` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue. They safely isolate the database accesses: +**A database pool can be used from any thread.** The `write` and `read` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue: ```swift -// Execute database statements: +// Modify the database: try dbPool.write { db in - try db.create(table: "places") { ... } + try db.create(table: "place") { ... } try Place(...).insert(db) } -// Wrap database statements in a transaction: -try dbPool.writeInTransaction { db in - if let place = try Place.fetchOne(db, key: 1) { - try place.delete(db) - } - return .commit -} - // Read values: try dbPool.read { db in let places = try Place.fetchAll(db) let placeCount = try Place.fetchCount(db) } +``` -// Extract a value from the database: +Database access methods can return values: + +```swift let placeCount = try dbPool.read { db in try Place.fetchCount(db) } + +let newPlaceCount = try dbPool.write { db -> Int in + try Place(...).insert(db) + return try Place.fetchCount(db) +} ``` -Database pools allow several threads to access the database at the same time: +**A database pool needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency](#concurrency) chapter. + +For a sample code that sets up a database pool on iOS, see [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift), and replace DatabaseQueue with DatabasePool. + + +### Database Pool Concurrency + +Unlike [database queues](#database-queues), pools allow several threads to access the database at the same time: - When you don't need to modify the database, prefer the `read` method, because several threads can perform reads in parallel. Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured](#databasepool-configuration). +- Reads are guaranteed an immutable view of the last committed state of the database, regardless of concurrent writes. This kind of isolation is called [snapshot isolation](https://sqlite.org/isolation.html). + - Unlike reads, writes are serialized. There is never more than a single thread that is writing into the database. + +- The `write` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, the whole transaction is rollbacked, and the error is rethrown. -- Reads are guaranteed an immutable view of the last committed state of the database, regardless of concurrent writes. This kind of isolation is called "snapshot isolation". - - To provide `read` closures an immutable view of the last executed writing block *as a whole*, use `writeInTransaction` instead of `write`. + When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints) for more information. - Database pools can take [snapshots](#database-snapshots) of the database. -See [Differences between Database Queues and Pools](#differences-between-database-queues-and-pools) before you decide to use a database pool. When you're sure, see [Advanced DatabasePool](#advanced-databasepool) for more DatabasePool hotness. - -**A database pool needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency](#concurrency) chapter. - -For a sample code that sets up a database pool on iOS, see [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift), and replace DatabaseQueue with DatabasePool. +See the [Concurrency](#concurrency) chapter for more details about database pools, how they differ from database queues, and advanced use cases. ### DatabasePool Configuration @@ -462,7 +528,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/2.10/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -483,11 +549,11 @@ SQLite API - [Date and DateComponents](#date-and-datecomponents) - [NSNumber and NSDecimalNumber](#nsnumber-and-nsdecimalnumber) - [Swift enums](#swift-enums) + - [Custom Value Types](#custom-value-types) - [Transactions and Savepoints](#transactions-and-savepoints) Advanced topics: -- [Custom Value Types](#custom-value-types) - [Prepared Statements](#prepared-statements) - [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates) - [Database Schema Introspection](#database-schema-introspection) @@ -502,22 +568,22 @@ Once granted with a [database connection](#database-connections), the `execute` For example: ```swift -try dbQueue.inDatabase { db in +try dbQueue.write { db in try db.execute(""" - CREATE TABLE players ( - id INTEGER PRIMARY KEY, + 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]) } ``` @@ -530,7 +596,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 ``` @@ -551,8 +617,8 @@ let playerId = player.id **Rows** are the raw results of SQL queries: ```swift -try dbQueue.inDatabase { db in - if let row = try Row.fetchOne(db, "SELECT * FROM wines WHERE id = ?", arguments: [1]) { +try dbQueue.read { db in + 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) @@ -564,8 +630,8 @@ try dbQueue.inDatabase { db in **Values** are the Bool, Int, String, Date, Swift enums, etc. stored in row columns: ```swift -try dbQueue.inDatabase { db in - let urls = try URL.fetchCursor(db, "SELECT url FROM wines") +try dbQueue.read { db in + let urls = try URL.fetchCursor(db, "SELECT url FROM wine") while let url = try urls.next() { print(url) } @@ -576,8 +642,8 @@ try dbQueue.inDatabase { db in **Records** are your application objects that can initialize themselves from rows: ```swift -let wines = try dbQueue.inDatabase { db in - try Wine.fetchAll(db, "SELECT * FROM wines") +let wines = try dbQueue.read { db in + try Wine.fetchAll(db, "SELECT * FROM wine") } ``` @@ -623,7 +689,7 @@ try Row.fetchOne(...) // Row? The `fetchAll()` method returns a regular Swift array, that you iterate like all other arrays: ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in // [Player] let players = try Player.fetchAll(db, "SELECT ...") for player in players { @@ -635,7 +701,7 @@ try dbQueue.inDatabase { db in Unlike arrays, cursors returned by `fetchCursor()` load their results step after step: ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in // Cursor of Player let players = try Player.fetchCursor(db, "SELECT ...") while let player = try players.next() { @@ -650,10 +716,12 @@ Both arrays and cursors can iterate over database results. How do you choose one ```swift // Wrong - let cursor = try dbQueue.inDatabase { try Player.fetchCursor($0, ...) } + let cursor = try dbQueue.read { try Player.fetchCursor($0, ...) } + while let player = try players.next() { ... } // OK - let array = try dbQueue.inDatabase { try Player.fetchAll($0, ...) } + let array = try dbQueue.read { try Player.fetchAll($0, ...) } + for player in players { // use player } ``` - **Cursors can be iterated only one time.** Arrays can be iterated many times. @@ -675,29 +743,29 @@ Both arrays and cursors can iterate over database results. How do you choose one If you don't see, or don't care about the difference, use arrays. If you care about memory and performance, use cursors when appropriate. -**All GRDB cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +**All GRDB cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // 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 ``` @@ -718,12 +786,12 @@ let hosts = try Set(cursor) // Set Fetch **cursors** of rows, **arrays**, or **single** rows (see [fetching methods](#fetching-methods)): ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in try Row.fetchCursor(db, "SELECT ...", arguments: ...) // A Cursor of Row 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"] @@ -731,8 +799,8 @@ try dbQueue.inDatabase { db in } } -let rows = try dbQueue.inDatabase { db in - try Row.fetchAll(db, "SELECT * FROM players") +let rows = try dbQueue.read { db in + try Row.fetchAll(db, "SELECT * FROM player") } ``` @@ -740,15 +808,15 @@ 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"]) ``` -See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care: @@ -978,7 +1046,7 @@ See the documentation of [`Dictionary.init(_:uniquingKeysWith:)`](https://develo Instead of rows, you can directly fetch **[values](#values)**. Like rows, fetch them as **cursors**, **arrays**, or **single** values (see [fetching methods](#fetching-methods)). Values are extracted from the leftmost column of the SQL queries: ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in try Int.fetchCursor(db, "SELECT ...", arguments: ...) // A Cursor of Int try Int.fetchAll(db, "SELECT ...", arguments: ...) // [Int] try Int.fetchOne(db, "SELECT ...", arguments: ...) // Int? @@ -988,8 +1056,8 @@ try dbQueue.inDatabase { db in try Optional.fetchAll(db, "SELECT ...", arguments: ...) // [Int?] } -let playerCount = try dbQueue.inDatabase { db in - try Int.fetchOne(db, "SELECT COUNT(*) FROM players")! +let playerCount = try dbQueue.read { db in + try Int.fetchOne(db, "SELECT COUNT(*) FROM player")! } ``` @@ -998,8 +1066,8 @@ let playerCount = try dbQueue.inDatabase { 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] ``` @@ -1019,20 +1087,20 @@ GRDB ships with built-in support for the following value types: - Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol. -Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html): ```swift 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"] @@ -1042,7 +1110,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): @@ -1129,7 +1197,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"] @@ -1164,7 +1232,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" @@ -1184,7 +1252,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 ) ``` @@ -1192,9 +1260,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) @@ -1205,14 +1273,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 ``` @@ -1240,11 +1308,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"] @@ -1263,120 +1331,7 @@ Grape.fromDatabaseValue(row[0]) // nil ``` -## Transactions and Savepoints - -The `DatabaseQueue.inTransaction()` and `DatabasePool.writeInTransaction()` methods open an SQLite transaction and run their closure argument in a protected dispatch queue. They block the current thread until your database statements are executed: - -```swift -try dbQueue.inTransaction { db in - let wine = Wine(color: .red, name: "Pomerol") - try wine.insert(db) - return .commit -} -``` - -If an error is thrown within the transaction body, the transaction is rollbacked and the error is rethrown by the `inTransaction` method. If you return `.rollback` from your closure, the transaction is also rollbacked, but no error is thrown. - -If you want to insert a transaction between other database statements, you can use the Database.inTransaction() function, or even raw SQL statements: - -```swift -try dbQueue.inDatabase { db in // or dbPool.write { db in - ... - try db.inTransaction { - ... - return .commit - } - ... - try db.beginTransaction() - ... - try db.commit() - ... - try db.execute("BEGIN TRANSACTION") - ... - try db.execute("COMMIT") -} -``` - -You can ask a database if a transaction is currently opened: - -```swift -func myCriticalMethod(_ db: Database) throws { - precondition(db.isInsideTransaction, "This method requires a transaction") - try ... -} -``` - -Yet, you have a better option than checking for transactions: critical sections of your application should use savepoints, described below: - -```swift -func myCriticalMethod(_ db: Database) throws { - try db.inSavepoint { - // Here the database is guaranteed to be inside a transaction. - try ... - } -} -``` - - -### Savepoints - -**Statements grouped in a savepoint can be rollbacked without invalidating a whole transaction:** - -```swift -try dbQueue.inTransaction { db in - try db.inSavepoint { - try db.execute("DELETE ...") - try db.execute("INSERT ...") // need to rollback the delete above if this fails - return .commit - } - - // Other savepoints, etc... - return .commit -} -``` - -If an error is thrown within the savepoint body, the savepoint is rollbacked and the error is rethrown by the `inSavepoint` method. If you return `.rollback` from your closure, the body is also rollbacked, but no error is thrown. - -**Unlike transactions, savepoints can be nested.** They implicitly open a transaction if no one was opened when the savepoint begins. As such, they behave just like nested transactions. Yet the database changes are only committed to disk when the outermost savepoint is committed: - -```swift -try dbQueue.inDatabase { db in - try db.inSavepoint { - ... - try db.inSavepoint { - ... - return .commit - } - ... - return .commit // writes changes to disk - } -} -``` - -SQLite savepoints are more than nested transactions, though. For advanced savepoints uses, use [SQL queries](https://www.sqlite.org/lang_savepoint.html). - - -### Transaction Kinds - -SQLite supports [three kinds of transactions](https://www.sqlite.org/lang_transaction.html): deferred (the default), immediate, and exclusive. - -The transaction kind can be changed in the database configuration, or for each transaction: - -```swift -// Set the default transaction kind to IMMEDIATE: -var config = Configuration() -config.defaultTransactionKind = .immediate -let dbQueue = try DatabaseQueue(path: "...", configuration: config) - -// BEGIN IMMEDIATE TRANSACTION ... -dbQueue.inTransaction { db in ... } - -// BEGIN EXCLUSIVE TRANSACTION ... -dbQueue.inTransaction(.exclusive) { db in ... } -``` - - -## Custom Value Types +### Custom Value Types Conversion to and from the database is based on the `DatabaseValueConvertible` protocol: @@ -1397,6 +1352,216 @@ The `databaseValue` property returns [DatabaseValue](#databasevalue), a type tha The `fromDatabaseValue()` factory method returns an instance of your custom type if the database value contains a suitable value. If the database value does not contain a suitable value, such as "foo" for Date, `fromDatabaseValue` *must* return nil (GRDB will interpret this nil result as a conversion error, and react accordingly). +## Transactions and Savepoints + +- [Transactions and Safety](#transactions-and-safety) +- [Explicit Transactions](#explicit-transactions) +- [Savepoints](#savepoints) +- [Transaction Kinds](#transaction-kinds) + + +### Transactions and Safety + +**A transaction** is a fundamental tool of SQLite that guarantees [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. + +GRDB generally opens transactions for you, as a way to enforce its [concurrency guarantees](#concurrency), and provide maximal security for both your application data and application logic: + +```swift +// BEGIN TRANSACTION +// INSERT INTO credit ... +// INSERT INTO debit ... +// COMMIT +try dbQueue.write { db in + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) +} + +// BEGIN TRANSACTION +// INSERT INTO credit ... +// INSERT INTO debit ... +// COMMIT +try dbPool.write { db in + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) +} +``` + +Yet you may need to exactly control when transactions take place: + + +### Explicit Transactions + +`DatabaseQueue.inDatabase()` and `DatabasePool.writeWithoutTransaction()` execute your database statements outside of any transaction: + +```swift +// 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 credit ... +// INSERT INTO debit ... +try dbPool.writeWithoutTransaction { db in + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) +} +``` + +**Writing outside of any transaction can be dangerous.** In our credit/debit example, you may successfully insert a credit, but fail inserting the debit, and end up with unbalanced accounts (oops). + +Furthermore, outside of any transaction, database pool concurrent reads may see an inconsistent state of the database: + +```swift +// UNSAFE CONCURRENCY +try dbPool.writeWithoutTransaction { db in + try Credit(destinationAccout, amount).insert(db) + // <- Concurrent dbPool.read sees a partial db update here + try Debit(sourceAccount, amount).insert(db) +} +``` + +To open explicit transactions, use one of the `Database.inTransaction`, `DatabaseQueue.inTransaction`, or `DatabasePool.writeInTransaction` methods: + +```swift +// BEGIN TRANSACTION +// INSERT INTO credit ... +// INSERT INTO debit ... +// COMMIT +try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction + try db.inTransaction { + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + return .commit + } +} + +// BEGIN TRANSACTION +// INSERT INTO credit ... +// INSERT INTO debit ... +// COMMIT +try dbQueue.inTransaction { db in // or dbPool.writeInTransaction + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + return .commit +} +``` + +If an error is thrown from the transaction block, the transaction is rollbacked and the error is rethrown by the `inTransaction` method. If you return `.rollback` instead of `.commit`, the transaction is also rollbacked, but no error is thrown. + +You can also perform manual transaction management: + +```swift +try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction + try db.beginTransaction() + ... + try db.commit() + + try db.execute("BEGIN TRANSACTION") + ... + try db.execute("ROLLBACK") +} +``` + +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/Configuration.html) configuration flag: + +```swift +// fatal error: A transaction has been left opened at the end of a database access +try dbQueue.inDatabase { db in + try db.execute("BEGIN TRANSACTION") + // <- no commit or rollback +} +``` + +You can ask if a transaction is currently opened: + +```swift +func myCriticalMethod(_ db: Database) throws { + precondition(db.isInsideTransaction, "This method requires a transaction") + try ... +} +``` + +Yet, you have a better option than checking for transactions: critical database sections should use savepoints, described below: + +```swift +func myCriticalMethod(_ db: Database) throws { + try db.inSavepoint { + // Here the database is guaranteed to be inside a transaction. + try ... + } +} +``` + + +### Savepoints + +**Statements grouped in a savepoint can be rollbacked without invalidating a whole transaction:** + +```swift +try dbQueue.write { db in + // Makes sure both inserts succeed, or none: + try db.inSavepoint { + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + return .commit + } + + // Other savepoints, etc... +} +``` + +If an error is thrown from the savepoint block, the savepoint is rollbacked and the error is rethrown by the `inSavepoint` method. If you return `.rollback` instead of `.commit`, the savepoint is also rollbacked, but no error is thrown. + +**Unlike transactions, savepoints can be nested.** They implicitly open a transaction if no one was opened when the savepoint begins. As such, they behave just like nested transactions. Yet the database changes are only written to disk when the outermost transaction is committed: + +```swift +try dbQueue.inDatabase { db in + try db.inSavepoint { + ... + try db.inSavepoint { + ... + return .commit + } + ... + return .commit // writes changes to disk + } +} +``` + +SQLite savepoints are more than nested transactions, though. For advanced uses, use [SQLite savepoint documentation](https://www.sqlite.org/lang_savepoint.html). + + +### Transaction Kinds + +SQLite supports [three kinds of transactions](https://www.sqlite.org/lang_transaction.html): deferred (the default), immediate, and exclusive. + +The transaction kind can be changed in the database configuration, or for each transaction: + +```swift +// 1) Default configuration: +let dbQueue = try DatabaseQueue(path: "...") + +// BEGIN DEFERED TRANSACTION ... +dbQueue.write { db in ... } + +// BEGIN EXCLUSIVE TRANSACTION ... +dbQueue.inTransaction(.exclusive) { db in ... } + +// 2) Customized default transaction kind: +var config = Configuration() +config.defaultTransactionKind = .immediate +let dbQueue = try DatabaseQueue(path: "...", configuration: config) + +// BEGIN IMMEDIATE TRANSACTION ... +dbQueue.write { db in ... } + +// BEGIN EXCLUSIVE TRANSACTION ... +dbQueue.inTransaction(.exclusive) { db in ... } +``` + + ## Prepared Statements **Prepared Statements** let you prepare an SQL query and execute it later, several times if you need, with different arguments. @@ -1404,16 +1569,16 @@ The `fromDatabaseValue()` factory method returns an instance of your custom type There are two kinds of prepared statements: **select statements**, and **update statements**: ```swift -try dbQueue.inDatabase { db in - let updateSQL = "INSERT INTO players (name, score) VALUES (:name, :score)" +try dbQueue.write { db in + 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) } ``` -The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). +The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift updateStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1471,8 +1636,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) @@ -1488,11 +1653,11 @@ let reverse = DatabaseFunction("reverse", argumentCount: 1, pure: true) { (value return nil } // ... and return reversed string: - return String(string.characters.reversed()) + return String(string.reversed()) } dbQueue.add(function: reverse) // Or dbPool.add(function: ...) -try dbQueue.inDatabase { db in +try dbQueue.read { db in // "oof" try String.fetchOne(db, "SELECT reverse('foo')")! } @@ -1514,7 +1679,7 @@ let averageOf = DatabaseFunction("averageOf", pure: true) { (values: [DatabaseVa } dbQueue.add(function: averageOf) -try dbQueue.inDatabase { db in +try dbQueue.read { db in // 2.0 try Double.fetchOne(db, "SELECT averageOf(1, 2, 3)")! } @@ -1536,7 +1701,7 @@ let sqrt = DatabaseFunction("sqrt", argumentCount: 1, pure: true) { (values: [Da dbQueue.add(function: sqrt) // SQLite error 1 with statement `SELECT sqrt(-1)`: invalid negative number -try dbQueue.inDatabase { db in +try dbQueue.read { db in try Double.fetchOne(db, "SELECT sqrt(-1)")! } ``` @@ -1545,7 +1710,7 @@ try dbQueue.inDatabase { 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)) ``` @@ -1582,7 +1747,7 @@ struct MaxLength : DatabaseAggregate { return } // ... and update the result - let length = string.characters.count + let length = string.count if length > maxLength { maxLength = length } @@ -1601,9 +1766,9 @@ let maxLength = DatabaseFunction( dbQueue.add(function: maxLength) // Or dbPool.add(function: ...) -try dbQueue.inDatabase { db in +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")! } ``` @@ -1617,45 +1782,41 @@ 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 -Player.select(maxLength.apply(nameColumn)) - .asRequest(of: Int.self) - .fetchOne(db) // Int? +// SELECT maxLength("name") FROM player +Int.fetchOne(db, Player.select(maxLength.apply(nameColumn))) // Int? ``` ## Database Schema Introspection -**SQLite provides database schema introspection tools**, such as the [sqlite_master](https://www.sqlite.org/faq.html#q7) table, and the pragma [table_info](https://www.sqlite.org/pragma.html#pragma_table_info): +GRDB comes with a set of schema introspection methods: ```swift -try db.create(table: "players") { t in - t.column("id", .integer).primaryKey() - t.column("name", .text) +try dbQueue.read { db in + // Bool, true if the table exists + try db.tableExists("player") + + // [ColumnInfo], the columns in the table + try db.columns(in: "player") + + // PrimaryKeyInfo + try db.primaryKey("player") + + // [ForeignKeyInfo], the foreign keys defined on the table + try db.foreignKeys(on: "player") + + // [IndexInfo], the indexes defined on the table + try db.indexes(on: "player") + + // Bool, true if column(s) is a unique key + try db.table("player", hasUniqueKey: ["email"]) } -// -for row in try Row.fetchAll(db, "SELECT * FROM sqlite_master") { - print(row) -} +// Bool, true if argument is the name of an internal SQLite table +Database.isSQLiteInternalTable(...) -// -// -for row in try Row.fetchAll(db, "PRAGMA table_info('players')") { - print(row) -} -``` - -GRDB provides high-level methods as well: - -```swift -try db.tableExists("players") // Bool, true if the table exists -try db.columns(in: "players") // [ColumnInfo], the columns in the table -try db.indexes(on: "players") // [IndexInfo], the indexes defined on the table -try db.foreignKeys(on: "players") // [ForeignKeyInfo], the foreign keys defined on the table -try db.primaryKey("players") // PrimaryKeyInfo -try db.table("players", hasUniqueKey: ["email"]) // Bool, true if column(s) is a unique key +// Bool, true if argument is the name of an internal GRDB table +Database.isGRDBInternalTable(...) ``` @@ -1675,7 +1836,7 @@ row["consumed"] // "Hello" row["produced"] // nil ``` -Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below. +Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below. To see how row adapters can be used, see [Joined Queries Support](#joined-queries-support). @@ -1685,7 +1846,7 @@ To see how row adapters can be used, see [Joined Queries Support](#joined-querie ColumnMapping renames columns. Build one with a dictionary whose keys are adapted column names, and values the column names in the raw row: ```swift -// +// [newName:"Hello"] let adapter = ColumnMapping(["newName": "oldName"]) let row = try Row.fetchOne(db, "SELECT 'Hello' AS oldName", adapter: adapter)! ``` @@ -1695,7 +1856,7 @@ let row = try Row.fetchOne(db, "SELECT 'Hello' AS oldName", adapter: adapter)! `SuffixRowAdapter` hides the first columns in a row: ```swift -// +// [b:1 c:2] let adapter = SuffixRowAdapter(fromIndex: 1) let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c", adapter: adapter)! ``` @@ -1705,14 +1866,14 @@ let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c", adapter: adapter `RangeRowAdapter` only exposes a range of columns. ```swift -// +// [b:1] let adapter = RangeRowAdapter(1..<2) let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c", adapter: adapter)! ``` ### EmptyRowAdapter -`EmptyRowAdapter` hides all rows. +`EmptyRowAdapter` hides all columns. ```swift let adapter = EmptyRowAdapter() @@ -1734,13 +1895,13 @@ let adapter = ScopeAdapter([ let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d", adapter: adapter)! ``` -ScopeAdapter does not change the columns and values of the fetched row. Instead, it defines *scopes*, which you access with the `Row.scoped(on:)` method. This method returns an optional Row, which is nil if the scope is missing. +ScopeAdapter does not change the columns and values of the fetched row. Instead, it defines *scopes*, which you access through the `Row.scopes` property: ```swift -row // -row.scoped(on: "left") // -row.scoped(on: "right") // -row.scoped(on: "missing") // nil +row // [a:0 b:1 c:2 d:3] +row.scopes["left"] // [a:0 b:1] +row.scopes["right"] // [c:2 d:3] +row.scopes["missing"] // nil ``` Scopes can be nested: @@ -1756,13 +1917,13 @@ let adapter = ScopeAdapter([ ]) let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d", adapter: adapter)! -let leftRow = row.scoped(on: "left")! -leftRow.scoped(on: "left") // -leftRow.scoped(on: "right") // +let leftRow = row.scopes["left"]! +leftRow.scopes["left"] // [a:0] +leftRow.scopes["right"] // [b:1] -let rightRow = row.scoped(on: "right")! -rightRow.scoped(on: "left") // -rightRow.scoped(on: "right") // +let rightRow = row.scopes["right"]! +rightRow.scopes["left"] // [c:2] +rightRow.scopes["right"] // [d:3] ``` Any adapter can be extended with scopes: @@ -1773,8 +1934,8 @@ let adapter = ScopeAdapter(base: baseAdapter, scopes: [ "remainder": SuffixRowAdapter(fromIndex: 2)]) let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d", adapter: adapter)! -row // -row.scoped(on: "remainder") // +row // [a:0 b:1] +row.scopes["remainder"] // [c:2 d:3] ``` @@ -1797,7 +1958,7 @@ let sqliteVersion = String(cString: sqlite3_libversion()) Raw pointers to database connections and statements are available through the `Database.sqliteConnection` and `Statement.sqliteStatement` properties: ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in // The raw pointer to a database connection: let sqliteConnection = db.sqliteConnection @@ -1818,8 +1979,8 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used - `sqlite3_aggregate_context`, `sqlite3_create_function_v2`, `sqlite3_result_blob`, `sqlite3_result_double`, `sqlite3_result_error`, `sqlite3_result_error_code`, `sqlite3_result_int64`, `sqlite3_result_null`, `sqlite3_result_text`, `sqlite3_user_data`, `sqlite3_value_blob`, `sqlite3_value_bytes`, `sqlite3_value_double`, `sqlite3_value_int64`, `sqlite3_value_text`, `sqlite3_value_type`: see [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates) - `sqlite3_backup_finish`, `sqlite3_backup_init`, `sqlite3_backup_step`: see [Backup](#backup) - `sqlite3_bind_blob`, `sqlite3_bind_double`, `sqlite3_bind_int64`, `sqlite3_bind_null`, `sqlite3_bind_parameter_count`, `sqlite3_bind_parameter_name`, `sqlite3_bind_text`, `sqlite3_clear_bindings`, `sqlite3_column_blob`, `sqlite3_column_bytes`, `sqlite3_column_count`, `sqlite3_column_double`, `sqlite3_column_int64`, `sqlite3_column_name`, `sqlite3_column_text`, `sqlite3_column_type`, `sqlite3_exec`, `sqlite3_finalize`, `sqlite3_prepare_v2`, `sqlite3_reset`, `sqlite3_step`: see [Executing Updates](#executing-updates), [Fetch Queries](#fetch-queries), [Prepared Statements](#prepared-statements), [Values](#values) -- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.10/Structs/Configuration.html) -- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.10/Classes/Database.html) +- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/Configuration.html) +- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Classes/Database.html) - `sqlite3_close`, `sqlite3_close_v2`, `sqlite3_next_stmt`, `sqlite3_open_v2`: see [Database Connections](#database-connections) - `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [FetchedRecordsController](#fetchedrecordscontroller) - `sqlite3_config`: see [Error Log](#error-log) @@ -1830,9 +1991,9 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used - `sqlite3_last_insert_rowid`: see [Executing Updates](#executing-updates) - `sqlite3_preupdate_count`, `sqlite3_preupdate_depth`, `sqlite3_preupdate_hook`, `sqlite3_preupdate_new`, `sqlite3_preupdate_old`: see [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks) - `sqlite3_set_authorizer`: **reserved by GRDB** -- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/2.10/Classes/Statement.html) -- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.10/Structs/Configuration.html) -- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.10/Classes/DatabasePool.html) +- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Classes/Statement.html) +- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/Configuration.html) +- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Classes/DatabasePool.html) Records @@ -1841,7 +2002,7 @@ Records **On top of the [SQLite API](#sqlite-api), GRDB provides protocols and a class** that help manipulating database rows as regular objects named "records": ```swift -try dbQueue.inDatabase { db in +try dbQueue.write { db in if let place = try Place.fetchOne(db, key: 1) { place.isFavorite = true try place.update(db) @@ -1851,9 +2012,11 @@ try dbQueue.inDatabase { db in Of course, you need to open a [database connection](#database-connections), and [create a database table](#database-schema) first. -Your custom structs and classes can adopt each protocol individually, and opt in to focused sets of features. Or you can subclass the `Record` class, and get the full toolkit in one go: fetching methods, persistence methods, and changes tracking. See the [list of record methods](#list-of-record-methods) for an overview. +Your custom structs and classes can adopt each protocol individually, and opt in to focused sets of features. Or you can subclass the `Record` class, and get the full toolkit in one go: fetching methods, persistence methods, and record comparison. See the [list of record methods](#list-of-record-methods) for an overview. > :point_up: **Note**: if you are familiar with Core Data's NSManagedObject or Realm's Object, you may experience a cultural shock: GRDB records are not uniqued, and do not auto-update. This is both a purpose, and a consequence of protocol-oriented programming. You should read [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) for a general introduction. +> +> :bulb: **Tip**: after you have read this chapter, check the [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) Guide. **Overview** @@ -1863,25 +2026,30 @@ Your custom structs and classes can adopt each protocol individually, and opt in - [Deleting Records](#deleting-records) - [Counting Records](#counting-records) -**Protocols and the Record class** +**Protocols and the Record Class** - [Record Protocols Overview](#record-protocols-overview) -- [RowConvertible Protocol](#rowconvertible-protocol) -- [TableMapping Protocol](#tablemapping-protocol) -- [Persistable Protocol](#persistable-protocol) +- [FetchableRecord Protocol](#fetchablerecord-protocol) +- [TableRecord Protocol](#tablerecord-protocol) +- [PersistableRecord Protocol](#persistablerecord-protocol) - [Persistence Methods](#persistence-methods) - [Customizing the Persistence Methods](#customizing-the-persistence-methods) - [Codable Records](#codable-records) - [Record Class](#record-class) -- [Changes Tracking](#changes-tracking) +- [Record Comparison] - [Conflict Resolution](#conflict-resolution) - [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key) +- [Customized Decoding of Database Rows](#customized-decoding-of-database-rows) + +**Records in a Glance** + +- [Examples of Record Definitions](#examples-of-record-definitions) - [List of Record Methods](#list-of-record-methods) ### Inserting Records -To insert a record in the database, subclass the [Record](#record-class) class or adopt the [Persistable](#persistable-protocol) protocol, and call the `insert` method: +To insert a record in the database, subclass the [Record](#record-class) class or adopt the [PersistableRecord] protocol, and call the `insert` method: ```swift class Player : Record { ... } @@ -1893,14 +2061,14 @@ try player.insert(db) ### Fetching Records -[Record](#record-class) subclasses and types that adopt the [RowConvertible](#rowconvertible-protocol) protocol can be fetched from the database: +[Record](#record-class) subclasses and types that adopt the [FetchableRecord] protocol can be fetched from the database: ```swift class Player : Record { ... } let players = try Player.fetchAll(db, "SELECT ...", arguments: ...) // [Player] ``` -Add the [TableMapping](#tablemapping-protocol) protocol and you can stop writing SQL: +Add the [TableRecord] protocol and you can stop writing SQL: ```swift let spain = try Country.fetchOne(db, key: "ES") // Country? @@ -1915,32 +2083,32 @@ See [fetching methods](#fetching-methods), and the [query interface](#the-query- ### Updating Records -[Record](#record-class) subclasses and types that adopt the [Persistable](#persistable-protocol) protocol can be updated in the database: +[Record](#record-class) subclasses and types that adopt the [PersistableRecord] protocol can be updated in the database: ```swift let player = try Player.fetchOne(db, key: 1)! -player.name = "Arthur" +player.score = 1000 try player.update(db) ``` -It is possible to [avoid useless updates](#changes-tracking): +It is possible to [avoid useless updates](#record-comparison): ```swift let player = try Player.fetchOne(db, key: 1)! -player.name = "Arthur" -try player.updateChanges(db) +player.score = 1000 +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") ``` ### Deleting Records -[Record](#record-class) subclasses and types that adopt the [Persistable](#persistable-protocol) protocol can be deleted from the database: +[Record](#record-class) subclasses and types that adopt the [PersistableRecord] protocol can be deleted from the database: ```swift let player = try Player.fetchOne(db, key: 1)! @@ -1964,7 +2132,7 @@ try Player.filter(emailColumn == nil).deleteAll(db) ### Counting Records -[Record](#record-class) subclasses and types that adopt the [TableMapping](#tablemapping-protocol) protocol can be counted: +[Record](#record-class) subclasses and types that adopt the [TableRecord] protocol can be counted: ```swift let playerWithEmailCount = try Player.filter(emailColumn != nil).fetchCount(db) // Int @@ -1974,14 +2142,16 @@ let playerWithEmailCount = try Player.filter(emailColumn != nil).fetchCount(db) Details follow: - [Record Protocols Overview](#record-protocols-overview) -- [RowConvertible Protocol](#rowconvertible-protocol) -- [TableMapping Protocol](#tablemapping-protocol) -- [Persistable Protocol](#persistable-protocol) +- [FetchableRecord Protocol](#fetchablerecord-protocol) +- [TableRecord Protocol](#tablerecord-protocol) +- [PersistableRecord Protocol](#persistablerecord-protocol) - [Codable Records](#codable-records) - [Record Class](#record-class) -- [Changes Tracking](#changes-tracking) +- [Record Comparison] - [Conflict Resolution](#conflict-resolution) - [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key) +- [Customized Decoding of Database Rows](#customized-decoding-of-database-rows) +- [Examples of Record Definitions](#examples-of-record-definitions) - [List of Record Methods](#list-of-record-methods) @@ -1989,14 +2159,14 @@ Details follow: **GRDB ships with three record protocols**. Your own types will adopt one or several of them, according to the abilities you want to extend your types with. -- [RowConvertible](#rowconvertible-protocol) is able to **read**: it grants the ability to efficiently decode raw database row. +- [FetchableRecord] is able to **decode database rows**. - You can always decode rows yourself: + It is always possible to decode rows without this protocol: ```swift struct Place { ... } - try dbQueue.inDatabase { db in - let rows = try Row.fetchAll(db, "SELECT * FROM places") + try dbQueue.read { db in + let rows = try Row.fetchAll(db, "SELECT * FROM place") let places: [Place] = rows.map { row in return Place( id: row["id"], @@ -2009,60 +2179,60 @@ Details follow: } ``` - But RowConvertible lets you write code that is much more readable, and much more efficient as well, both in terms of performance and memory usage: + But FetchableRecord lets you write code that is easier to read, and more efficient as well, both in terms of performance and memory usage: ```swift struct Place: FetchableRecord { ... } - try dbQueue.inDatabase { db in - let places = try Place.fetchAll(db, "SELECT * FROM places") + try dbQueue.read { db in + let places = try Place.fetchAll(db, "SELECT * FROM place") } ``` - RowConvertible is not able to build SQL requests for you, though. For that, you also need TableMapping: + FetchableRecord is not able to build SQL requests for you, though. For that, you also need TableRecord: -- [TableMapping](#tablemapping-protocol) is able to **build requests without SQL**: +- [TableRecord] is able to **generate SQL queries**: ```swift - struct Place : TableMapping { ... } - // SELECT * FROM places ORDER BY title + struct Place: TableRecord { ... } + // SELECT * FROM place ORDER BY title let request = Place.order(Column("title")) ``` - When a type adopts both TableMapping and RowConvertible, it can load from those requests: + When a type adopts both TableRecord and FetchableRecord, it can load from those requests: ```swift - struct Place : TableMapping, RowConvertible { ... } - try dbQueue.inDatabase { db in + struct Place: TableRecord, FetchableRecord { ... } + try dbQueue.read { db in let places = try Place.order(Column("title")).fetchAll(db) let paris = try Place.fetchOne(key: 1) } ``` -- [Persistable](#persistable-protocol) is able to **write**: it can create, update, and delete rows in the database: +- [PersistableRecord] is able to **write**: it can create, update, and delete rows in the database: ```swift - struct Place : Persistable { ... } - try dbQueue.inDatabase { db in + struct Place : PersistableRecord { ... } + try dbQueue.write { db in try Place.delete(db, key: 1) try Place(...).insert(db) } ``` - A persistable record can also [compare](#changes-tracking) itself against other records, and avoid useless database updates. + A persistable record can also [compare](#record-comparison) itself against other records, and avoid useless database updates. -## RowConvertible Protocol +## FetchableRecord Protocol -**The RowConvertible protocol grants fetching methods to any type** that can be built from a database row: +**The FetchableRecord protocol grants fetching methods to any type** that can be built from a database row: ```swift -protocol RowConvertible { +protocol FetchableRecord { /// Row initializer init(row: Row) } ``` -**To use RowConvertible**, subclass the [Record](#record-class) class, or adopt it explicitly. For example: +**To use FetchableRecord**, subclass the [Record](#record-class) class, or adopt it explicitly. For example: ```swift struct Place { @@ -2071,7 +2241,7 @@ struct Place { var coordinate: CLLocationCoordinate2D } -extension Place : RowConvertible { +extension Place : FetchableRecord { init(row: Row) { id = row["id"] title = row["title"] @@ -2082,15 +2252,12 @@ extension Place : RowConvertible { } ``` -Rows also accept keys of type `Column`: +Rows also accept columns: ```swift -extension Place : RowConvertible { - enum Columns { - static let id = Column("id") - static let title = Column("title") - static let latitude = Column("latitude") - static let longitude = Column("longitude") +extension Place : FetchableRecord { + enum Columns: String, ColumnExpression { + case id, title, latitude, longitude } init(row: Row) { @@ -2109,7 +2276,7 @@ See [column values](#column-values) for more information about the `row[]` subsc > > :bulb: **Tip**: the `init(row:)` initializer can be automatically generated when your type adopts the standard `Decodable` protocol. See [Codable Records](#codable-records) for more information. -RowConvertible allows adopting types to be fetched from SQL queries: +FetchableRecord allows adopting types to be fetched from SQL queries: ```swift try Place.fetchCursor(db, "SELECT ...", arguments:...) // A Cursor of Place @@ -2117,38 +2284,67 @@ try Place.fetchAll(db, "SELECT ...", arguments:...) // [Place] try Place.fetchOne(db, "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html) for more information about the query arguments. + +> :point_up: **Note**: The `FetchableRecord.init(row:)` initializer fits the needs of most applications. But some application are more demanding than others. When FetchableRecord does not exactly provide the support you need, have a look at the [Customized Decoding of Database Rows](#customized-decoding-of-database-rows) chapter. -## TableMapping Protocol +## TableRecord Protocol -**Adopt the TableMapping protocol** on top of [RowConvertible](#rowconvertible-protocol), and you are granted with the full [query interface](#the-query-interface). +**The TableRecord protocol** generates SQL for you. To use TableRecord, subclass the [Record](#record-class) class, or adopt it explicitly: ```swift -protocol TableMapping { +protocol TableRecord { static var databaseTableName: String { get } static var databaseSelection: [SQLSelectable] { get } } ``` -The `databaseTableName` type property is the name of a database table. `databaseSelection` is optional, and documented in the [Columns Selected by a Request](#columns-selected-by-a-request) chapter. +- The `databaseTableName` type property is the name of a database table. By default, it is derived from the type name: + + ```swift + struct Place: TableRecord { } + print(Place.databaseTableName) // prints "place" + ``` + + For example: + + - Place: `place` + - Country: `country` + - PostalAddress: `postalAddress` + - HTTPRequest: `httpRequest` + - TOEFL: `toefl` + + You can still provide a custom table name: + + ```swift + struct Place: TableRecord { + static let databaseTableName = "location" + } + print(Place.databaseTableName) // prints "location" + ``` + + Subclasses of the [Record](#record-class) class must always override their superclass's `databaseTableName` property: + + ```swift + class Place: Record { + override class var databaseTableName: String { + return "place" + } + } + print(Place.databaseTableName) // prints "place" + ``` + +- The `databaseSelection` type property is optional, and documented in the [Columns Selected by a Request](#columns-selected-by-a-request) chapter. -**To use TableMapping**, subclass the [Record](#record-class) class, or adopt it explicitely. For example: +When a type adopts both TableRecord and [FetchableRecord](#fetchablerecord-protocol), it can be fetched using the [query interface](#the-query-interface): ```swift -extension Place : TableMapping { - static let databaseTableName = "places" -} -``` - -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) ``` -TableMapping can also fetch records by primary key: +TableRecord can also fetch records by primary key: ```swift try Player.fetchOne(db, key: 1) // Player? @@ -2161,27 +2357,24 @@ 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' -try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Citizenship? +// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' +try Citizenship.fetchOne(db, key: ["citizenId": 1, "countryCode": "FR"]) // Citizenship? ``` -## Persistable Protocol +## PersistableRecord Protocol **GRDB provides two protocols that let adopting types create, update, and delete rows in the database:** ```swift -protocol MutablePersistable : TableMapping { - /// The name of the database table (from TableMapping) - static var databaseTableName: String { get } - +protocol MutablePersistableRecord : TableRecord { /// Defines the values persisted in the database func encode(to container: inout PersistenceContainer) @@ -2192,7 +2385,7 @@ protocol MutablePersistable : TableMapping { ``` ```swift -protocol Persistable : MutablePersistable { +protocol PersistableRecord : MutablePersistableRecord { /// Non-mutating version of the optional didInsert(with:for:) func didInsert(with rowID: Int64, for column: String?) } @@ -2200,23 +2393,22 @@ protocol Persistable : MutablePersistable { Yes, two protocols instead of one. Both grant exactly the same advantages. Here is how you pick one or the other: -- *If your type is a struct that mutates on insertion*, choose `MutablePersistable`. - - For example, your table has an INTEGER PRIMARY KEY and you want to store the inserted id on successful insertion. Or your table has a UUID primary key, and you want to automatically generate one on insertion. +- **If your type is a class**, choose `PersistableRecord`. On top of that, implement `didInsert(with:for:)` if the database table has an auto-incremented primary key. -- Otherwise, stick with `Persistable`. Particularly if your type is a class. +- **If your type is a struct, and the database table has an auto-incremented primary key**, choose `MutablePersistableRecord`, and implement `didInsert(with:for:)`. + +- **Otherwise**, choose `PersistableRecord`, and ignore `didInsert(with:for:)`. The `encode(to:)` method defines which [values](#values) (Bool, Int, String, Date, Swift enums, etc.) are assigned to database columns. > :bulb: **Tip**: `encode(to:)` can be automatically generated when your type adopts the standard `Encodable` protocol. See [Codable Records](#codable-records) for more information. -The optional `didInsert` method lets the adopting type store its rowID after successful insertion. If your table has an INTEGER PRIMARY KEY column, you are likely to define this method. Otherwise, you can safely ignore it. It is called from a protected dispatch queue, and serialized with all database updates. +The optional `didInsert` method lets the adopting type store its rowID after successful insertion, and is only useful for tables that have an auto-incremented primary key. It is called from a protected dispatch queue, and serialized with all database updates. -**To use those protocols**, subclass the [Record](#record-class) class, or adopt one of them explicitly. For example: +**To use the persistable protocols**, subclass the [Record](#record-class) class, or adopt one of them explicitly. For example: ```swift -extension Place : MutablePersistable { - +extension Place : MutablePersistableRecord { /// The values persisted in the database func encode(to container: inout PersistenceContainer) { container["id"] = id @@ -2240,15 +2432,12 @@ try paris.insert(db) paris.id // some value ``` -Persistence containers also accept keys of type `Column`: +Persistence containers also accept columns: ```swift -extension Place : MutablePersistable { - enum Columns { - static let id = Column("id") - static let title = Column("title") - static let latitude = Column("latitude") - static let longitude = Column("longitude") +extension Place : MutablePersistableRecord { + enum Columns: String, ColumnExpression { + case id, title, latitude, longitude } func encode(to container: inout PersistenceContainer) { @@ -2263,7 +2452,7 @@ extension Place : MutablePersistable { ### Persistence Methods -[Record](#record-class) subclasses and types that adopt [Persistable](#persistable-protocol) are given default implementations for methods that insert, update, and delete: +[Record](#record-class) subclasses and types that adopt [PersistableRecord] are given default implementations for methods that insert, update, and delete: ```swift // Instance methods @@ -2320,10 +2509,10 @@ class Player : Record { } ``` -If you use the raw [Persistable](#persistable-protocol) protocol, use one of the *special methods* `performInsert`, `performUpdate`, `performSave`, `performDelete`, or `performExists`: +If you use the raw [PersistableRecord] protocol, use one of the *special methods* `performInsert`, `performUpdate`, `performSave`, `performDelete`, or `performExists`: ```swift -struct Link : Persistable { +struct Link : PersistableRecord { var url: URL func insert(_ db: Database) throws { @@ -2353,7 +2542,7 @@ struct Link : Persistable { [Swift Archival & Serialization](https://github.com/apple/swift-evolution/blob/master/proposals/0166-swift-archival-serialization.md) was introduced with Swift 4. -GRDB provides default implementations for [`RowConvertible.init(row:)`](#rowconvertible-protocol) and [`Persistable.encode(to:)`](#persistable-protocol) for record types that also adopt an archival protocol (`Codable`, `Encodable` or `Decodable`). When all their properties are themselves codable, Swift generates the archiving methods, and you don't need to write them down: +GRDB provides default implementations for [`FetchableRecord.init(row:)`](#fetchablerecord-protocol) and [`PersistableRecord.encode(to:)`](#persistablerecord-protocol) for record types that also adopt an archival protocol (`Codable`, `Encodable` or `Decodable`). When all their properties are themselves codable, Swift generates the archiving methods, and you don't need to write them down: ```swift // Declare a plain Codable struct or class... @@ -2363,12 +2552,10 @@ struct Player: Codable { } // Adopt Record protocols... -extension Player: RowConvertible, Persistable { - static let databaseTableName = "players" -} +extension Player: FetchableRecord, PersistableRecord { } // ...and you can save and fetch players: -try dbQueue.inDatabase { db in +try dbQueue.write { db in try Player(name: "Arthur", score: 100).insert(db) let players = try Player.fetchAll(db) } @@ -2378,9 +2565,7 @@ GRDB support for Codable works well with "flat" records, whose stored properties ```swift // Can't take profit from Codable code generation: -struct Place: RowConvertible, Persistable, Codable { - static let databaseTableName = "places" - +struct Place: FetchableRecord, PersistableRecord, Codable { var title: String var coordinate: CLLocationCoordinate2D // <- Not a simple value! } @@ -2410,14 +2595,12 @@ struct Place: Codable { } // Free database support! -extension Place: RowConvertible, Persistable { - static let databaseTableName = "places" -} +extension Place: FetchableRecord, PersistableRecord { } ``` -GRDB ships with support for nested codable records, but this is a more complex topic. See [Joined Queries Support](#joined-queries-support) for more information. +GRDB ships with support for nested codable records, but this is a more complex topic. See [Associations](Documentation/AssociationsBasics.md) for more information. -As documented with the [Persistable](#persistable-protocol) protocol, have your struct records use MutablePersistable instead of Persistable when they store their automatically incremented row id: +As documented with the [PersistableRecord] protocol, have your struct records use MutablePersistableRecord instead of PersistableRecord when they store their automatically incremented row id: ```swift struct Place: Codable { @@ -2428,9 +2611,7 @@ struct Place: Codable { var coordinate: CLLocationCoordinate2D { ... } } -extension Place: RowConvertible, MutablePersistable { - static let databaseTableName = "places" - +extension Place: FetchableRecord, MutablePersistableRecord { mutating func didInsert(with rowID: Int64, for column: String?) { // Update id after insertion id = rowID @@ -2448,40 +2629,56 @@ place.id // A unique id ## Record Class -**Record** is a class that is designed to be subclassed. It inherits its features from the [RowConvertible, TableMapping, and Persistable](#record-protocols-overview) protocols. On top of that, Record instances can [track their changes](#changes-tracking). +**Record** is a class that is designed to be subclassed. It inherits its features from the [FetchableRecord, TableRecord, and PersistableRecord](#record-protocols-overview) protocols. On top of that, Record instances can compare against previous versions of themselves in order to [avoid useless updates](#record-comparison). -Record subclasses define their custom database relationship by overriding database methods: +Record subclasses define their custom database relationship by overriding database methods. For example: ```swift -class Place : Record { +class Place: Record { var id: Int64? var title: String + var isFavorite: Bool var coordinate: CLLocationCoordinate2D + init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) { + self.id = id + self.title = title + self.isFavorite = isFavorite + self.coordinate = coordinate + super.init() + } + /// The table name override class var databaseTableName: String { - return "places" + return "place" } - /// Initialize from a database row + /// The table columns + enum Columns: String, ColumnExpression { + case id, title, favorite, latitude, longitude + } + + /// Creates a record from a database row required init(row: Row) { - id = row["id"] - title = row["title"] + id = row[Columns.id] + title = row[Columns.title] + isFavorite = row[Columns.favorite] coordinate = CLLocationCoordinate2D( - latitude: row["latitude"], - longitude: row["longitude"]) + latitude: row[Columns.latitude], + longitude: row[Columns.longitude]) super.init(row: row) } /// The values persisted in the database override func encode(to container: inout PersistenceContainer) { - container["id"] = id - container["title"] = title - container["latitude"] = coordinate.latitude - container["longitude"] = coordinate.longitude + container[Columns.id] = id + container[Columns.title] = title + container[Columns.favorite] = isFavorite + container[Columns.latitude] = coordinate.latitude + container[Columns.longitude] = coordinate.longitude } - /// When relevant, update record ID after a successful insertion + /// Update record ID after a successful insertion override func didInsert(with rowID: Int64, for column: String?) { id = rowID } @@ -2489,13 +2686,13 @@ class Place : Record { ``` -## Changes Tracking +## Record Comparison -**Changes tracking is the ability, for a record, to compare against another record, or against previous versions of itself.** +**Records can compare against other records, or against previous versions of themselves.** -The `update()` [method](#persistence-methods) always executes an UPDATE statement. When the record has not been edited, this costly database access is generally useless. +This helps avoiding costly UPDATE statements when a record has not been edited. -You can use instead the `updateChanges` method, available on the [Persistable](#persistable-protocol) protocol, which performs an update of the changed columns only (and does nothing if record has no change): +You can use the `updateChanges` method, available on the [PersistableRecord] protocol, which performs an update of the changed columns only (and does nothing if record has no change): ```swift let oldPlayer = try Player.fetchOne(db, ...) @@ -2508,7 +2705,7 @@ if try newPlayer.updateChanges(db, from: oldPlayer) { } ``` -> :point_up: **Note**: The comparison is performed of the database representation of records. As long as your record type adopts a Persistable protocol, you don't need to care about Equatable. +> :point_up: **Note**: The comparison is performed of the database representation of records. As long as your record type adopts a PersistableRecord protocol, you don't need to care about Equatable. The [Record](#record-class) class is able to compare against itself, and knows if it has changes that have not been saved since it was last fetched or persisted: @@ -2523,12 +2720,12 @@ if try player.updateChanges(db) { } ``` -You can also use the `databaseEqual` method, which returns whether two records have the same database representation: +You can also use the `databaseEquals` method, which returns whether two records have the same database representation: ```swift let oldPlayer: Player = ... var newPlayer: Player = ... -if newPlayer.databaseEqual(oldPlayer) == false { +if newPlayer.databaseEquals(oldPlayer) == false { try newPlayer.save(db) } ``` @@ -2576,42 +2773,42 @@ The [five different policies](https://www.sqlite.org/lang_conflict.html) are: ab - At the table level ```swift - // CREATE TABLE players ( - // id INTEGER PRIMARY KEY, + // CREATE TABLE player ( + // id INTEGER PRIMARY KEY AUTOINCREMENT, // email TEXT UNIQUE ON CONFLICT REPLACE // ) - try db.create(table: "players") { t in - t.column("id", .integer).primaryKey() + 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 ( - // id INTEGER PRIMARY KEY, + // CREATE TABLE player ( + // id INTEGER PRIMARY KEY AUTOINCREMENT, // email TEXT UNIQUE // ) - try db.create(table: "players") { t in - t.column("id", .integer).primaryKey() + 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 MutablePersistable or Persistable protocol. It will alter the INSERT and UPDATE queries run by the `insert`, `update` and `save` [persistence methods](#persistence-methods): +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): ```swift -protocol MutablePersistable { +protocol MutablePersistableRecord { /// The policy that handles SQLite conflicts when records are inserted /// or updated. /// @@ -2621,13 +2818,13 @@ protocol MutablePersistable { static var persistenceConflictPolicy: PersistenceConflictPolicy { get } } -struct Player : MutablePersistable { +struct Player : MutablePersistableRecord { static let persistenceConflictPolicy = PersistenceConflictPolicy( insert: .replace, update: .replace) } -// INSERT OR REPLACE INTO players (...) VALUES (...) +// INSERT OR REPLACE INTO player (...) VALUES (...) try player.insert(db) ``` @@ -2645,13 +2842,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") @@ -2663,10 +2860,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) ``` @@ -2679,10 +2876,10 @@ Without primary key, records don't have any identity, and the [persistence metho When SQLite won't let you provide an explicit primary key (as in [full-text](#full-text-search) tables, for example), you may want to make your record type fully aware of the hidden rowid column: -1. Have the `databaseSelection` static property (from the [TableMapping](#tablemapping-protocol) protocol) return the hidden rowid column: +1. Have the `databaseSelection` static property (from the [TableRecord] protocol) return the hidden rowid column: ```swift - struct Event : TableMapping { + struct Event : TableRecord { static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] } @@ -2697,30 +2894,22 @@ 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) ``` -2. Have `init(row:)` from the [RowConvertible](#rowconvertible-protocol) protocol consume the "rowid" column: +2. Have `init(row:)` from the [FetchableRecord] protocol consume the "rowid" column: ```swift - struct Event : RowConvertible { + struct Event : FetchableRecord { var id: Int64? init(row: Row) { - id = row["rowid"] + id = row[Column.rowID] } } ``` - If you prefer using the Column type from the [query interface](#the-query-interface), use the `Column.rowID` constant: - - ```swift - init(row: Row) { - id = row[.rowID] - } - ``` - Your fetched records will then know their ids: ```swift @@ -2728,14 +2917,14 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu event.id // some value ``` -3. Encode the rowid in `encode(to:)`, and keep it in the `didInsert(with:for:)` method (both from the [Persistable and MutablePersistable](#persistable-protocol) protocols): +3. Encode the rowid in `encode(to:)`, and keep it in the `didInsert(with:for:)` method (both from the [PersistableRecord and MutablePersistableRecord](#persistablerecord-protocol) protocols): ```swift - struct Event : MutablePersistable { + struct Event : MutablePersistableRecord { var id: Int64? func encode(to container: inout PersistenceContainer) { - container[.rowID] = id + container[Column.rowID] = id container["message"] = message container["date"] = date } @@ -2764,6 +2953,198 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu ``` +## Customized Decoding of Database Rows + +**Some GRDB users eventually discover that the [FetchableRecord] protocol does not fit all situations.** Use cases that are not well handled by FetchableRecord include: + +- Your application needs polymorphic row decoding: it decodes some class or another, depending on the values contained in a database row. + +- Your application needs to decode rows with a context: each decoded value should be initialized with some extra value that does not come from the database. + +- Your application needs a record type that supports untrusted databases, and may fail at decoding database rows (throw an error when a row contains invalid values). + +Since those use cases are not well handled by FetchableRecord, don't try to implement them on top of this protocol: you'll just fight the framework. + +Instead, please have a look at the [CustomizedDecodingOfDatabaseRows](Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift) playground. You'll run some sample code, and learn how to escape FetchableRecord when you need. And remember that leaving FetchableRecord will not deprive you of [query interface requests](#requests) and generally all SQL generation features of the [TableRecord] and [PersistableRecord] protocols. + + +## Examples of Record Definitions + +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: "place") { t in + t.autoIncrementedPrimaryKey("id") + t.column("title", .text).notNull() + t.column("favorite", .boolean).notNull().defaults(to: false) + t.column("longitude", .double).notNull() + t.column("latitude", .double).notNull() + } +} +``` + +Each one of the three examples below is correct. You will pick one or the other depending on your personal preferences and the requirements of your application: + +
+ Define a Codable struct, and adopt the record protocols you need + +This is the shortest way to define a record type. + +See the [Record Protocols Overview](#record-protocols-overview), and [Codable Records](#codable-records) for more information. + +```swift +struct Place: Codable { + var id: Int64? + var title: String + var favorite: Bool + var latitude: CLLocationDegrees + var longitude: CLLocationDegrees + + var coordinate: CLLocationCoordinate2D { + get { + return CLLocationCoordinate2D( + latitude: latitude, + longitude: longitude) + } + set { + latitude = newValue.latitude + longitude = newValue.longitude + } + } +} + +// SQL generation +extension Place: TableRecord { } + +// Fetching methods +extension Place: FetchableRecord { } + +// Persistence methods +extension Place: MutablePersistableRecord { + /// Update record ID after a successful insertion + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} +``` + +
+ +
+ Define a plain struct, and adopt the record protocols you need + +See the [Record Protocols Overview](#record-protocols-overview) for more information. + +```swift +struct Place { + var id: Int64? + var title: String + var isFavorite: Bool + var coordinate: CLLocationCoordinate2D +} + +// SQL generation +extension Place: TableRecord { + /// The table columns + enum Columns: String, ColumnExpression { + case id, title, favorite, latitude, longitude + } +} + +// Fetching methods +extension Place: FetchableRecord { + /// Creates a record from a database row + init(row: Row) { + id = row[Columns.id] + title = row[Columns.title] + isFavorite = row[Columns.favorite] + coordinate = CLLocationCoordinate2D( + latitude: row[Columns.latitude], + longitude: row[Columns.longitude]) + } +} + +// Persistence methods +extension Place: MutablePersistableRecord { + /// The values persisted in the database + func encode(to container: inout PersistenceContainer) { + container[Columns.id] = id + container[Columns.title] = title + container[Columns.favorite] = isFavorite + container[Columns.latitude] = coordinate.latitude + container[Columns.longitude] = coordinate.longitude + } + + /// Update record ID after a successful insertion + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} +``` + +
+ +
+ Subclass the Record class + +See the [Record class](#record-class) for more information. + +```swift +class Place: Record { + var id: Int64? + var title: String + var isFavorite: Bool + var coordinate: CLLocationCoordinate2D + + init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) { + self.id = id + self.title = title + self.isFavorite = isFavorite + self.coordinate = coordinate + super.init() + } + + /// The table name + override class var databaseTableName: String { + return "place" + } + + /// The table columns + enum Columns: String, ColumnExpression { + case id, title, favorite, latitude, longitude + } + + /// Creates a record from a database row + required init(row: Row) { + id = row[Columns.id] + title = row[Columns.title] + isFavorite = row[Columns.favorite] + coordinate = CLLocationCoordinate2D( + latitude: row[Columns.latitude], + longitude: row[Columns.longitude]) + super.init(row: row) + } + + /// The values persisted in the database + override func encode(to container: inout PersistenceContainer) { + container[Columns.id] = id + container[Columns.title] = title + container[Columns.favorite] = isFavorite + container[Columns.latitude] = coordinate.latitude + container[Columns.longitude] = coordinate.longitude + } + + /// Update record ID after a successful insertion + override func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} +``` + +
+ + ## List of Record Methods This is the list of record methods, along with their required protocols. The [Record](#record-class) adopts all these protocols, and adds a few extra methods. @@ -2771,54 +3152,54 @@ This is the list of record methods, along with their required protocols. The [Re | Method | Protocols | Notes | | ------ | --------- | :---: | | **Core Methods** | | | -| `init(row:)` | [RowConvertible](#rowconvertible-protocol) | | -| `Type.databaseTableName` | [TableMapping](#tablemapping-protocol) | | -| `Type.databaseSelection` | [TableMapping](#tablemapping-protocol) | [*](#columns-selected-by-a-request) | -| `Type.persistenceConflictPolicy` | [Persistable](#persistable-protocol) | [*](#conflict-resolution) | -| `record.encode(to:)` | [Persistable](#persistable-protocol) | | -| `record.didInsert(with:for:)` | [Persistable](#persistable-protocol) | | +| `init(row:)` | [FetchableRecord] | | +| `Type.databaseTableName` | [TableRecord] | | +| `Type.databaseSelection` | [TableRecord] | [*](#columns-selected-by-a-request) | +| `Type.persistenceConflictPolicy` | [PersistableRecord] | [*](#conflict-resolution) | +| `record.encode(to:)` | [PersistableRecord] | | +| `record.didInsert(with:for:)` | [PersistableRecord] | | | **Insert and Update Records** | | | -| `record.insert(db)` | [Persistable](#persistable-protocol) | | -| `record.save(db)` | [Persistable](#persistable-protocol) | | -| `record.update(db)` | [Persistable](#persistable-protocol) | | -| `record.update(db, columns:...)` | [Persistable](#persistable-protocol) | | -| `record.updateChanges(db, from:...)` | [Persistable](#persistable-protocol) | | -| `record.updateChanges(db)` | [Record](#record-class) | | +| `record.insert(db)` | [PersistableRecord] | | +| `record.save(db)` | [PersistableRecord] | | +| `record.update(db)` | [PersistableRecord] | | +| `record.update(db, columns:...)` | [PersistableRecord] | | +| `record.updateChanges(db, from:...)` | [PersistableRecord] | [*](#record-comparison) | +| `record.updateChanges(db)` | [Record](#record-class) | [*](#record-comparison) | | **Delete Records** | | | -| `record.delete(db)` | [Persistable](#persistable-protocol) | | -| `Type.deleteOne(db, key:...)` | [Persistable](#persistable-protocol) | ¹ | -| `Type.deleteAll(db)` | [Persistable](#persistable-protocol) | | -| `Type.deleteAll(db, keys:...)` | [Persistable](#persistable-protocol) | ¹ | -| `Type.filter(...).deleteAll(db)` | [Persistable](#persistable-protocol) | ² | +| `record.delete(db)` | [PersistableRecord] | | +| `Type.deleteOne(db, key:...)` | [PersistableRecord] | ¹ | +| `Type.deleteAll(db)` | [PersistableRecord] | | +| `Type.deleteAll(db, keys:...)` | [PersistableRecord] | ¹ | +| `Type.filter(...).deleteAll(db)` | [PersistableRecord] | ² | | **Check Record Existence** | | | -| `record.exists(db)` | [Persistable](#persistable-protocol) | | +| `record.exists(db)` | [PersistableRecord] | | | **Convert Record to Dictionary** | | | -| `record.databaseDictionary` | [Persistable](#persistable-protocol) | | +| `record.databaseDictionary` | [PersistableRecord] | | | **Count Records** | | | -| `Type.fetchCount(db)` | [TableMapping](#tablemapping-protocol) | | -| `Type.filter(...).fetchCount(db)` | [TableMapping](#tablemapping-protocol) | ² | +| `Type.fetchCount(db)` | [TableRecord] | | +| `Type.filter(...).fetchCount(db)` | [TableRecord] | ² | | **Fetch Record [Cursors](#cursors)** | | | -| `Type.fetchCursor(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | | -| `Type.fetchCursor(db, keys:...)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | ¹ | -| `Type.fetchCursor(db, sql)` | [RowConvertible](#rowconvertible-protocol) | ³ | -| `Type.fetchCursor(statement)` | [RowConvertible](#rowconvertible-protocol) | ⁴ | -| `Type.filter(...).fetchCursor(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | ² | +| `Type.fetchCursor(db)` | [FetchableRecord] & [TableRecord] | | +| `Type.fetchCursor(db, keys:...)` | [FetchableRecord] & [TableRecord] | ¹ | +| `Type.fetchCursor(db, sql)` | [FetchableRecord] | ³ | +| `Type.fetchCursor(statement)` | [FetchableRecord] | ⁴ | +| `Type.filter(...).fetchCursor(db)` | [FetchableRecord] & [TableRecord] | ² | | **Fetch Record Arrays** | | | -| `Type.fetchAll(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | | -| `Type.fetchAll(db, keys:...)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | ¹ | -| `Type.fetchAll(db, sql)` | [RowConvertible](#rowconvertible-protocol) | ³ | -| `Type.fetchAll(statement)` | [RowConvertible](#rowconvertible-protocol) | ⁴ | -| `Type.filter(...).fetchAll(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | ² | +| `Type.fetchAll(db)` | [FetchableRecord] & [TableRecord] | | +| `Type.fetchAll(db, keys:...)` | [FetchableRecord] & [TableRecord] | ¹ | +| `Type.fetchAll(db, sql)` | [FetchableRecord] | ³ | +| `Type.fetchAll(statement)` | [FetchableRecord] | ⁴ | +| `Type.filter(...).fetchAll(db)` | [FetchableRecord] & [TableRecord] | ² | | **Fetch Individual Records** | | | -| `Type.fetchOne(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | | -| `Type.fetchOne(db, key:...)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | ¹ | -| `Type.fetchOne(db, sql)` | [RowConvertible](#rowconvertible-protocol) | ³ | -| `Type.fetchOne(statement)` | [RowConvertible](#rowconvertible-protocol) | ⁴ | -| `Type.filter(...).fetchOne(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | ² | -| **[Changes Tracking](#changes-tracking)** | | | -| `record.databaseEqual(...)` | [Persistable](#persistable-protocol) | | -| `record.databaseChanges(from:...)` | [Persistable](#persistable-protocol) | | -| `record.updateChanges(db, from:...)` | [Persistable](#persistable-protocol) | | +| `Type.fetchOne(db)` | [FetchableRecord] & [TableRecord] | | +| `Type.fetchOne(db, key:...)` | [FetchableRecord] & [TableRecord] | ¹ | +| `Type.fetchOne(db, sql)` | [FetchableRecord] | ³ | +| `Type.fetchOne(statement)` | [FetchableRecord] | ⁴ | +| `Type.filter(...).fetchOne(db)` | [FetchableRecord] & [TableRecord] | ² | +| **[Record Comparison]** | | | +| `record.databaseEquals(...)` | [PersistableRecord] | | +| `record.databaseChanges(from:...)` | [PersistableRecord] | | +| `record.updateChanges(db, from:...)` | [PersistableRecord] | | | `record.hasDatabaseChanges` | [Record](#record-class) | | | `record.databaseChanges` | [Record](#record-class) | | | `record.updateChanges(db)` | [Record](#record-class) | | @@ -2842,13 +3223,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? ``` @@ -2859,9 +3240,9 @@ The Query Interface **The query interface lets you write pure Swift instead of SQL:** ```swift -try dbQueue.inDatabase { db in +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) @@ -2879,13 +3260,13 @@ You need to open a [database connection](#database-connections) before you can q Please bear in mind that the query interface can not generate all possible SQL queries. You may also *prefer* writing SQL, and this is just OK. From little snippets to full queries, your SQL skills are welcome: ```swift -try dbQueue.inDatabase { db in +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) @@ -2894,7 +3275,7 @@ try dbQueue.inDatabase { db in .fetchCount(db) // Delete (with SQL) - try db.execute("DELETE FROM wines WHERE corked") + try db.execute("DELETE FROM wine WHERE corked") } ``` @@ -2911,6 +3292,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 @@ -2926,15 +3308,15 @@ Once granted with a [database connection](#database-connections), you can setup ### Create Tables ```swift -// CREATE TABLE places ( -// id INTEGER PRIMARY KEY, +// 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 - t.column("id", .integer).primaryKey() +try db.create(table: "place") { t in + t.autoIncrementedPrimaryKey("id") t.column("title", .text) t.column("favorite", .boolean).notNull().defaults(to: false) t.column("longitude", .double).notNull() @@ -2944,13 +3326,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**: @@ -2962,6 +3338,10 @@ try db.create(table: "example") { t in ... } try db.create(table: "example", temporary: true, ifNotExists: true) { t in ``` +> :bulb: **Tip**: database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, 'httpRequest'. +> +> This will help you using [Associations](Documentation/AssociationsBasics.md) when you need them. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration. + **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 @@ -2988,16 +3368,30 @@ Define **not null** columns, and set **default** values: Use an individual column as **primary**, **unique**, or **foreign key**. When defining a foreign key, the referenced column is the primary key of the referenced table (unless you specify otherwise): ```swift - // id INTEGER PRIMARY KEY, - t.column("id", .integer).primaryKey() + // id INTEGER PRIMARY KEY AUTOINCREMENT, + t.autoIncrementedPrimaryKey("id") + + // uuid TEXT PRIMARY KEY, + t.column("uuid", .text).primaryKey() // 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: +> +> ```swift +> try db.create(table: "example") { t in +> t.autoIncrementedPrimaryKey("id") +> ... +> } +> ``` +> +> The reason for this recommendation is that auto-incremented primary keys prevent the reuse of ids. This prevents your app or [database observation tools](#database-changes-observation) to think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not. + **Create an index** on the column: ```swift @@ -3041,10 +3435,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) } ``` @@ -3086,7 +3480,7 @@ let players = try request.fetchAll(db) // [Player] let count = try request.fetchCount(db) // Int ``` -All requests start from **a type** that adopts the `TableMapping` protocol, such as a `Record` subclass (see [Records](#records)): +All requests start from **a type** that adopts the `TableRecord` protocol, such as a `Record` subclass (see [Records](#records)): ```swift class Player : Record { ... } @@ -3099,12 +3493,23 @@ let idColumn = Column("id") let nameColumn = Column("name") ``` +You can also declare column enums, if you prefer: + +```swift +// Columns.id and Columns.name can be used just as +// idColumn and nameColumn declared above. +enum Columns: String, ColumnExpression { + case id + case name +} +``` + You can now build requests with the following methods: `all`, `none`, `select`, `distinct`, `filter`, `matching`, `group`, `having`, `order`, `reversed`, `limit`. All those methods return another request, which you can further refine by applying another method: `Player.select(...).filter(...).order(...)`. - `all()`, `none()`: the requests for all rows, or no row. ```swift - // SELECT * FROM players + // SELECT * FROM player Player.all() ``` @@ -3113,50 +3518,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' - Citizenship.filter(key: ["playerID": 1, "countryISOCode": "FR"]) + // SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' + Citizenship.filter(key: ["citizenId": 1, "countryCode": "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) ``` @@ -3166,7 +3571,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) @@ -3175,7 +3580,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) @@ -3185,68 +3590,82 @@ 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) ``` + `orderByPrimaryKey()` sorts by primary key: + + ```swift + // SELECT * FROM player ORDER BY id + Player.orderByPrimaryKey() + + // SELECT * FROM country ORDER BY code + Country.orderByPrimaryKey() + + // SELECT * FROM citizenship ORDER BY citizenId, countryCode + Citizenship.orderByPrimaryKey() + ``` + - `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 specified, the result is ordered by rowID in reverse order. + If no ordering was already specified, this method has no effect: ```swift - // SELECT * FROM players ORDER BY _rowid_ DESC + // 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 - + .reversed() // - ignored - .order(scoreColumn) // ORDER BY score .limit(20, offset: 40) // - ignored - .limit(10) // LIMIT 10 ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/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"]) @@ -3259,7 +3678,7 @@ Player By default, query interface requests select all columns: ```swift -// SELECT * FROM players +// SELECT * FROM player let request = Player.all() ``` @@ -3268,34 +3687,34 @@ 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) ``` To specify the default selection for all requests built from a type, define the `databaseSelection` property: ```swift -struct RestrictedPlayer : TableMapping { - static let databaseTableName = "players" +struct RestrictedPlayer : TableRecord { + static let databaseTableName = "player" static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")] } -struct ExtendedPlayer : TableMapping { - static let databaseTableName = "players" +struct ExtendedPlayer : TableRecord { + 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() ``` -> :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. +> :point_up: **Note**: make sure the `databaseSelection` property is explicitly 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. To verify your setup, see the [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) FAQ. ## Expressions @@ -3310,16 +3729,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) ``` @@ -3330,7 +3749,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")) ``` @@ -3341,31 +3760,52 @@ 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 player WHERE (verified AND (score >= 1000) AND (name IS NOT NULL)) + let conditions = [ + verifiedColumn, + scoreColumn >= 1000, + nameColumn != nil] + Player.filter(conditions.joined(operator: .and)) + ``` + + When the sequence is empty, `joined(operator: .and)` returns true, and `joined(operator: .or)` returns false: + + ```swift + // SELECT * FROM player WHERE 1 + Player.filter([].joined(operator: .and)) + + // SELECT * FROM player WHERE 0 + Player.filter([].joined(operator: .or)) + ``` - `BETWEEN`, `IN`, `NOT IN` 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)) ``` @@ -3376,7 +3816,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")) ``` @@ -3391,10 +3831,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)) ``` @@ -3403,7 +3843,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) ``` @@ -3415,13 +3855,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)) ``` @@ -3430,10 +3870,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) ``` @@ -3466,7 +3906,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)) ``` @@ -3495,21 +3935,28 @@ let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) // Player? ``` -**When the selected columns don't fit the source type**, change your target: any other type that adopts the [RowConvertible](#rowconvertible-protocol) protocol, plain [database rows](#fetching-rows), and even [values](#values): +**When the selected columns don't fit the source type**, change your target: any other type that adopts the [FetchableRecord] protocol, plain [database rows](#fetching-rows), and even [values](#values): ```swift -let maxScore = try Player.select(max(scoreColumn)) - .asRequest(of: Int.self) - .fetchOne(db) // Int? +let request = Player.select(max(scoreColumn)) +let maxScore = try Int.fetchOne(db, request) // Int? -let row = try Player.select(min(scoreColumn), max(scoreColumn)) - .asRequest(of: Row.self) - .fetchOne(db)! +let request = Player.select(min(scoreColumn), max(scoreColumn)) +let row = try Row.fetchOne(db, request)! // Row let minScore = row[0] as Int? let maxScore = row[1] as Int? ``` -More information about `asRequest(of:)` can be found in the [Custom Requests](#custom-requests) chapter. +You may also use the `asRequest(of:)` method, which lets you alter the type of the request itself, and feed database observation tools like [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): + +```swift +let request = Player.select(max(scoreColumn)).asRequest(of: Int.self) +request.rx + .fetchOne(in: dbQueue) + .subscribe(onNext: { maxScore: Int? in + print("Maximum score has changed") + }) +``` ## Fetching By Key @@ -3517,60 +3964,60 @@ More information about `asRequest(of:)` can be found in the [Custom Requests](#c **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' -try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Citizenship? +// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' +try Citizenship.fetchOne(db, key: ["citizenId": 1, "countryCode": "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' -let request = Citizenship.filter(key: ["playerID": 1, "countryISOCode": "FR"]) +// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' +let request = Citizenship.filter(key: ["citizenId": 1, "countryCode": "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? ``` @@ -3591,16 +4038,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) ``` @@ -3608,82 +4055,77 @@ let count = try Player.select(nameColumn, scoreColumn).distinct().fetchCount(db) **Other aggregated values** can also be selected and fetched (see [SQL Functions](#sql-functions)): ```swift -let maxScore = try Player.select(max(scoreColumn)) - .asRequest(of: Int.self) - .fetchOne(db) // Int? +let request = Player.select(max(scoreColumn)) +let maxScore = try Int.fetchOne(db, request) // Int? -let row = try Player.select(min(scoreColumn), max(scoreColumn)) - .asRequest(of: Row.self) - .fetchOne(db)! +let request = Player.select(min(scoreColumn), max(scoreColumn)) +let row = try Row.fetchOne(db, request)! // Row let minScore = row[0] as Int? let maxScore = row[1] as Int? ``` -More information about `asRequest(of:)` can be found in the [Custom Requests](#custom-requests) chapter. - ## Delete Requests **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) ``` -> :point_up: **Note** Deletion methods are only available for records that adopts the [Persistable](#persistable-protocol) protocol. +> :point_up: **Note** Deletion methods are only available for records that adopts the [PersistableRecord] protocol. **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' -try Citizenship.deleteOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) +// DELETE FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' +try Citizenship.deleteOne(db, key: ["citizenId": 1, "countryCode": "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"]) ``` ## Custom Requests -Until now, we have seen [requests](#requests) created from any type that adopts the [TableMapping](#tablemapping-protocol) protocol: +Until now, we have seen [requests](#requests) created from any type that adopts the [TableRecord] protocol: ```swift let request = Player.all() // QueryInterfaceRequest ``` -Those requests of type `QueryInterfaceRequest` can fetch, count, and delete records: +Those requests of type `QueryInterfaceRequest` can fetch and count: ```swift try request.fetchCursor(db) // A Cursor of Player try request.fetchAll(db) // [Player] try request.fetchOne(db) // Player? try request.fetchCount(db) // Int -try request.deleteAll(db) ``` **When the query interface can not generate the SQL you need**, you can still fallback to [raw SQL](#fetch-queries): @@ -3693,100 +4135,124 @@ try request.deleteAll(db) try Player.fetchAll(db, "SELECT ...") // [Player] ``` -But you may prefer to bring some elegance back in, and build custom requests on top of the `Request` and `TypedRequest` protocols: +But you may prefer to bring some elegance back in, and build custom requests: ```swift // No custom SQL in sight try Player.customRequest().fetchAll(db) // [Player] ``` -Unlike QueryInterfaceRequest, these protocols can't delete. But they can fetch and count: +Custom requests also grant [FetchedRecordsController](#fetchedrecordscontroller) and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) the ability to observe the database: ```swift -/// The protocol for all types that define a way to fetch database rows. -protocol Request { - /// A tuple that contains a prepared statement that is ready to be - /// executed, and an eventual row adapter. +Player.customRequest(...).rx + .fetchAll(in: dbQueue) + .subscribe(onNext: { players: [Player] in + print("Players have changed") + }) +``` + +- [FetchRequest Protocol](#fetchrequest-protocol) +- [Building Custom Requests](#building-custom-requests) +- [Fetching From Custom Requests](#fetching-from-custom-requests) + + +### FetchRequest Protocol + +**FetchRequest** is the protocol for all requests that run from a single select statement, and know how fetched rows should be interpreted: + +```swift +protocol FetchRequest { + /// The type that tells how fetched rows should be decoded + associatedtype RowDecoder + + /// A tuple that contains a prepared statement, and an eventual row adapter. func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) /// The number of rows fetched by the request. func fetchCount(_ db: Database) throws -> Int -} - -/// The protocol for requests that know how to decode database rows. -protocol TypedRequest : Request { - /// The type that can convert raw database rows to fetched values - associatedtype RowDecoder + + /// The database region that the request looks into. + func databaseRegion(_ db: Database) throws -> DatabaseRegion } ``` -The `prepare` method returns a tuple made of a [prepared statement](#prepared-statements) and an optional [row adapter](#row-adapters). The prepared statement tells which SQL query should be executed. The row adapter can help *presenting* the fetched rows in the way expected by the row consumers (we'll see an example below). +When the `RowDecoder` associated type is [Row](#fetching-rows), or a [value](#value-queries), or a type that conforms to [FetchableRecord], the request can fetch: see [Fetching From Custom Requests](#fetching-from-custom-requests) below. + +The `prepare` method returns a prepared statement and an optional row adapter. The [prepared statement](#prepared-statements) tells which SQL query should be executed. The row adapter helps presenting the fetched rows in the way expected by the row decoders (see [row adapter](#row-adapters)). The `fetchCount` method has a default implementation that builds a correct but naive SQL query from the statement returned by `prepare`: `SELECT COUNT(*) FROM (...)`. Adopting types can refine the counting SQL by customizing their `fetchCount` implementation. +The `databaseRegion` method is involved in [database observation](#database-changes-observation). It is given a default implementation, based on the statement returned by `prepare`. For more information, see [DatabaseRegion](https://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/DatabaseRegion.html), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB). -### Fetching From Custom Requests - -A Request doesn't know what to fetch, but it can feed the [fetching methods](#fetching-methods) of any fetchable type ([Row](#fetching-rows), [value](#value-queries), or [record](#records)): +The FetchRequest protocol is adopted, for example, by [query interface requests](#requests): ```swift -let request: Request = ... -try Row.fetchCursor(db, request) // A Cursor of Row -try String.fetchAll(db, request) // [String] -try Player.fetchOne(db, request) // Player? -``` - -On top of that, a TypedRequest knows exactly what it has to do when its RowDecoder associated type can decode database rows ([Row](#fetching-rows) itself, [values](#value-queries), or [records](#records)): - -```swift -let request = ... // Some TypedRequest that fetches Player -try request.fetchCursor(db) // A Cursor of Player -try request.fetchAll(db) // [Player] -try request.fetchOne(db) // Player? +// A FetchRequest whose RowDecoder associated type is Player: +let request = Player.all() ``` ### Building Custom Requests -**To build custom requests**, you can create your own type that adopts the protocols, or derive requests from other requests, or use one of the built-in concrete types: +**To build custom requests**, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts the [FetchRequest](#fetchrequest-protocol) protocol. -- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.10/Structs/SQLRequest.html): a Request built from raw SQL -- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.10/Structs/AnyRequest.html): a type-erased Request -- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.10/Structs/AnyTypedRequest.html): a type-erased TypedRequest +- [SQLRequest](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: + + ```swift + extension Player { + static func filter(color: Color) -> SQLRequest { + return SQLRequest( + "SELECT * FROM player WHERE color = ?" + arguments: [color]) + } + } + + // [Player] + try Player.filter(color: .red).fetchAll(db) + ``` + +- The `asRequest(of:)` method changes the type fetched by the request: -Use the `asRequest(of:)` method to define the type fetched by the request: + ```swift + // Int? + let maxScore = Player.select(max(Column("score"))) + .asRequest(of: Int.self) + .fetchOne(db) + ``` + +- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. + +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request. + + +### Fetching From Custom Requests + +A type adopting [FetchRequest](#fetchrequest-protocol) knows exactly what it has to do when its RowDecoder associated type can decode database rows ([Row](#fetching-rows) itself, [values](#value-queries), or [FetchableRecord]): ```swift -let maxScore = Player.select(max(scoreColumn)) - .asRequest(of: Int.self) - .fetchOne(db) +let rowRequest = ... // Some FetchRequest that fetches Row +try request.fetchCursor(db) // A cursor of rows -extension Player { - static func customRequest(...) -> AnyTypedRequest { - let request = SQLRequest("SELECT ...", arguments: ...) - return request.asRequest(of: Player.self) - } -} +let playerRequest = ... // Some FetchRequest that fetches Player +try request.fetchAll(db) // [Player] -try Player.customRequest(...).fetchAll(db) // [Player] -try Player.customRequest(...).fetchCount(db) // Int +let intRequest = ... // Some FetchRequest that fetches Int +try request.fetchOne(db) // Int? ``` -Finally, use the `adapted(_:)` method to ease the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for more information. +For example: +```swift +let playerRequest = SQLRequest( + "SELECT * FROM player WHERE color = ?" + arguments: [color]) +try request.fetchAll(db) // [Player] +``` -Application Tools -================= +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. -On top of the APIs described above, GRDB provides a toolkit for applications. While none of those are mandatory, all of them help dealing with the database: - -- [Migrations](#migrations): Transform your database as your application evolves. -- [Full-Text Search](#full-text-search): Perform efficient and customizable full-text searches. -- [Joined Queries Support](#joined-queries-support): Consume complex joined queries. -- [Database Changes Observation](#database-changes-observation): Perform post-commit and post-rollback actions. -- [FetchedRecordsController](#fetchedrecordscontroller): Automated tracking of changes in a query results, plus UITableView animations. -- [Encryption](#encryption): Encrypt your database with SQLCipher. -- [Backup](#backup): Dump the content of a database to another. +The RowDecoder type associated with the FetchRequest does not have to be Row, DatabaseValueConvertible, or FetchableRecord. See the [Customized Decoding of Database Rows](#customized-decoding-of-database-rows) chapter for more information. ## Migrations @@ -3800,22 +4266,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 // ... // } ``` @@ -3844,6 +4310,15 @@ try migrator.migrate(dbQueue, upTo: "v1") // fatal error: database is already migrated beyond migration "v1" ``` +Check if a migration has been applied: + +```swift +let appliedMigrations = try migrator.appliedMigrations(in: dbQueue) +if appliedMigrations.contains("v2") { + // "v2" migration has been applied +} +``` + ### Advanced Database Schema Changes @@ -3852,15 +4327,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 - t.column("id", .integer).primaryKey() + 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") } ``` @@ -3873,7 +4348,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") @@ -3882,7 +4357,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 @@ -3891,7 +4366,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]) ``` @@ -3964,13 +4439,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") } ``` @@ -3980,13 +4455,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") @@ -3997,7 +4472,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="", @@ -4007,7 +4482,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" @@ -4031,7 +4506,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 @@ -4056,7 +4531,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 } ``` @@ -4070,7 +4545,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 } ``` @@ -4082,7 +4557,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) } @@ -4148,11 +4623,11 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html): +FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, - "SELECT * FROM documents WHERE content MATCH ?", + "SELECT * FROM document WHERE content MATCH ?", arguments: [pattern]) ``` @@ -4176,8 +4651,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") } ``` @@ -4187,13 +4662,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") @@ -4204,7 +4679,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', @@ -4213,7 +4688,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" @@ -4236,7 +4711,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(...) @@ -4262,7 +4737,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) } @@ -4277,7 +4752,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 } ``` @@ -4291,7 +4766,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 @@ -4335,11 +4810,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: @@ -4363,11 +4838,11 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html): +FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, - "SELECT * FROM documents WHERE documents MATCH ?", + "SELECT * FROM document WHERE document MATCH ?", arguments: [pattern]) ``` @@ -4385,7 +4860,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 @@ -4407,7 +4882,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) @@ -4415,8 +4890,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") @@ -4442,26 +4917,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 > ``` @@ -4476,7 +4951,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) ``` @@ -4484,11 +4959,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]) ``` @@ -4528,18 +5003,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. @@ -4547,10 +5022,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 ... ``` @@ -4558,11 +5033,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 [RowConvertible](#rowconvertible-protocol) records 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). @@ -4581,32 +5056,32 @@ To split rows, we will use [row adapters](#row-adapters). Row adapters adapt row At the very beginning, there is an SQL query: ```swift -try dbQueue.inDatabase { db in +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: @@ -4664,20 +5139,20 @@ Our introduction above has introduced important techniques. It uses [row adapter But we may want to make it more usable and robust: 1. It's generally easier to consume records than raw rows. -2. Joined records not always need all columns from a table (see `TableMapping.databaseSelection` in [Columns Selected by a Request](#columns-selected-by-a-request)). +2. Joined records not always need all columns from a table (see `TableRecord.databaseSelection` in [Columns Selected by a Request](#columns-selected-by-a-request)). 3. Building row adapters is long and error prone. -To address the first bullet, let's define a record that holds our player, optional team, and maximum score. Since it can decode database rows, it adopts the [RowConvertible](#rowconvertible-protocol) protocol: +To address the first bullet, let's define a record that holds our player, optional team, and maximum score. Since it can decode database rows, it adopts the [FetchableRecord] protocol: ```swift -struct Item { +struct PlayerInfo { var player: Player var team: Team? var maxScore: Int } -/// Item can decode rows: -extension Item: RowConvertible { +/// PlayerInfo can decode rows: +extension PlayerInfo: FetchableRecord { private enum Scopes { static let player = "player" static let team = "team" @@ -4691,34 +5166,47 @@ extension Item: RowConvertible { } ``` -Let's now write the method that fetches items: +Let's now write the method that fetches PlayerInfo records: ```swift -extension Item { - static func fetchAll(_ db: Database) throws -> [Item] { +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 provide an alias: `SELECT \(Players.selectionSQL(alias: "p")) FROM players p ...` +> :point_up: **Note**: you may also use SQL table aliases: +> +> ```swift +> let sql = """ +> SELECT +> \(Player.selectionSQL(alias: "p")), +> \(Team.selectionSQL(alias: "t")), +> MAX(r.score) AS maxScore +> 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: [ @@ -4730,29 +5218,29 @@ 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 items: +And finally, we can fetch player infos: ```swift - return try Item.fetchAll(db, sql, adapter: adapter) + return try PlayerInfo.fetchAll(db, sql, adapter: adapter) } } ``` -And when your app needs to fetch items, it now reads: +And when your app needs to fetch player infos, it now reads: ```swift -// Fetch items -let items = try dbQueue.inDatabase { db in - try Item.fetchAll(db) +// Fetch player infos +let playerInfos = try dbQueue.read { db in + try PlayerInfo.fetchAll(db) } ``` > :bulb: In this chapter, we have learned: > -> - how to define a `RowConvertible` record that consumes rows fetched from a joined query. +> - how to define a `FetchableRecord` record that consumes rows fetched from a joined query. > - how to use `selectionSQL` and `numberOfSelectedColumns` in order to deal with nested record types that define custom selection. > - how to use `splittingRowAdapters` in order to streamline the definition of row slices. > - how to gather all relevant methods and constants in a record type, fully responsible of its relationship with the database. @@ -4760,19 +5248,19 @@ let items = try dbQueue.inDatabase { db in ### Splitting Rows, the Request Way -The `Item.fetchAll` method [above](#splitting-rows-the-record-way) directly fetches records. It's all good, but in order to profit from [database observation](#database-changes-observation) with [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), you'll need a [custom request](#custom-requests) that defines a database query. +The `PlayerInfo.fetchAll` method [above](#splitting-rows-the-record-way) directly fetches records. It's all good, but in order to profit from [database observation](#database-changes-observation) with [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), you'll need a [custom request](#custom-requests) that defines a database query. -It is recommended that your read the previous paragraphs before you dive in this sample code. We start with the same Item record as above: +It is recommended that you read the previous paragraphs before you dive in this sample code. We start with the same PlayerInfo record as above: ```swift -struct Item { +struct PlayerInfo { var player: Player var team: Team? var maxScore: Int } -/// Item can decode rows: -extension Item: RowConvertible { +/// PlayerInfo can decode rows: +extension PlayerInfo: FetchableRecord { private enum Scopes { static let player = "player" static let team = "team" @@ -4789,32 +5277,31 @@ extension Item: RowConvertible { Now we write a method that returns a request, and build the fetching method on top of that request: ```swift -extension Item { - /// The request for all items - static func all() -> AnyTypedRequest { +extension PlayerInfo { + /// The request for all player infos + static func all() -> AdaptedFetchRequest> { let sql = """ 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 + return SQLRequest(sql).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ Player.numberOfSelectedColumns(db), Team.numberOfSelectedColumns(db)]) return ScopeAdapter([ Scopes.player: adapters[0], Scopes.team: adapters[1]]) - } - .asRequest(of: Item.self) + } } - /// Fetches all items - static func fetchAll(_ db: Database) throws -> [Item] { + /// Fetches all player infos + static func fetchAll(_ db: Database) throws -> [PlayerInfo] { return try all().fetchAll(db) } } @@ -4823,16 +5310,16 @@ extension Item { It is now time to use our request: ```swift -// Fetch items -let items = try dbQueue.inDatabase { db in - try Item.fetchAll(db) +// Fetch player infos +let playerInfos = try dbQueue.read { db in + try PlayerInfo.fetchAll(db) } -// Track items with RxRGDB: -Item.all() +// Track player infos with RxRGDB: +PlayerInfo.all() .rx.fetchAll(in: dbQueue) - .subscribe(onNext: { items: [Item] in - print("items have changed") + .subscribe(onNext: { playerInfos: [PlayerInfo] in + print("Player infos have changed") }) ``` @@ -4846,63 +5333,60 @@ Item.all() You can consume complex joined queries with Codable records as well. As a demonstration, we'll rewrite the [above](#splitting-rows-the-request-way) sample code: ```swift -struct Player: Decodable, RowConvertible, TableMapping { - static let databaseTableName = "players" +struct Player: Decodable, FetchableRecord, TableRecord { var id: Int64 var name: String } -struct Team: Decodable, RowConvertible, TableMapping { - static let databaseTableName = "teams" +struct Team: Decodable, FetchableRecord, TableRecord { var id: Int64 var name: String var color: Color } -struct Item: Decodable, RowConvertible { +struct PlayerInfo: Decodable, FetchableRecord { var player: Player var team: Team? var maxScore: Int } -extension Item { - /// The request for all items - static func all() -> AnyTypedRequest { +extension PlayerInfo { + /// The request for all player infos + static func all() -> AdaptedFetchRequest> { let sql = """ 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 + return SQLRequest(sql).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ Player.numberOfSelectedColumns(db), Team.numberOfSelectedColumns(db)]) return ScopeAdapter([ CodingKeys.player.stringValue: adapters[0], CodingKeys.team.stringValue: adapters[1]]) - } - .asRequest(of: Item.self) + } } - /// Fetches all items - static func fetchAll(_ db: Database) throws -> [Item] { + /// Fetches all player infos + static func fetchAll(_ db: Database) throws -> [PlayerInfo] { return try all().fetchAll(db) } } -// Fetch items -let items = try dbQueue.inDatabase { db in - try Item.fetchAll(db) +// Fetch player infos +let playerInfos = try dbQueue.read { db in + try PlayerInfo.fetchAll(db) } -// Track items with RxRGDB: -Item.all() +// Track player infos with RxRGDB: +PlayerInfo.all() .rx.fetchAll(in: dbQueue) - .subscribe(onNext: { items: [Item] in - print("items have changed") + .subscribe(onNext: { playerInfos: [PlayerInfo] in + print("Player infos have changed") }) ``` @@ -4930,18 +5414,17 @@ Database observation requires that a single [database queue](#database-queues) o ### After Commit Hook -**When your application needs to make sure a database transaction has been successfully committed before it executes some work, use the `Database.afterNextTransactionCommit(_:)` method.** +When your application needs to make sure a specific database transaction has been successfully committed before it executes some work, use the `Database.afterNextTransactionCommit(_:)` method. Its closure argument is called right after database changes have been successfully written to disk: ```swift -dbQueue.inTransaction { db in +try dbQueue.write { db in db.afterNextTransactionCommit { db in print("success") } ... - return .commit // prints "success" -} +} // prints "success" ``` The closure runs in a protected dispatch queue, serialized with all database updates. @@ -4977,15 +5460,13 @@ func startMonitoring(_ db: Database, region: CLRegion) throws { The method above won't trigger the location manager if the transaction is eventually rollbacked (explicitly, or because of an error), as in the sample code below: ```swift -try dbQueue.inTransaction { db in +try dbQueue.write { db in // success try startMonitoring(db, region) // On error, the transaction is rollbacked, the region is not inserted, and // the location manager is not invoked. try failableMethod(db) - - return .commit } ``` @@ -5046,23 +5527,27 @@ By default, database holds weak references to its transaction observers: they ar > :point_up: **Note**: the changes that are not notified are changes to internal system tables (such as `sqlite_master`), changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite). -Notified changes are not actually written to disk until `databaseDidCommit` is called. On the other side, `databaseDidRollback` confirms their invalidation: +Notified changes are not actually written to disk until the [transaction](#transactions-and-savepoints) commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation: ```swift -try dbQueue.inTransaction { db in +try dbQueue.write { db in try db.execute("INSERT ...") // 1. didChange try db.execute("UPDATE ...") // 2. didChange - return .commit // 3. willCommit, 4. didCommit -} +} // 3. willCommit, 4. didCommit try dbQueue.inTransaction { db in try db.execute("INSERT ...") // 1. didChange try db.execute("UPDATE ...") // 2. didChange return .rollback // 3. didRollback } + +try dbQueue.write { db in + try db.execute("INSERT ...") // 1. didChange + throw SomeError() +} // 2. didRollback ``` -Database statements that are executed outside of an explicit transaction do not drop off the radar: +Database statements that are executed outside of any transaction do not drop off the radar: ```swift try dbQueue.inDatabase { db in @@ -5118,18 +5603,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. } } ``` @@ -5139,14 +5624,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") } } } @@ -5173,14 +5658,14 @@ class PureTransactionObserver: TransactionObserver { **You can specify how long an observer is notified of database changes and transactions.** -The `remove(transactionObserver:)` method explicitely stops notifications, at any time: +The `remove(transactionObserver:)` method explicitly stops notifications, at any time: ```swift // From a database queue or pool: dbQueue.remove(transactionObserver: observer) // From a database connection: -dbQueue.inDatabase { db in // or dbPool.write +dbQueue.inDatabase { db in db.remove(transactionObserver: observer) } ``` @@ -5212,14 +5697,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() @@ -5257,7 +5742,7 @@ protocol TransactionObserverType : class { It looks and behaves very much like [Core Data's NSFetchedResultsController](https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsController_Class/). -Given a fetch request, and a type that adopts the [RowConvertible](#rowconvertible-protocol) protocol, such as a subclass of the [Record](#record-class) class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record. +Given a fetch request, and a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](#record-class) class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record. See [GRDBDemoiOS](DemoApps/GRDBDemoiOS/GRDBDemoiOS) for an sample app that uses FetchedRecordsController. @@ -5278,12 +5763,12 @@ See also [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), an [RxSwift](https When you initialize a fetched records controller, you provide the following mandatory information: - A [database connection](#database-connections) -- The type of the fetched records. It must be a type that adopts the [RowConvertible](#rowconvertible-protocol) protocol, such as a subclass of the [Record](#record-class) class +- The type of the fetched records. It must be a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](#record-class) class - A fetch request ```swift class Player : Record { ... } -let dbQueue = DatabaseQueue(...) // Or DatabasePool +let dbQueue = DatabaseQueue(...) // or DatabasePool // Using a Request from the Query Interface: let controller = FetchedRecordsController( @@ -5293,21 +5778,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 countryCode = ?", 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 """) ``` @@ -5324,18 +5809,26 @@ try controller.performFetch() In general, FetchedRecordsController is designed to respond to changes at *the database layer*, by [notifying](#the-changes-notifications) when *database rows* change location or values. -Changes are not reflected until they are applied in the database by a successful [transaction](#transactions-and-savepoints). Transactions can be explicit, or implicit: +Changes are not reflected until they are applied in the database by a successful [transaction](#transactions-and-savepoints): ```swift -try dbQueue.inTransaction { db in +// One transaction +try dbQueue.write { db in // or dbPool.write try player1.insert(db) try player2.insert(db) - return .commit // Explicit transaction } -try dbQueue.inDatabase { db in - try player1.insert(db) // Implicit transaction - try player2.insert(db) // Implicit transaction +// One transaction +try dbQueue.inTransaction { db in // or dbPool.writeInTransaction + try player1.insert(db) + try player2.insert(db) + return .commit +} + +// Two transactions +try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction + try player1.insert(db) + try player2.insert(db) } ``` @@ -5443,10 +5936,10 @@ try controller.performFetch() FetchedRecordsController let you feed table and collection views, and keep them up-to-date with the database content. -For nice animated updates, a fetched records controller needs to recognize identical records between two different result sets. When records adopt the [TableMapping](#tablemapping-protocol) protocol, they are automatically compared according to their primary key: +For nice animated updates, a fetched records controller needs to recognize identical records between two different result sets. When records adopt the [TableRecord] protocol, they are automatically compared according to their primary key: ```swift -class Player : TableMapping { ... } +class Player : TableRecord { ... } let controller = FetchedRecordsController( dbQueue, request: Player.all()) @@ -5563,7 +6056,7 @@ When the database itself can be read and modified from [any thread](#database-co ```swift // Change database on the main thread: -try dbQueue.inDatabase { db in +try dbQueue.write { db in try Player(...).insert(db) } // Here callbacks have not been called yet. @@ -5600,7 +6093,7 @@ Alternatively, perform a manual installation of GRDB and SQLCipher: ```sh cd [GRDB directory] - git checkout v2.10.0 + git checkout v3.0.0-beta.1 git submodule update --init SQLCipher/src ``` @@ -5667,20 +6160,6 @@ The `backup` method blocks the current thread until the destination database con When the source is a [database pool](#database-pools), concurrent writes can happen during the backup. Those writes may, or may not, be reflected in the backup, but they won't trigger any error. -Good To Know -============ - -This chapter covers general topics that you should be aware of. - -- [Avoiding SQL Injection](#avoiding-sql-injection) -- [Error Handling](#error-handling) -- [Unicode](#unicode) -- [Memory Management](#memory-management) -- [Data Protection](#data-protection) -- [Concurrency](#concurrency) -- [Performance](#performance) - - ## Avoiding SQL Injection SQL injection is a technique that lets an attacker nuke your database. @@ -5693,8 +6172,9 @@ Here is an example of code that is vulnerable to SQL injection: ```swift // BAD BAD BAD +let id = 1 let name = textField.text -try dbQueue.inDatabase { db in +try dbQueue.write { db in try db.execute("UPDATE students SET name = '\(name)' WHERE id = \(id)") } ``` @@ -5707,19 +6187,35 @@ DROP TABLE students; --' WHERE id = 1 ``` -To avoid those problems, **never embed raw values in your SQL queries**. The only correct technique is to provide [arguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html) to your SQL queries: +To avoid those problems, **never embed raw values in your SQL queries**. The only correct technique is to provide [arguments](#executing-updates) to your raw SQL queries: ```swift -// Good let name = textField.text -try dbQueue.inDatabase { db in +try dbQueue.write { db in + // Good try db.execute( "UPDATE students SET name = ? WHERE id = ?", arguments: [name, id]) + + // Just as good + try db.execute( + "UPDATE students SET name = :name WHERE id = :id", + arguments: ["name": name, "id": id]) } ``` -See [Executing Updates](#executing-updates) for more information on statement arguments. +When you use [records](#records) and the [query interface](#the-query-interface), GRDB always prevents SQL injection for you: + +```swift +let id = 1 +let name = textField.text +try dbQueue.write { db in + if var student = try Student.fetchOne(db, key: id) { + student.name = name + try student.update(db) + } +} +``` ## Error Handling @@ -5742,7 +6238,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) @@ -5755,11 +6251,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 } @@ -5803,7 +6299,7 @@ do { ### PersistenceError -**PersistenceError** is thrown by the [Persistable](#persistable-protocol) protocol, in a single case: when the `update` method could not find any row to update: +**PersistenceError** is thrown by the [PersistableRecord] protocol, in a single case: when the `update` method could not find any row to update: ```swift do { @@ -5859,11 +6355,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) @@ -5873,8 +6369,8 @@ They uncover programmer errors, false assumptions, and prevent misuses. Here are ```swift // fatal error: Database methods are not reentrant. - dbQueue.inDatabase { db in - dbQueue.inDatabase { db in + dbQueue.write { db in + dbQueue.write { db in ... } } @@ -5997,7 +6493,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) @@ -6016,7 +6512,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) ``` @@ -6066,7 +6562,7 @@ Data protection can be enabled [globally](https://developer.apple.com/library/co You can also explicitly protect a database, by configuring its enclosing *directory*. This will not only protect the database file, but also all [temporary files](https://www.sqlite.org/tempfiles.html) created by SQLite (including the persistent `.shm` and `.wal` files created by [database pools](#database-pools)). -For example, to explicitely use [complete](https://developer.apple.com/reference/foundation/fileprotectiontype/1616200-complete) protection: +For example, to explicitly use [complete](https://developer.apple.com/reference/foundation/fileprotectiontype/1616200-complete) protection: ```swift // Paths @@ -6124,7 +6620,7 @@ GRDB ships with three concurrency modes: - :bowtie: **Guarantee 2: reads are always isolated**. This means that they are guaranteed an immutable view of the last committed state of the database, and that you can perform subsequent fetches without fearing eventual concurrent writes to mess with your application logic: ```swift - try dbPool.read { db in // or dbQueue.inDatabase { ... } + try dbPool.read { db in // or dbQueue.read // Guaranteed to be equal let count1 = try Player.fetchCount(db) let count2 = try Player.fetchCount(db) @@ -6149,12 +6645,12 @@ Those guarantees hold as long as you follow three rules: ```swift // SAFE CONCURRENCY - func currentUser(_ db: Database) throws -> User? { + func fetchCurrentUser(_ db: Database) throws -> User? { return try User.fetchOne(db) } // dbQueue is a singleton defined somewhere in your app - let user = try dbQueue.inDatabase { db in // or dbPool.read { ... } - try currentUser(db) + let user = try dbQueue.read { db in // or dbPool.read + try fetchCurrentUser(db) } // UNSAFE CONCURRENCY @@ -6162,7 +6658,7 @@ Those guarantees hold as long as you follow three rules: // the database. func currentUser() throws -> User? { let dbQueue = try DatabaseQueue(...) - return try dbQueue.inDatabase { db in + return try dbQueue.read { db in try User.fetchOne(db) } } @@ -6175,7 +6671,7 @@ Those guarantees hold as long as you follow three rules: ```swift // SAFE CONCURRENCY - try dbPool.read { db in // or dbQueue.inDatabase { ... } + try dbPool.read { db in // or dbQueue.read // Guaranteed to be equal: let count1 = try Place.fetchCount(db) let count2 = try Place.fetchCount(db) @@ -6207,19 +6703,26 @@ Those guarantees hold as long as you follow three rules: On that last example, see [Advanced DatabasePool](#advanced-databasepool) if you look after extra performance. -- :point_up: **Rule 3**: When you perform several modifications of the database that temporarily put the database in an inconsistent state, group those modifications within a [transaction](#transactions-and-savepoints): +- :point_up: **Rule 3**: When you perform several modifications of the database that temporarily put the database in an inconsistent state, make sure those modifications are grouped within a [transaction](#transactions-and-savepoints). ```swift // SAFE CONCURRENCY - try dbPool.writeInTransaction { db in // or dbQueue.inTransaction { ... } + try dbPool.write { db in // or dbQueue.write + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + } + + // SAFE CONCURRENCY + try dbPool.writeInTransaction { db in // or dbQueue.inTransaction try Credit(destinationAccout, amount).insert(db) try Debit(sourceAccount, amount).insert(db) return .commit } // UNSAFE CONCURRENCY - try dbPool.write { db in // or dbQueue.inDatabase { ... } + try dbPool.writeWithoutTransaction { db in try Credit(destinationAccout, amount).insert(db) + // <- Concurrent dbPool.read sees a partial db update here try Debit(sourceAccount, amount).insert(db) } ``` @@ -6278,14 +6781,15 @@ try dbPool.read { db in } ``` -The correct solution is the `readFromCurrentState` method, which must be called from within a write block: +The correct solution is the `readFromCurrentState` method, which must be called from within a write block, outside of any transaction: ```swift // CORRECT -try dbPool.write { db in +try dbPool.writeWithoutTransaction { db in // Increment the number of players try Player(...).insert(db) + // <- not in a transaction here try dbPool.readFromCurrentState { db // Read the number of players. The writer queue has been unlocked :-) let count = try Player.fetchCount(db) @@ -6298,7 +6802,7 @@ try dbPool.write { db in The closure can run concurrently with eventual updates performed after `readFromCurrentState`: those updates won't be visible from within the closure. In the example below, the number of players is guaranteed to be non-zero, even though it is fetched concurrently with the player deletion: ```swift -try dbPool.write { db in +try dbPool.writeWithoutTransaction { db in // Increment the number of players try Player(...).insert(db) @@ -6343,11 +6847,12 @@ let playerCount = try snapshot.read { db in } ``` -When you want to control the latest committed changes seen by a snapshot, create it from the pool's writer protected dispatch queue: +When you want to control the latest committed changes seen by a snapshot, create it from the pool's writer protected dispatch queue, outside of any transaction: ```swift -let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in +let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in try Player.deleteAll() + // <- not in a transaction here return dbPool.makeSnapshot() } // <- Other threads may modify the database here @@ -6369,7 +6874,7 @@ try snapshot2.read { db in ### DatabaseWriter and DatabaseReader Protocols -Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. +Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. These protocols provide a unified API that lets you write safe concurrent code that targets all three concurrency modes. @@ -6425,7 +6930,7 @@ DatabaseWriter and DatabaseReader fuel, for example: Reentrant database accesses make it very easy to break the second [safety rule](#guarantees-and-rules), which says: "group related statements within a single call to a DatabaseQueue or DatabasePool database access method.". Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring. - Reentrant methods have been introduced in order to support [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), a set of reactive extensions to GRDB based on [RxSwift](https://github.com/ReactiveX/RxSwift) that need precise scheduling. + There is a single valid use case for reentrant methods, which is when you are unable to control database access scheduling. - **`unsafeReentrantWrite`** @@ -6434,7 +6939,7 @@ DatabaseWriter and DatabaseReader fuel, for example: Reentrant calls are allowed: ```swift - dbQueue.inDatabase { db1 in + dbQueue.write { db1 in // No "Database methods are not reentrant" fatal error: dbQueue.unsafeReentrantWrite { db2 in dbQueue.unsafeReentrantWrite { db3 in @@ -6446,7 +6951,7 @@ DatabaseWriter and DatabaseReader fuel, for example: Reentrant database accesses make it very easy to break the second [safety rule](#guarantees-and-rules), which says: "group related statements within a single call to a DatabaseQueue or DatabasePool database access method.". Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring. - Reentrant methods have been introduced in order to support [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), a set of reactive extensions to GRDB based on [RxSwift](https://github.com/ReactiveX/RxSwift) that need precise scheduling. + There is a single valid use case for reentrant methods, which is when you are unable to control database access scheduling. ### Dealing with External Connections @@ -6463,7 +6968,7 @@ If you absolutely need multiple connections, then: - Read about [isolation in SQLite](https://www.sqlite.org/isolation.html) - Learn about [locks and transactions](https://www.sqlite.org/lang_transaction.html) - Become a master of the [WAL mode](https://www.sqlite.org/wal.html) -- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.10/Structs/Configuration.html) +- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/Configuration.html) - [Ask questions](https://github.com/groue/GRDB.swift/issues) @@ -6498,7 +7003,7 @@ Most GRBD APIs are [synchronous](#database-connections). Spawning them into para ```swift DispatchQueue.global().async { - dbQueue.inDatabase { db in + dbQueue.write { db in // Perform database work } DispatchQueue.main.async { @@ -6514,18 +7019,25 @@ Performing multiple updates to the database is much faster when executed inside ```swift // Inefficient -try dbQueue.inDatabase { db in +try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction for player in players { try player.insert(db) } } // Efficient -try dbQueue.inTransaction { db in +try dbQueue.write { db in // or dbPool.write for player in players { try player.insert(db) } - return .Commit +} + +// Efficient +try dbQueue.inTransaction { db in // or dbPool.writeInTransaction + for player in players { + try player.insert(db) + } + return .commit } ``` @@ -6538,10 +7050,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) ``` @@ -6585,7 +7097,7 @@ if player.hasDatabaseChanges { } ``` -See [changes tracking](#changes-tracking) for more information. +See [Record Comparison] for more information. ### Performance tip: learn about SQL strengths and weaknesses @@ -6601,10 +7113,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) } ``` @@ -6613,10 +7125,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) ``` @@ -6667,7 +7179,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() { @@ -6688,7 +7200,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 @@ -6763,17 +7275,17 @@ Database accesses that run in background threads postpone the closing of connect When you want to debug a request that does not deliver the expected results, you may want to print the SQL that is actually executed. -Use the `asSQLRequest` method: +You can turn your request into a `SQLRequest` instance: ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in let request = Wine .filter(Column("origin") == "Burgundy") .order(Column("price") - let sqlRequest = try request.asSQLRequest(db) + 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"] } @@ -6783,26 +7295,26 @@ Another option is to setup a tracing function that will print out all SQL reques ```swift var config = Configuration() -config.trace = { print("SQL: \($0)") } // Prints all SQL statements +config.trace = { print($0) } // Prints all SQL statements let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) -try dbQueue.inDatabase { db in +try dbQueue.read { db in let wines = Wine .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 } ``` ### Generic parameter 'T' could not be inferred -You may get this error when using DatabaseQueue.inDatabase, DatabasePool.read, or DatabasePool.write: +You may get this error when using the `read` and `write` methods of database queues and pools: ```swift // Generic parameter 'T' could not be inferred -let x = try dbQueue.inDatabase { db in +let x = try dbQueue.read { db in let result = try String.fetchOne(db, ...) return result } @@ -6814,7 +7326,7 @@ The general workaround is to explicitly declare the type of the closure result: ```swift // General Workaround -let string = try dbQueue.inDatabase { db -> String? in +let string = try dbQueue.read { db -> String? in let result = try String.fetchOne(db, ...) return result } @@ -6824,7 +7336,7 @@ You can also, when possible, write a single-line closure: ```swift // Single-line closure workaround: -let string = try dbQueue.inDatabase { db in +let string = try dbQueue.read { db in try String.fetchOne(db, ...) } ``` @@ -6863,6 +7375,30 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [Matt Greenfield](https://github.com/sobri909), [David Hart](https://github.com/hartbit), [@kluufger](https://github.com/kluufger), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy), [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB. +- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [Matt Greenfield](https://github.com/sobri909), [David Hart](https://github.com/hartbit), [@kluufger](https://github.com/kluufger), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Florent Pillet](http://github.com/fpillet), [@pocketpixels](https://github.com/pocketpixels), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy), [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [Mathieu "Kali" Poumeyrol](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. + +Legacy +====== + +#### Changes Tracking + +This chapter has been renamed [Record Comparison]. + +#### Persistable Protocol + +This protocol has been renamed [PersistableRecord] in GRDB 3.0. + +#### RowConvertible Protocol + +This protocol has been renamed [FetchableRecord] in GRDB 3.0. + +#### TableMapping Protocol + +This protocol has been renamed [TableRecord] in GRDB 3.0. + +[FetchableRecord]: #fetchablerecord-protocol +[PersistableRecord]: #persistablerecord-protocol +[Record Comparison]: #record-comparison +[TableRecord]: #tablerecord-protocol diff --git a/TODO.md b/TODO.md index 611ac36eb..a5076c93f 100644 --- a/TODO.md +++ b/TODO.md @@ -17,24 +17,35 @@ GRDB 3.0 -- [ ] Rename "changes tracking" (ambiguous with database observation) to "record comparison" -- [ ] Refactor SQL generation and rowId extraction from expression on the visitor pattern. Provide more documentation for literal expressions which become the only way to extend GRDB. -- [ ] Hide useless scheduling methods behind protocols : https://forums.swift.org/t/discouraging-protocol-methods-on-concrete-values/8737/4?u=gwendal.roue -- [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970 -- [ ] Do one of those two: - 1. Make save() impossible to customize: remove it from Persistable protocol, and remove performSave() from tne public API. - 2. Open Record.save(), and have RecordBox.save() forward this method to its underlying type. -- [ ] Not sure: Make the MutablePersistable.update(_:columns:) method mutating (as support for an updatedDate column) - [ ] Not sure: type safety - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? -- [ ] Rename Request to FetchRequest, because Request is a bad name: https://github.com/swift-server/http/pull/7#issuecomment-308448528 -- [ ] Rename RowConvertible, TableMapping, MutablePersistable and Persistable so that their names contain Record: FetchableRecord, TableRecord, MutablePersistableRecord, PersistableRecord? -- [ ] Not sure: Consider introducing RowDecodable and RowEncodable on top of FetchableRecord and MutablePersistableRecord. This would allow keeping fetching and persistence methods private in some files. -- [ ] Drop IteratorCursor, use AnyCursor instead -- [ ] Drop TypedRequest, have FetchRequest defaults to Row requests. -- [ ] Rename columnCount -> numberOfColumns -- [ ] Try to remove double Persistable/MutablePersistable protocols: Would non-mutating Record methods help? +- [ ] HiddenColumnsAdapter +- [ ] Find a common name for DatabaseQueue.inDatabase / DatabasePool.writeWithoutTransaction: + - writeRaw, rawWrite, pureWrite, plainWrite, directWrite, basicWrite + - 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 +- [ ] Joins and full-text tables +- [ ] DatabaseRequest should be part of RxGRDB, as DatabaseRegionConvertible. Rename fetchedRegion(_:) to databaseRegion(_:). SelectStatementRequest hasn't much traction left: remove? +- [ ] Provide a way to extend both QueryInterfaceRequest and Association: + + ```swift + extension ??? where ??? = Player { + func filter(color: Color) -> Self { + return filter(Column("color") == color) + } + } + let players = Player.all().filter(color: .red) + let players = Player.filter(color: .red) // Possible ?? + let teamPlayers = Team.players.filter(color: .red) + ``` +- [ ] From vapor: How do they use [keypaths](https://docs.vapor.codes/3.0/fluent/querying/) for filtering? + Not sure @@ -89,6 +100,7 @@ Requires recompilation of SQLite: Reading list: +- Documentation generation: https://twitter.com/jckarter/status/987525569196650496: cmark is the implementation the Swift compiler uses for doc comments etc. - VACUUM (https://blogs.gnome.org/jnelson/) - http://www.sqlite.org/intern-v-extern-blob.html - https://sqlite.org/sharedcache.html diff --git a/Tests/GRDBTests/AnyCursorTests.swift b/Tests/GRDBTests/AnyCursorTests.swift index 611bf94c4..7a8a86675 100644 --- a/Tests/GRDBTests/AnyCursorTests.swift +++ b/Tests/GRDBTests/AnyCursorTests.swift @@ -42,9 +42,9 @@ class AnyCursorTests: GRDBTestCase { } func testAnyCursorFromCursor() { - let base = IteratorCursor([0, 1]) + let base = AnyCursor([0, 1]) // This helper function makes sure AnyCursor initializer accepts any cursor, - // and not only IteratorCursor: + // and not only AnyCursor: func makeAnyCursor(_ cursor: C) -> AnyCursor where C.Element == Int { return AnyCursor(cursor) } @@ -75,4 +75,20 @@ class AnyCursorTests: GRDBTestCase { XCTFail() } } + + func testAnyCursorFromIterator() { + let cursor = AnyCursor(iterator: [0, 1].makeIterator()) + XCTAssertEqual(try cursor.next()!, 0) + XCTAssertEqual(try cursor.next()!, 1) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + + func testAnyCursorFromSequence() { + let cursor = AnyCursor([0, 1]) + XCTAssertEqual(try cursor.next()!, 0) + XCTAssertEqual(try cursor.next()!, 1) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } } 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..3f619c67b --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -0,0 +1,876 @@ +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) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"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) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"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) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"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) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"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) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"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) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"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) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"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) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"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) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"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) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"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) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"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)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"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)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"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)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"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)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"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)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"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)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"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)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"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)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"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)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 3) AND (\"custom\".\"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)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 3) AND (\"custom\".\"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 new file mode 100644 index 000000000..22334f88f --- /dev/null +++ b/Tests/GRDBTests/ColumnExpressionTests.swift @@ -0,0 +1,141 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +class ColumnExpressionTests: GRDBTestCase { + + func testRawColumnExpression() throws { + struct Player: TableRecord, FetchableRecord, PersistableRecord { + var id: Int64 + var name: String + var score: Int + + struct Column: ColumnExpression { + var name: String + } + + enum Columns { + static let id = Player.Column(name: "id") + static let name = Player.Column(name: "name") + static let score = Player.Column(name: "score") + } + + static let databaseTableName = "players" + // Test databaseSelection + static let databaseSelection: [SQLSelectable] = [Columns.id, Columns.name, Columns.score] + + init(row: Row) { + // Test row subscript + id = row[Columns.id] + name = row[Columns.name] + score = row[Columns.score] + } + + func encode(to container: inout PersistenceContainer) { + // Test container subscript + container[Columns.id] = id + container[Columns.name] = name + container[Columns.score] = score + } + + static var testRequest: QueryInterfaceRequest { + // Test expression derivation + return filter(Columns.name != nil).order(Columns.score.desc) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "players") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name") + t.column("score") + } + + // Test rowId column identification + try XCTAssertEqual(Player.filter(key: 1).databaseRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.Columns.id == 1).databaseRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(1 == Player.Columns.id).databaseRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).databaseRegion(db).description, "players(id,name,score)[1,2]") + try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "players(id,name,score)[1,2,3]") + + // Test specific column updates + let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000]) + try? player.update(db, columns: [Player.Columns.name, Player.Columns.score]) + XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") + + // Test FTS3 match expression + let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo")) + let literal = expression.literal + XCTAssertEqual(literal.sql, "(\"name\" MATCH ?)") + XCTAssertEqual(literal.arguments, ["foo"]) + } + } + + func testRawRepresentableColumnExpression() throws { + struct Player: TableRecord, FetchableRecord, PersistableRecord { + var id: Int64 + var name: String + var score: Int + + enum Columns: String, ColumnExpression { + case id, name, score + } + + static let databaseTableName = "players" + // Test databaseSelection + static let databaseSelection: [SQLSelectable] = [Columns.id, Columns.name, Columns.score] + + init(row: Row) { + // Test row subscript + id = row[Columns.id] + name = row[Columns.name] + score = row[Columns.score] + } + + func encode(to container: inout PersistenceContainer) { + // Test container subscript + container[Columns.id] = id + container[Columns.name] = name + container[Columns.score] = score + } + + static var testRequest: QueryInterfaceRequest { + // Test expression derivation + return filter(Columns.name != nil).order(Columns.score.desc) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "players") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name") + t.column("score") + } + + // Test rowId column identification + try XCTAssertEqual(Player.filter(key: 1).databaseRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.Columns.id == 1).databaseRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(1 == Player.Columns.id).databaseRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).databaseRegion(db).description, "players(id,name,score)[1,2]") + try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "players(id,name,score)[1,2,3]") + + // Test specific column updates + let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000]) + try? player.update(db, columns: [Player.Columns.name, Player.Columns.score]) + XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") + + // Test FTS3 match expression + let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo")) + let literal = expression.literal + XCTAssertEqual(literal.sql, "(\"name\" MATCH ?)") + XCTAssertEqual(literal.arguments, ["foo"]) + } + } +} diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 882d246ea..1d999c64f 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -77,6 +77,7 @@ private class UserDatabaseWriter : DatabaseWriter { func add(collation: DatabaseCollation) { } func remove(collation: DatabaseCollation) { } func write(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() } + func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() } func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() } func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { preconditionFailure() } } @@ -110,47 +111,45 @@ private class UserFTS5WrapperTokenizer : FTS5WrapperTokenizer { } #endif -// MARK: - MutablePersistable +// MARK: - MutablePersistableRecord -private struct UserMutablePersistable1 : MutablePersistable { - static let databaseTableName = "UserMutablePersistable1" +private struct UserMutablePersistableRecord1 : MutablePersistableRecord { + static let databaseTableName = "UserMutablePersistableRecord1" func encode(to container: inout PersistenceContainer) { } } -private class UserMutablePersistable2 : MutablePersistable { - static let databaseTableName = "UserMutablePersistable2" +private class UserMutablePersistableRecord2 : MutablePersistableRecord { + static let databaseTableName = "UserMutablePersistableRecord2" func encode(to container: inout PersistenceContainer) { } } -// MARK: - Persistable +// MARK: - PersistableRecord -private struct UserPersistable1 : Persistable { - static let databaseTableName = "UserPersistable1" +private struct UserPersistableRecord1 : PersistableRecord { + static let databaseTableName = "UserPersistableRecord1" func encode(to container: inout PersistenceContainer) { } } -private class UserPersistable2 : Persistable { - static let databaseTableName = "UserPersistable2" +private class UserPersistableRecord2 : PersistableRecord { + static let databaseTableName = "UserPersistableRecord2" func encode(to container: inout PersistenceContainer) { } } -// MARK: - Request +// MARK: - FetchRequest -private struct UserRequest1 : Request { +private struct UserRowRequest : FetchRequest { + struct CustomType { } + typealias RowDecoder = CustomType func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() } } -private class UserRequest2 : Request { - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() } -} +// MARK: - FetchableRecord -// MARK: - RowConvertible - -private struct UserRowConvertible1 : RowConvertible { +private struct UserFetchableRecord1 : FetchableRecord { init(row: Row) { } } -private class UserRowConvertible2 : RowConvertible { +private class UserFetchableRecord2 : FetchableRecord { required init(row: Row) { } } @@ -164,27 +163,14 @@ private class UserStatementColumnConvertible2 : StatementColumnConvertible { required init(sqliteStatement: SQLiteStatement, index: Int32) { } } -// MARK: - TableMapping +// MARK: - TableRecord -private struct UserTableMapping1 : TableMapping { - static let databaseTableName = "UserTableMapping1" +private struct UserTableRecord1 : TableRecord { + static let databaseTableName = "UserTableRecord1" } -private class UserTableMapping2 : TableMapping { - static let databaseTableName = "UserTableMapping2" -} - -// MARK: - TypedRequest - -private struct UserTypedRequest1 : TypedRequest { - struct CustomType { } - typealias RowDecoder = CustomType - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() } -} - -private class UserTypedRequest2 : TypedRequest { - typealias RowDecoder = T - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() } +private class UserTableRecord2 : TableRecord { + static let databaseTableName = "UserTableRecord2" } // MARK: - TransactionObserver diff --git a/Tests/GRDBTests/CursorTests.swift b/Tests/GRDBTests/CursorTests.swift index 81debde5d..c69411c3b 100644 --- a/Tests/GRDBTests/CursorTests.swift +++ b/Tests/GRDBTests/CursorTests.swift @@ -12,15 +12,15 @@ private struct TestError : Error { } class CursorTests: GRDBTestCase { func testContainsEquatable() { - XCTAssertTrue(try IteratorCursor([1, 2]).contains(1)) - XCTAssertFalse(try IteratorCursor([1, 2]).contains(3)) + XCTAssertTrue(try AnyCursor([1, 2]).contains(1)) + XCTAssertFalse(try AnyCursor([1, 2]).contains(3)) } func testContainsClosure() { - XCTAssertTrue(try IteratorCursor([1, 2]).contains { $0 == 1 }) - XCTAssertFalse(try IteratorCursor([1, 2]).contains { $0 == 3 }) + XCTAssertTrue(try AnyCursor([1, 2]).contains { $0 == 1 }) + XCTAssertFalse(try AnyCursor([1, 2]).contains { $0 == 3 }) do { - _ = try IteratorCursor([1, 2]).contains { _ -> Bool in throw TestError() } + _ = try AnyCursor([1, 2]).contains { _ -> Bool in throw TestError() } XCTFail() } catch is TestError { } catch { @@ -29,10 +29,10 @@ class CursorTests: GRDBTestCase { } func testDropLast() { - XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(0) == [1, 2, 3, 4, 5]) - XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(2) == [1, 2, 3]) - XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(10) == []) - XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast() == [1, 2, 3, 4]) + XCTAssertTrue(try AnyCursor([1, 2, 3, 4, 5]).dropLast(0) == [1, 2, 3, 4, 5]) + XCTAssertTrue(try AnyCursor([1, 2, 3, 4, 5]).dropLast(2) == [1, 2, 3]) + XCTAssertTrue(try AnyCursor([1, 2, 3, 4, 5]).dropLast(10) == []) + XCTAssertTrue(try AnyCursor([1, 2, 3, 4, 5]).dropLast() == [1, 2, 3, 4]) } func testContainsIsLazy() { @@ -55,8 +55,8 @@ class CursorTests: GRDBTestCase { } func testFirst() { - XCTAssertEqual(try IteratorCursor([1, 2]).first { $0 == 1 }!, 1) - XCTAssertTrue(try IteratorCursor([1, 2]).first { $0 == 3 } == nil) + XCTAssertEqual(try AnyCursor([1, 2]).first { $0 == 1 }!, 1) + XCTAssertTrue(try AnyCursor([1, 2]).first { $0 == 3 } == nil) } func testFirstIsLazy() { @@ -78,24 +78,15 @@ class CursorTests: GRDBTestCase { } } - #if swift(>=4.1) func testCompactMap() { - let cursor = IteratorCursor(["1", "foo", "2"]).compactMap { Int($0) } + 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 = IteratorCursor(["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 = IteratorCursor([1, 2]) + let cursor = AnyCursor([1, 2]) var ints: [Int] = [] try cursor.forEach { ints.append($0) } XCTAssertEqual(ints, [1, 2]) @@ -121,66 +112,66 @@ class CursorTests: GRDBTestCase { func testJoinedWithSeparator() throws { do { - let x = try IteratorCursor([String]()).joined() + let x = try AnyCursor([String]()).joined() XCTAssertEqual(x, "") } do { - let x = try IteratorCursor([String]()).joined(separator: "><") + let x = try AnyCursor([String]()).joined(separator: "><") XCTAssertEqual(x, "") } do { - let x = try IteratorCursor(["foo"]).joined() + let x = try AnyCursor(["foo"]).joined() XCTAssertEqual(x, "foo") } do { - let x = try IteratorCursor(["foo"]).joined(separator: "><") + let x = try AnyCursor(["foo"]).joined(separator: "><") XCTAssertEqual(x, "foo") } do { - let x = try IteratorCursor(["foo", "bar", "baz"]).joined() + let x = try AnyCursor(["foo", "bar", "baz"]).joined() XCTAssertEqual(x, "foobarbaz") } do { - let x = try IteratorCursor(["foo", "bar", "baz"]).joined(separator: "><") + let x = try AnyCursor(["foo", "bar", "baz"]).joined(separator: "><") XCTAssertEqual(x, "foo>), 1) + XCTAssertEqual(try AnyCursor([1, 2, 3]).max(), 3) + XCTAssertEqual(try AnyCursor([1, 2, 3]).max(by: >), 1) } func testMin() { - XCTAssertEqual(try IteratorCursor([1, 2, 3]).min(), 1) - XCTAssertEqual(try IteratorCursor([1, 2, 3]).min(by: >), 3) + XCTAssertEqual(try AnyCursor([1, 2, 3]).min(), 1) + XCTAssertEqual(try AnyCursor([1, 2, 3]).min(by: >), 3) } func testReduce() throws { - let cursor = IteratorCursor([1, 2]) + let cursor = AnyCursor([1, 2]) let squareSum = try cursor.reduce(0) { (acc, int) in acc + int * int } XCTAssertEqual(squareSum, 5) } func testReduceInto() throws { - let cursor = IteratorCursor([1, 2]) + let cursor = AnyCursor([1, 2]) let squareSum = try cursor.reduce(into: 0) { (acc, int) in acc += int * int } XCTAssertEqual(squareSum, 5) } func testSuffix() throws { do { - let cursor = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = AnyCursor([1, 2, 3, 4, 5]) let suffix = try cursor.suffix(0) XCTAssertTrue(suffix == []) } do { - let cursor = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = AnyCursor([1, 2, 3, 4, 5]) let suffix = try cursor.suffix(2) XCTAssertTrue(suffix == [4, 5]) } do { - let cursor = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = AnyCursor([1, 2, 3, 4, 5]) let suffix = try cursor.suffix(10) XCTAssertTrue(suffix == [1, 2, 3, 4, 5]) } diff --git a/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift b/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift index a1bf82a11..c663af6fd 100644 --- a/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift +++ b/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift @@ -47,7 +47,7 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { class Witness { } let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in var transactionCount = 0 weak var deallocationWitness: Witness? = nil do { @@ -89,7 +89,7 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { class Witness { } let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in var transactionCount = 0 try db.execute(startSQL) 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/DatabaseCollationTests.swift b/Tests/GRDBTests/DatabaseCollationTests.swift index 2e8f4bdab..04297a1db 100644 --- a/Tests/GRDBTests/DatabaseCollationTests.swift +++ b/Tests/GRDBTests/DatabaseCollationTests.swift @@ -22,9 +22,16 @@ class DatabaseCollationTests: GRDBTestCase { try db.execute("INSERT INTO strings VALUES (7, 'Z')") try db.execute("INSERT INTO strings VALUES (8, 'z')") - XCTAssertEqual( - try Int.fetchAll(db, "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"), - [1,3,2,6,7,4,5,8]) + // Swift 4.2 and Swift 4.1 don't sort strings in the same way + if "z" < "à" { + XCTAssertEqual( + try Int.fetchAll(db, "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"), + [1,3,2,6,7,4,8,5]) + } else { + XCTAssertEqual( + try Int.fetchAll(db, "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"), + [1,3,2,6,7,4,5,8]) + } XCTAssertEqual( try Int.fetchAll(db, "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.caseInsensitiveCompare.name), id"), [1,3,2,4,6,5,7,8]) diff --git a/Tests/GRDBTests/DatabaseErrorTests.swift b/Tests/GRDBTests/DatabaseErrorTests.swift index 45fd6b4f6..986cfa109 100644 --- a/Tests/GRDBTests/DatabaseErrorTests.swift +++ b/Tests/GRDBTests/DatabaseErrorTests.swift @@ -40,7 +40,7 @@ class DatabaseErrorTests: GRDBTestCase { func testDatabaseErrorInTopLevelSavepoint() throws { let dbQueue = try makeDatabaseQueue() do { - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in do { try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) 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/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 6cfaf1850..a582a9e5c 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -31,7 +31,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal") XCTAssertEqual(journalMode, "wal") try db.create(table: "moves") { $0.column("value", .integer) } @@ -42,7 +42,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block1 = { () in let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time - try! dbQueue.inDatabase { db in + try! dbQueue.writeWithoutTransaction { db in try db.execute("BEGIN DEFERRED TRANSACTION") s1.signal() _ = s2.wait(timeout: .distantFuture) @@ -56,7 +56,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block2 = { () in _ = s0.wait(timeout: .distantFuture) // Avoid "database is locked" error: don't open the two databases at the same time let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") - try! dbQueue.inDatabase { db in + try! dbQueue.writeWithoutTransaction { db in _ = s1.wait(timeout: .distantFuture) try db.execute("INSERT INTO moves VALUES (1)") s2.signal() @@ -93,7 +93,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal") XCTAssertEqual(journalMode, "wal") try db.create(table: "moves") { $0.column("value", .integer) } @@ -104,7 +104,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block1 = { () in let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time - try! dbQueue.inDatabase { db in + try! dbQueue.writeWithoutTransaction { db in _ = s1.wait(timeout: .distantFuture) try db.execute("BEGIN DEFERRED TRANSACTION") s2.signal() @@ -119,7 +119,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block2 = { () in _ = s0.wait(timeout: .distantFuture) // Avoid "database is locked" error: don't open the two databases at the same time let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") - try! dbQueue.inDatabase { db in + try! dbQueue.writeWithoutTransaction { db in try db.execute("BEGIN DEFERRED TRANSACTION") s1.signal() _ = s2.wait(timeout: .distantFuture) @@ -158,7 +158,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal") XCTAssertEqual(journalMode, "wal") try db.create(table: "moves") { $0.column("value", .integer) } @@ -169,7 +169,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block1 = { () in let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time - try! dbQueue.inDatabase { db in + try! dbQueue.writeWithoutTransaction { db in try db.execute("BEGIN DEFERRED TRANSACTION") s1.signal() _ = s2.wait(timeout: .distantFuture) @@ -183,7 +183,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block2 = { () in _ = s0.wait(timeout: .distantFuture) // Avoid "database is locked" error: don't open the two databases at the same time let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") - try! dbQueue.inDatabase { db in + try! dbQueue.writeWithoutTransaction { db in _ = s1.wait(timeout: .distantFuture) try db.execute("BEGIN DEFERRED TRANSACTION") try db.execute("INSERT INTO moves VALUES (1)") @@ -215,7 +215,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { func testReadFromPreviousNonWALDatabase() throws { do { let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") try db.execute("INSERT INTO items (id) VALUES (NULL)") } @@ -229,6 +229,31 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } } + func testWriteOpensATransaction() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + XCTAssertTrue(db.isInsideTransaction) + do { + try db.execute("BEGIN DEFERRED TRANSACTION") + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message!, "cannot start a transaction within a transaction") + XCTAssertEqual(error.sql!, "BEGIN DEFERRED TRANSACTION") + XCTAssertEqual(error.description, "SQLite error 1 with statement `BEGIN DEFERRED TRANSACTION`: cannot start a transaction within a transaction") + } + } + } + + func testWriteWithoutTransactionDoesNotOpenATransaction() throws { + let dbPool = try makeDatabasePool() + try dbPool.writeWithoutTransaction { db in + XCTAssertFalse(db.isInsideTransaction) + try db.beginTransaction() + try db.commit() + } + } + func testReadOpensATransaction() throws { let dbPool = try makeDatabasePool() try dbPool.read { db in @@ -256,7 +281,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { // dbPool.read // throws let block1 = { () in - try! dbPool.write { db in + try! dbPool.writeWithoutTransaction { db in try db.execute("PRAGMA locking_mode=EXCLUSIVE") try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") s1.signal() @@ -369,7 +394,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("DELETE FROM items") } } catch { @@ -419,7 +444,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("DELETE FROM items") } try dbPool.checkpoint() @@ -468,7 +493,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block2 = { () in do { _ = s1.wait(timeout: .distantFuture) - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("INSERT INTO items (id) VALUES (NULL)") s2.signal() _ = s3.wait(timeout: .distantFuture) @@ -515,7 +540,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("INSERT INTO items (id) VALUES (NULL)") } try dbPool.checkpoint() @@ -556,7 +581,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block1 = { () in do { - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("INSERT INTO items (id) VALUES (NULL)") s1.signal() _ = s2.wait(timeout: .distantFuture) @@ -686,7 +711,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("DELETE FROM items") } } catch { @@ -736,7 +761,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("DELETE FROM items") } try dbPool.checkpoint() @@ -780,7 +805,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("INSERT INTO items (id) VALUES (NULL)") } try dbPool.checkpoint() @@ -797,7 +822,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { func testReadFromCurrentStateOpensATransaction() throws { let dbPool = try makeDatabasePool() let s = DispatchSemaphore(value: 0) - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try dbPool.readFromCurrentState { db in XCTAssertTrue(db.isInsideTransaction) do { @@ -820,7 +845,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } // Writer Reader - // dbPool.write { + // dbPool.writeWithoutTransaction { // > // dbPool.readFromCurrentState { // < @@ -833,7 +858,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { // } var i: Int! = nil - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try dbPool.readFromCurrentState { db in _ = s1.wait(timeout: .distantFuture) i = try! Int.fetchOne(db, "SELECT COUNT(*) FROM persons")! @@ -849,7 +874,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { func testReadFromCurrentStateError() throws { dbConfiguration.trace = { print($0) } let dbPool = try makeDatabasePool() - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("PRAGMA locking_mode=EXCLUSIVE") try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") do { @@ -879,11 +904,11 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { try db.execute("INSERT INTO t DEFAULT VALUES") } - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.beginTransaction(.deferred) } - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1) } @@ -891,7 +916,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { try db.execute("INSERT INTO t DEFAULT VALUES") } - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1) try db.rollback() try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 2) diff --git a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift index 903de8132..677cefe89 100644 --- a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift +++ b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift @@ -17,7 +17,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { try db.execute("CREATE INDEX foobar ON items(foo, bar)") } - dbPool.write { db in + try dbPool.write { db in // Assert that the writer cache is empty XCTAssertTrue(db.schemaCache.primaryKey("items") == nil) XCTAssertTrue(db.schemaCache.columns(in: "items") == nil) @@ -148,7 +148,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { // table exists: false let block1 = { () in - try! dbPool.write { db in + try! dbPool.writeWithoutTransaction { db in try db.execute("CREATE TABLE foo(id INTEGER PRIMARY KEY)") // warm cache _ = try db.primaryKey("foo") diff --git a/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift b/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift index 3ea611a80..cb3829448 100644 --- a/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift @@ -343,7 +343,7 @@ class ConcurrencyTests: GRDBTestCase { var rows1: [Row]? var rows2: [Row]? queue.async(group: group) { - try! dbQueue2.inDatabase { db in + try! dbQueue2.writeWithoutTransaction { db in _ = s1.wait(timeout: .distantFuture) rows1 = try Row.fetchAll(db, "SELECT * FROM stuffs") s2.signal() diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 23fe4f7dc..93ad7ef8e 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -95,11 +95,11 @@ class DatabaseQueueTests: GRDBTestCase { dbConfiguration.allowsUnsafeTransactions = true let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.beginTransaction() } - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.commit() } } diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index ba0a0f401..4f7d992ee 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -265,19 +265,19 @@ class DatabaseRegionTests : GRDBTestCase { let statement = try db.makeSelectStatement("SELECT foo.name FROM FOO JOIN BAR ON fooId = foo.id") let expectedRegion = DatabaseRegion(table: "foo", columns: ["name", "id"]) .union(DatabaseRegion(table: "bar", columns: ["fooId"])) - XCTAssertEqual(statement.fetchedRegion, expectedRegion) - XCTAssertEqual(statement.fetchedRegion.description, "bar(fooId),foo(id,name)") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "bar(fooId),foo(id,name)") } do { let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM foo") if sqlite3_libversion_number() < 3019000 { let expectedRegion = DatabaseRegion.fullDatabase - XCTAssertEqual(statement.fetchedRegion, expectedRegion) - XCTAssertEqual(statement.fetchedRegion.description, "full database") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "full database") } else { let expectedRegion = DatabaseRegion(table: "foo") - XCTAssertEqual(statement.fetchedRegion, expectedRegion) - XCTAssertEqual(statement.fetchedRegion.description, "foo(*)") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "foo(*)") } } } @@ -287,7 +287,7 @@ class DatabaseRegionTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, a TEXT)") - struct Record: TableMapping { + struct Record: TableRecord { static let databaseTableName = "foo" } @@ -295,156 +295,179 @@ class DatabaseRegionTests : GRDBTestCase { do { let request = Record.all() - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") } do { let request = Record.filter(Column("a") == 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") } do { let request = Record.filter(Column("id") >= 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") } do { let request = Record.filter((Column("id") == 1) || (Column("a") == "foo")) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") } // No rowId do { let request = Record.filter(Column("id") == nil) - try XCTAssertEqual(request.fetchedRegion(db).description, "empty") + try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter(Column("id") === nil) - try XCTAssertEqual(request.fetchedRegion(db).description, "empty") + try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter(nil == Column("id")) - try XCTAssertEqual(request.fetchedRegion(db).description, "empty") + try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter(nil === Column("id")) - try XCTAssertEqual(request.fetchedRegion(db).description, "empty") + try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter((Column("id") == 1) && (Column("id") == 2)) - try XCTAssertEqual(request.fetchedRegion(db).description, "empty") + try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter(key: 1).filter(key: 2) - try XCTAssertEqual(request.fetchedRegion(db).description, "empty") + try XCTAssertEqual(request.databaseRegion(db).description, "empty") } // Single rowId do { let request = Record.filter(Column("id") == 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(Column("id") === 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(Column("id") == 1 && Column("a") == "foo") - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(Column.rowID == 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(1 == Column("id")) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(1 === Column("id")) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(1 === Column.rowID) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(key: 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(key: 1).filter(key: 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(key: 1).filter(Column("a") == "foo") - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } // Multiple rowIds do { let request = Record.filter(Column("id") == 1 || Column.rowID == 2) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2]") } do { let request = Record.filter((Column("id") == 1 && Column("a") == "foo") || Column.rowID == 2) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2]") } do { let request = Record.filter([1, 2, 3].contains(Column("id"))) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") } do { let request = Record.filter([1, 2, 3].contains(Column.rowID)) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") } do { let request = Record.filter(keys: [1, 2, 3]) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") } } } + 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.databaseRegion(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.databaseRegion(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 try db.execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, a TEXT)") - struct Record: TableMapping { + struct Record: TableRecord { static let databaseTableName = "foo" } let request = Record.filter(keys: [1, 2, 3]) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") do { - let derivedRequest: AnyRequest = AnyRequest(request) - try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]") + let derivedRequest: AnyFetchRequest = AnyFetchRequest(request) + try XCTAssertEqual(derivedRequest.databaseRegion(db).description, "foo(a,id)[1,2,3]") } do { - let derivedRequest: AnyTypedRequest = AnyTypedRequest(request) - try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]") - } - do { - let derivedRequest: AnyTypedRequest = request.asRequest(of: Row.self) - try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]") - } - do { - let derivedRequest: AdaptedTypedRequest = request.adapted { db in SuffixRowAdapter(fromIndex: 1) } - try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]") - } - do { - let derivedRequest: AdaptedRequest = AnyRequest(request).adapted { db in SuffixRowAdapter(fromIndex: 1) } - try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]") + let derivedRequest: AdaptedFetchRequest = request.adapted { db in SuffixRowAdapter(fromIndex: 1) } + try XCTAssertEqual(derivedRequest.databaseRegion(db).description, "foo(a,id)[1,2,3]") } do { // SQL request loses region info - let derivedRequest: SQLRequest = try request.asSQLRequest(db) - try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)") + let derivedRequest = try SQLRequest(db, request: request) + try XCTAssertEqual(derivedRequest.databaseRegion(db).description, "foo(a,id)") } } } @@ -483,20 +506,20 @@ class DatabaseRegionTests : GRDBTestCase { do { let statement = try db.makeSelectStatement("SELECT rowid FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"]) - XCTAssertEqual(statement.fetchedRegion, expectedRegion) - XCTAssertEqual(statement.fetchedRegion.description, "foo(ROWID)") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "foo(ROWID)") } do { let statement = try db.makeSelectStatement("SELECT _ROWID_ FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"]) - XCTAssertEqual(statement.fetchedRegion, expectedRegion) - XCTAssertEqual(statement.fetchedRegion.description, "foo(ROWID)") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "foo(ROWID)") } do { let statement = try db.makeSelectStatement("SELECT oID FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"]) - XCTAssertEqual(statement.fetchedRegion, expectedRegion) - XCTAssertEqual(statement.fetchedRegion.description, "foo(ROWID)") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "foo(ROWID)") } } } diff --git a/Tests/GRDBTests/DatabaseSavepointTests.swift b/Tests/GRDBTests/DatabaseSavepointTests.swift index b86fba0cb..64e4dbaa0 100644 --- a/Tests/GRDBTests/DatabaseSavepointTests.swift +++ b/Tests/GRDBTests/DatabaseSavepointTests.swift @@ -59,7 +59,7 @@ class DatabaseSavepointTests: GRDBTestCase { func testIsInsideTransaction() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in XCTAssertFalse(db.isInsideTransaction) try db.inTransaction { XCTAssertTrue(db.isInsideTransaction) @@ -91,7 +91,7 @@ class DatabaseSavepointTests: GRDBTestCase { func testIsInsideTransactionWithImplicitRollback() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.create(table: "test") { t in t.column("value", .integer).unique() } @@ -112,7 +112,7 @@ class DatabaseSavepointTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -143,7 +143,7 @@ class DatabaseSavepointTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -173,7 +173,7 @@ class DatabaseSavepointTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -210,7 +210,7 @@ class DatabaseSavepointTests: GRDBTestCase { observer.reset() sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -247,7 +247,7 @@ class DatabaseSavepointTests: GRDBTestCase { observer.reset() sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -285,7 +285,7 @@ class DatabaseSavepointTests: GRDBTestCase { observer.reset() sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -329,7 +329,7 @@ class DatabaseSavepointTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -359,7 +359,7 @@ class DatabaseSavepointTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -389,7 +389,7 @@ class DatabaseSavepointTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -426,7 +426,7 @@ class DatabaseSavepointTests: GRDBTestCase { observer.reset() sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -463,7 +463,7 @@ class DatabaseSavepointTests: GRDBTestCase { observer.reset() sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -501,7 +501,7 @@ class DatabaseSavepointTests: GRDBTestCase { observer.reset() sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index aa5799a9e..a6fe799e9 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -25,7 +25,7 @@ class DatabaseSnapshotTests: GRDBTestCase { func testSnapshotSeesLatestTransaction() throws { let dbPool = try makeDatabasePool() - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.create(table: "t") { $0.column("id", .integer).primaryKey() } try db.execute("INSERT INTO t DEFAULT VALUES") let snapshot = try dbPool.makeSnapshot() @@ -40,21 +40,6 @@ class DatabaseSnapshotTests: GRDBTestCase { } } - func testSnapshotDoesNotSeeUncommittedTransaction() throws { - let dbPool = try makeDatabasePool() - try dbPool.write { db in - try db.create(table: "t") { $0.column("id", .integer).primaryKey() } - try db.beginTransaction() - try db.execute("INSERT INTO t DEFAULT VALUES") - let snapshot = try dbPool.makeSnapshot() - try db.commit() - try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1) - try snapshot.read { db in - try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 0) - } - } - } - func testSnapshotCreatedOutsideOfWriterQueue() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in diff --git a/Tests/GRDBTests/DatabaseTests.swift b/Tests/GRDBTests/DatabaseTests.swift index 28e47ebf9..91369b7f6 100644 --- a/Tests/GRDBTests/DatabaseTests.swift +++ b/Tests/GRDBTests/DatabaseTests.swift @@ -302,7 +302,7 @@ class DatabaseTests : GRDBTestCase { func testExplicitTransactionManagement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.beginTransaction() XCTAssertEqual(lastSQLQuery, "BEGIN DEFERRED TRANSACTION") try db.rollback() diff --git a/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift index 1e41287a2..8501da8f4 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift @@ -41,8 +41,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchCursor(db, sql)) try test(Fetched.fetchCursor(statement)) - try test(Fetched.fetchCursor(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db)) + try test(Fetched.fetchCursor(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchCursor(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" @@ -50,8 +50,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter)) try test(Fetched.fetchCursor(statement, adapter: adapter)) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db)) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } } @@ -85,16 +85,16 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -117,16 +117,16 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -142,8 +142,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchAll(db, sql)) try test(Fetched.fetchAll(statement)) - try test(Fetched.fetchAll(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db)) + try test(Fetched.fetchAll(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchAll(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" @@ -151,8 +151,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter)) try test(Fetched.fetchAll(statement, adapter: adapter)) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db)) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } } @@ -177,16 +177,16 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -209,16 +209,16 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -235,8 +235,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, 1 WHERE 0" @@ -244,8 +244,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } do { @@ -257,8 +257,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, NULL" @@ -266,8 +266,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } do { @@ -279,8 +279,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, 1" @@ -288,8 +288,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } } @@ -315,16 +315,16 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } @@ -347,16 +347,16 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } @@ -376,8 +376,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Optional.fetchCursor(db, sql)) try test(Optional.fetchCursor(statement)) - try test(Optional.fetchCursor(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchCursor(db)) + try test(Optional.fetchCursor(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchCursor(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" @@ -385,8 +385,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter)) try test(Optional.fetchCursor(statement, adapter: adapter)) - try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchCursor(db)) + try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } } @@ -420,16 +420,16 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Optional.fetchCursor(db, sql), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchCursor(db), sql: sql) + try test(Optional.fetchCursor(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchCursor(db), sql: sql) + try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -452,16 +452,16 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchCursor(db, sql), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchCursor(db), sql: sql) + try test(Optional.fetchCursor(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchCursor(db), sql: sql) + try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -479,8 +479,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Optional.fetchAll(db, sql)) try test(Optional.fetchAll(statement)) - try test(Optional.fetchAll(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchAll(db)) + try test(Optional.fetchAll(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchAll(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" @@ -488,8 +488,8 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter)) try test(Optional.fetchAll(statement, adapter: adapter)) - try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchAll(db)) + try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } } @@ -514,16 +514,16 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Optional.fetchAll(db, sql), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -546,16 +546,16 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchAll(db, sql), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } diff --git a/Tests/GRDBTests/DatabaseValueTests.swift b/Tests/GRDBTests/DatabaseValueTests.swift index ecce04100..2db3b009a 100644 --- a/Tests/GRDBTests/DatabaseValueTests.swift +++ b/Tests/GRDBTests/DatabaseValueTests.swift @@ -120,6 +120,6 @@ class DatabaseValueTests: GRDBTestCase { XCTAssertEqual(databaseValue_Int64.description, "1") XCTAssertEqual(databaseValue_Double.description, "100000.1") XCTAssertEqual(databaseValue_String.description, "\"foo\\n\\t\\r\"") - XCTAssertEqual(databaseValue_Data.description, "3 bytes") // may be fragile + XCTAssertEqual(databaseValue_Data.description, "Data(3 bytes)") // may be fragile } } diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift new file mode 100644 index 000000000..1286ecffb --- /dev/null +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -0,0 +1,131 @@ +import XCTest +#if GRDBCIPHER +import GRDBCipher +#elseif GRDBCUSTOMSQLITE +import GRDBCustomSQLite +#else +import GRDB +#endif + +private struct Author: FetchableRecord, PersistableRecord, Codable { + var id: Int64 + var firstName: String? + var lastName: String? + var country: String + var fullName: String { + return [firstName, lastName] + .compactMap { $0 } + .joined(separator: " ") + } + + static let databaseTableName = "author" + static let books = hasMany(Book.self) + var books: QueryInterfaceRequest { + return request(for: Author.books) + } +} +private struct Book: FetchableRecord, PersistableRecord, Codable { + var id: Int64 + var authorId: Int64 + var title: String + + static let databaseTableName = "book" + static let author = belongsTo(Author.self) + var author: QueryInterfaceRequest { + return request(for: Book.author) + } +} + +private var libraryMigrator: DatabaseMigrator = { + var migrator = DatabaseMigrator() + migrator.registerMigration("library") { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") + t.column("firstName", .text) + t.column("lastName", .text) + t.column("country", .text).notNull() + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorId", .integer).notNull().references("author") + t.column("title", .text).notNull() + } + } + migrator.registerMigration("fixture") { db in + try Author(id: 1, firstName: "Herman", lastName: "Melville", country: "US").insert(db) + try Author(id: 2, firstName: "Marcel", lastName: "Proust", country: "FR").insert(db) + try Book(id: 1, authorId: 1, title: "Moby-Dick").insert(db) + try Book(id: 2, authorId: 2, title: "Du côté de chez Swann").insert(db) + } + return migrator +}() + +// One extension... +extension DerivableRequest where RowDecoder == Author { + func filter(country: String) -> Self { + return filter(Column("country") == country) + } + + func orderByFullName() -> Self { + return order( + Column("lastName").collating(.localizedCaseInsensitiveCompare), + Column("firstName").collating(.localizedCaseInsensitiveCompare)) + } +} + +class DerivableRequestTests: GRDBTestCase { + func testFilter() throws { + let dbQueue = try makeDatabaseQueue() + try libraryMigrator.migrate(dbQueue) + try dbQueue.inDatabase { db in + // ... for two requests (1) + let frenchAuthorNames = try Author.all() + .filter(country: "FR") + .fetchAll(db) + .map { $0.fullName } + XCTAssertEqual(frenchAuthorNames, ["Marcel Proust"]) + + // ... for two requests (2) + let frenchBookTitles = try Book + .joining(required: Book.author.filter(country: "FR")) + .order(Column("title")) + .fetchAll(db) + .map { $0.title } + XCTAssertEqual(frenchBookTitles, ["Du côté de chez Swann"]) + } + } + + func testOrder() throws { + let dbQueue = try makeDatabaseQueue() + try libraryMigrator.migrate(dbQueue) + try dbQueue.inDatabase { db in + // ... for two requests (1) + let authorNames = try Author.all() + .orderByFullName() + .fetchAll(db) + .map { $0.fullName } + XCTAssertEqual(authorNames, ["Herman Melville", "Marcel Proust"]) + + let reversedAuthorNames = try Author.all() + .orderByFullName() + .reversed() + .fetchAll(db) + .map { $0.fullName } + XCTAssertEqual(reversedAuthorNames, ["Marcel Proust", "Herman Melville"]) + + // ... for two requests (2) + let bookTitles = try Book + .joining(required: Book.author.orderByFullName()) + .fetchAll(db) + .map { $0.title } + XCTAssertEqual(bookTitles, ["Moby-Dick", "Du côté de chez Swann"]) + + let reversedBookTitles = try Book + .joining(required: Book.author.orderByFullName()) + .reversed() + .fetchAll(db) + .map { $0.title } + XCTAssertEqual(reversedBookTitles, ["Du côté de chez Swann", "Moby-Dick"]) + } + } +} diff --git a/Tests/GRDBTests/DropFirstCursorTests.swift b/Tests/GRDBTests/DropFirstCursorTests.swift index 889b21c5f..2343305c5 100644 --- a/Tests/GRDBTests/DropFirstCursorTests.swift +++ b/Tests/GRDBTests/DropFirstCursorTests.swift @@ -13,7 +13,7 @@ class DropFirstCursorTests: GRDBTestCase { func testDropFirstCursorFromCursor() throws { do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.dropFirst(0) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 2) @@ -24,7 +24,7 @@ class DropFirstCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.dropFirst(2) try XCTAssertEqual(cursor.next()!, 3) try XCTAssertEqual(cursor.next()!, 4) @@ -33,13 +33,13 @@ class DropFirstCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.dropFirst(10) XCTAssertTrue(try cursor.next() == nil) // end XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.dropFirst() try XCTAssertEqual(cursor.next()!, 2) try XCTAssertEqual(cursor.next()!, 3) @@ -70,7 +70,7 @@ class DropFirstCursorTests: GRDBTestCase { } func testDropFirstChain() throws { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.dropFirst(1).dropFirst(1) try XCTAssertEqual(cursor.next()!, 3) try XCTAssertEqual(cursor.next()!, 4) diff --git a/Tests/GRDBTests/DropWhileCursorTests.swift b/Tests/GRDBTests/DropWhileCursorTests.swift index 63e9b0832..7cbcc336d 100644 --- a/Tests/GRDBTests/DropWhileCursorTests.swift +++ b/Tests/GRDBTests/DropWhileCursorTests.swift @@ -13,7 +13,7 @@ class DropWhileCursorTests: GRDBTestCase { func testDropWhileCursorFromCursor() throws { do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.drop(while: { $0 < 3 }) try XCTAssertEqual(cursor.next()!, 3) try XCTAssertEqual(cursor.next()!, 1) @@ -22,13 +22,13 @@ class DropWhileCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.drop(while: { _ in true }) XCTAssertTrue(try cursor.next() == nil) // end XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.drop(while: { _ in false }) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 2) @@ -39,7 +39,7 @@ class DropWhileCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.drop(while: { _ in throw TestError() }) _ = try cursor.next() XCTFail() diff --git a/Tests/GRDBTests/EnumeratedCursorTests.swift b/Tests/GRDBTests/EnumeratedCursorTests.swift index b89211877..c4625be92 100644 --- a/Tests/GRDBTests/EnumeratedCursorTests.swift +++ b/Tests/GRDBTests/EnumeratedCursorTests.swift @@ -12,7 +12,7 @@ private struct TestError : Error { } class EnumeratedCursorTests: GRDBTestCase { func testEnumeratedCursorFromCursor() throws { - let base = IteratorCursor(["foo", "bar"]) + let base = AnyCursor(["foo", "bar"]) let cursor = base.enumerated() var (n, x) = try cursor.next()! XCTAssertEqual(x, "foo") diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index 1d0404233..f440074f8 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -14,21 +14,21 @@ private struct Book { let body: String } -extension Book : RowConvertible { +extension Book : FetchableRecord { init(row: Row) { - id = row[.rowID] + id = row[Column.rowID] title = row["title"] author = row["author"] body = row["body"] } } -extension Book : MutablePersistable { +extension Book : MutablePersistableRecord { static let databaseTableName = "books" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] func encode(to container: inout PersistenceContainer) { - container[.rowID] = id + container[Column.rowID] = id container["title"] = title container["author"] = author container["body"] = body diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index 107176e91..022554d6d 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -14,21 +14,21 @@ private struct Book { let body: String } -extension Book : RowConvertible { +extension Book : FetchableRecord { init(row: Row) { - id = row[.rowID] + id = row[Column.rowID] title = row["title"] author = row["author"] body = row["body"] } } -extension Book : MutablePersistable { +extension Book : MutablePersistableRecord { static let databaseTableName = "books" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] func encode(to container: inout PersistenceContainer) { - container[.rowID] = id + container[Column.rowID] = id container["title"] = title container["author"] = author container["body"] = body diff --git a/Tests/GRDBTests/FTS4TableBuilderTests.swift b/Tests/GRDBTests/FTS4TableBuilderTests.swift index c20ffe114..0dfa34dce 100644 --- a/Tests/GRDBTests/FTS4TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS4TableBuilderTests.swift @@ -177,7 +177,7 @@ class FTS4TableBuilderTests: GRDBTestCase { func testFTS4Options() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.create(virtualTable: "documents", using: FTS4()) { t in t.content = "" t.compress = "zip" diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index 8906440d2..0d645db56 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -15,21 +15,21 @@ private struct Book { let body: String } -extension Book : RowConvertible { +extension Book : FetchableRecord { init(row: Row) { - id = row[.rowID] + id = row[Column.rowID] title = row["title"] author = row["author"] body = row["body"] } } -extension Book : MutablePersistable { +extension Book : MutablePersistableRecord { static let databaseTableName = "books" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] func encode(to container: inout PersistenceContainer) { - container[.rowID] = id + container[Column.rowID] = id container["title"] = title container["author"] = author container["body"] = body diff --git a/Tests/GRDBTests/FetchRequestTests.swift b/Tests/GRDBTests/FetchRequestTests.swift new file mode 100644 index 000000000..6ba92882a --- /dev/null +++ b/Tests/GRDBTests/FetchRequestTests.swift @@ -0,0 +1,139 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +class FetchRequestTests: GRDBTestCase { + + func testRequestFetchRows() throws { + struct CustomRequest : FetchRequest { + typealias RowDecoder = Row + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (db.makeSelectStatement("SELECT * FROM table1"), nil) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + try db.execute("INSERT INTO table1 DEFAULT VALUES") + try db.execute("INSERT INTO table1 DEFAULT VALUES") + + let request = CustomRequest() + let rows = try request.fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM table1") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0], ["id": 1]) + XCTAssertEqual(rows[1], ["id": 2]) + } + } + + func testRequestFetchValues() throws { + struct CustomRequest : FetchRequest { + typealias RowDecoder = Int + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (db.makeSelectStatement("SELECT id FROM table1"), nil) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + try db.execute("INSERT INTO table1 DEFAULT VALUES") + try db.execute("INSERT INTO table1 DEFAULT VALUES") + + let request = CustomRequest() + let ints = try request.fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT id FROM table1") + XCTAssertEqual(ints.count, 2) + XCTAssertEqual(ints[0], 1) + XCTAssertEqual(ints[1], 2) + } + } + + func testRequestFetchRecords() throws { + struct CustomRecord: FetchableRecord, Decodable { + var id: Int + } + struct CustomRequest : FetchRequest { + typealias RowDecoder = CustomRecord + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (db.makeSelectStatement("SELECT id FROM table1"), nil) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + try db.execute("INSERT INTO table1 DEFAULT VALUES") + try db.execute("INSERT INTO table1 DEFAULT VALUES") + + let request = CustomRequest() + let records = try request.fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT id FROM table1") + XCTAssertEqual(records.count, 2) + XCTAssertEqual(records[0].id, 1) + XCTAssertEqual(records[1].id, 2) + } + } + + func testRequestFetchCount() throws { + struct CustomRequest : FetchRequest { + typealias RowDecoder = Row + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (db.makeSelectStatement("SELECT * FROM table1"), nil) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + try db.execute("INSERT INTO table1 DEFAULT VALUES") + try db.execute("INSERT INTO table1 DEFAULT VALUES") + + let request = CustomRequest() + let count = try request.fetchCount(db) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT * FROM table1)") + XCTAssertEqual(count, 2) + } + } + + func testRequestCustomizedFetchCount() throws { + struct CustomRequest : FetchRequest { + typealias RowDecoder = Row + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (db.makeSelectStatement("INVALID"), nil) + } + + func fetchCount(_ db: Database) throws -> Int { + return 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + try db.execute("INSERT INTO table1 DEFAULT VALUES") + try db.execute("INSERT INTO table1 DEFAULT VALUES") + + let request = CustomRequest() + let count = try request.fetchCount(db) + XCTAssertEqual(lastSQLQuery, "INSERT INTO table1 DEFAULT VALUES") + XCTAssertEqual(count, 2) + } + } +} diff --git a/Tests/GRDBTests/RowConvertible+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift similarity index 96% rename from Tests/GRDBTests/RowConvertible+QueryInterfaceRequestTests.swift rename to Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift index 5f2c5c9d2..6eb9671fa 100644 --- a/Tests/GRDBTests/RowConvertible+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift @@ -13,7 +13,7 @@ private struct Reader { let age: Int? } -extension Reader : RowConvertible { +extension Reader : FetchableRecord { init(row: Row) { id = row["id"] name = row["name"] @@ -21,7 +21,7 @@ extension Reader : RowConvertible { } } -extension Reader : MutablePersistable { +extension Reader : MutablePersistableRecord { static let databaseTableName = "readers" func encode(to container: inout PersistenceContainer) { @@ -41,7 +41,7 @@ private struct AltReader { let age: Int? } -extension AltReader : RowConvertible { +extension AltReader : FetchableRecord { init(row: Row) { id = row["id"] name = row["name"] @@ -50,7 +50,7 @@ extension AltReader : RowConvertible { } -class RowConvertibleQueryInterfaceRequestTests: GRDBTestCase { +class FetchableRecordQueryInterfaceRequestTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { var migrator = DatabaseMigrator() @@ -66,7 +66,7 @@ class RowConvertibleQueryInterfaceRequestTests: GRDBTestCase { } - // MARK: - Fetch RowConvertible + // MARK: - Fetch FetchableRecord func testAll() throws { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/GRDBTests/RowConvertibleDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift similarity index 89% rename from Tests/GRDBTests/RowConvertibleDecodableTests.swift rename to Tests/GRDBTests/FetchableRecordDecodableTests.swift index 1389ec3c3..03ab93312 100644 --- a/Tests/GRDBTests/RowConvertibleDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -8,14 +8,14 @@ import XCTest import GRDB #endif -class RowConvertibleDecodableTests: GRDBTestCase { } +class FetchableRecordDecodableTests: GRDBTestCase { } -// MARK: - RowConvertible conformance derived from Decodable +// MARK: - FetchableRecord conformance derived from Decodable -extension RowConvertibleDecodableTests { +extension FetchableRecordDecodableTests { func testTrivialDecodable() { - struct Struct : RowConvertible, Decodable { + struct Struct : FetchableRecord, Decodable { let value: String } @@ -26,7 +26,7 @@ extension RowConvertibleDecodableTests { } func testCustomDecodable() { - struct Struct : RowConvertible, Decodable { + struct Struct : FetchableRecord, Decodable { let value: String private enum CodingKeys : String, CodingKey { @@ -45,28 +45,28 @@ extension RowConvertibleDecodableTests { } } - func testCustomRowConvertible() { - struct Struct : RowConvertible, Decodable { + func testCustomFetchableRecord() { + struct Struct : FetchableRecord, Decodable { let value: String init(row: Row) { - value = (row["value"] as String) + " (RowConvertible)" + value = (row["value"] as String) + " (FetchableRecord)" } } do { let s = Struct(row: ["value": "foo"]) - XCTAssertEqual(s.value, "foo (RowConvertible)") + XCTAssertEqual(s.value, "foo (FetchableRecord)") } } } // MARK: - Different kinds of single-value properties -extension RowConvertibleDecodableTests { +extension FetchableRecordDecodableTests { func testTrivialProperty() { - struct Struct : RowConvertible, Decodable { + struct Struct : FetchableRecord, Decodable { let int64: Int64 let optionalInt64: Int64? } @@ -100,7 +100,7 @@ extension RowConvertibleDecodableTests { } } - struct Struct : RowConvertible, Decodable { + struct Struct : FetchableRecord, Decodable { let value: Value let optionalValue: Value? } @@ -144,7 +144,7 @@ extension RowConvertibleDecodableTests { } } - struct Struct : RowConvertible, Decodable { + struct Struct : FetchableRecord, Decodable { let value: Value let optionalValue: Value? } @@ -181,7 +181,7 @@ extension RowConvertibleDecodableTests { case foo, bar } - struct Struct : RowConvertible, Decodable { + struct Struct : FetchableRecord, Decodable { let value: Value let optionalValue: Value? } @@ -239,7 +239,7 @@ extension RowConvertibleDecodableTests { } } - struct Struct : RowConvertible, Decodable { + struct Struct : FetchableRecord, Decodable { let value: Value let optionalValue: Value? } @@ -269,10 +269,10 @@ extension RowConvertibleDecodableTests { // MARK: - Foundation Codable Types -extension RowConvertibleDecodableTests { +extension FetchableRecordDecodableTests { func testStructWithDate() { - struct StructWithDate : RowConvertible, Decodable { + struct StructWithDate : FetchableRecord, Decodable { let date: Date } @@ -282,7 +282,7 @@ extension RowConvertibleDecodableTests { } func testStructWithURL() { - struct StructWithURL : RowConvertible, Decodable { + struct StructWithURL : FetchableRecord, Decodable { let url: URL } @@ -292,7 +292,7 @@ extension RowConvertibleDecodableTests { } func testStructWithUUID() { - struct StructWithUUID : RowConvertible, Decodable { + struct StructWithUUID : FetchableRecord, Decodable { let uuid: UUID } diff --git a/Tests/GRDBTests/RowConvertibleTests.swift b/Tests/GRDBTests/FetchableRecordTests.swift similarity index 79% rename from Tests/GRDBTests/RowConvertibleTests.swift rename to Tests/GRDBTests/FetchableRecordTests.swift index 367eaddb6..a928b9ef4 100644 --- a/Tests/GRDBTests/RowConvertibleTests.swift +++ b/Tests/GRDBTests/FetchableRecordTests.swift @@ -12,14 +12,14 @@ private struct Fetched { var lastName: String } -extension Fetched : RowConvertible { +extension Fetched : FetchableRecord { init(row: Row) { firstName = row["firstName"] lastName = row["lastName"] } } -class RowConvertibleTests: GRDBTestCase { +class FetchableRecordTests: GRDBTestCase { func testRowInitializer() { let row = Row(["firstName": "Arthur", "lastName": "Martin"]) @@ -45,8 +45,8 @@ class RowConvertibleTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchCursor(db, sql)) try test(Fetched.fetchCursor(statement)) - try test(Fetched.fetchCursor(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db)) + try test(Fetched.fetchCursor(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchCursor(db)) } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" @@ -54,8 +54,8 @@ class RowConvertibleTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter)) try test(Fetched.fetchCursor(statement, adapter: adapter)) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db)) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } } @@ -89,16 +89,16 @@ class RowConvertibleTests: GRDBTestCase { let sql = "SELECT throw(), NULL" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT 0, throw(), NULL" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -121,16 +121,16 @@ class RowConvertibleTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -147,8 +147,8 @@ class RowConvertibleTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchAll(db, sql)) try test(Fetched.fetchAll(statement)) - try test(Fetched.fetchAll(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db)) + try test(Fetched.fetchAll(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchAll(db)) } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" @@ -156,8 +156,8 @@ class RowConvertibleTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter)) try test(Fetched.fetchAll(statement, adapter: adapter)) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db)) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } } @@ -182,16 +182,16 @@ class RowConvertibleTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -214,16 +214,16 @@ class RowConvertibleTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -240,8 +240,8 @@ class RowConvertibleTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, 1 WHERE 0" @@ -249,8 +249,8 @@ class RowConvertibleTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } do { @@ -263,8 +263,8 @@ class RowConvertibleTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName" @@ -272,8 +272,8 @@ class RowConvertibleTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } } @@ -299,16 +299,16 @@ class RowConvertibleTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } @@ -331,16 +331,16 @@ class RowConvertibleTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } diff --git a/Tests/GRDBTests/FetchedRecordsControllerTests.swift b/Tests/GRDBTests/FetchedRecordsControllerTests.swift index 148573696..867f5594c 100644 --- a/Tests/GRDBTests/FetchedRecordsControllerTests.swift +++ b/Tests/GRDBTests/FetchedRecordsControllerTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private class ChangesRecorder { +private class ChangesRecorder { var changes: [(record: Record, change: FetchedRecordChange)] = [] var recordsBeforeChanges: [Record]! var recordsAfterChanges: [Record]! @@ -85,7 +85,7 @@ private class Person : Record { } } -private struct Book : RowConvertible { +private struct Book : FetchableRecord { var id: Int64 var authorID: Int64 var title: String @@ -897,7 +897,7 @@ class FetchedRecordsControllerTests: GRDBTestCase { }) try specificController.performFetch() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("INSERT INTO persons (id, name) VALUES (?, ?)", arguments: [1, "Arthur"]) try db.execute("INSERT INTO persons (id, name) VALUES (?, ?)", arguments: [2, "Barbara"]) try db.execute("UPDATE persons SET name = ? WHERE id = ?", arguments: ["Craig", 1]) diff --git a/Tests/GRDBTests/FilterCursorTests.swift b/Tests/GRDBTests/FilterCursorTests.swift index 10b68d8f1..dbde9254e 100644 --- a/Tests/GRDBTests/FilterCursorTests.swift +++ b/Tests/GRDBTests/FilterCursorTests.swift @@ -12,7 +12,7 @@ private struct TestError : Error { } class FilterCursorTests: GRDBTestCase { func testFilterCursorFromCursor() { - let base = IteratorCursor([1, 2, 3, 4]) + let base = AnyCursor([1, 2, 3, 4]) let cursor = base.filter { $0 % 2 == 0 } XCTAssertEqual(try cursor.next()!, 2) XCTAssertEqual(try cursor.next()!, 4) @@ -39,7 +39,7 @@ class FilterCursorTests: GRDBTestCase { } func testThrowingFilterCursorFromCursor() { - let base = IteratorCursor([0, 1]) + let base = AnyCursor([0, 1]) let cursor = base.filter { if $0 > 0 { throw TestError() } return true diff --git a/Tests/GRDBTests/FlattenCursorTests.swift b/Tests/GRDBTests/FlattenCursorTests.swift index 41a160879..f2fa00338 100644 --- a/Tests/GRDBTests/FlattenCursorTests.swift +++ b/Tests/GRDBTests/FlattenCursorTests.swift @@ -10,7 +10,7 @@ import XCTest class FlattenCursorTests: GRDBTestCase { func testFlatMapOfSequence() { - let cursor = IteratorCursor([1, 2]).flatMap { [$0, $0+1] } + let cursor = AnyCursor([1, 2]).flatMap { [$0, $0+1] } XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertEqual(try cursor.next()!, 2) @@ -20,7 +20,7 @@ class FlattenCursorTests: GRDBTestCase { } func testFlatMapOfCursor() { - let cursor = IteratorCursor([1, 2]).flatMap { IteratorCursor([$0, $0+1]) } + let cursor = AnyCursor([1, 2]).flatMap { AnyCursor([$0, $0+1]) } XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertEqual(try cursor.next()!, 2) @@ -30,7 +30,7 @@ class FlattenCursorTests: GRDBTestCase { } func testSequenceFlatMapOfCursor() { - let cursor = [1, 2].flatMap { IteratorCursor([$0, $0+1]) } + let cursor = [1, 2].flatMap { AnyCursor([$0, $0+1]) } XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertEqual(try cursor.next()!, 2) @@ -40,7 +40,7 @@ class FlattenCursorTests: GRDBTestCase { } func testJoinedSequences() { - let cursor = IteratorCursor([[1, 2], [2, 3]]).joined() + let cursor = AnyCursor([[1, 2], [2, 3]]).joined() XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertEqual(try cursor.next()!, 2) @@ -50,7 +50,7 @@ class FlattenCursorTests: GRDBTestCase { } func testJoinedCursors() { - let cursor = IteratorCursor([IteratorCursor([1, 2]), IteratorCursor([2, 3])]).joined() + let cursor = AnyCursor([AnyCursor([1, 2]), AnyCursor([2, 3])]).joined() XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertEqual(try cursor.next()!, 2) diff --git a/Tests/GRDBTests/ForeignKeyInfoTests.swift b/Tests/GRDBTests/ForeignKeyInfoTests.swift index 03c9b53ce..91d8e0d4c 100644 --- a/Tests/GRDBTests/ForeignKeyInfoTests.swift +++ b/Tests/GRDBTests/ForeignKeyInfoTests.swift @@ -28,6 +28,14 @@ class ForeignKeyInfoTests: GRDBTestCase { try db.execute("CREATE TABLE children3 (parentA, parentB, FOREIGN KEY (parentA, parentB) REFERENCES parents2)") try db.execute("CREATE TABLE children4 (parentA1, parentB1, parentA2, parentB2, FOREIGN KEY (parentA1, parentB1) REFERENCES parents2, FOREIGN KEY (parentA2, parentB2) REFERENCES parents2(b, a))") + do { + _ = try db.foreignKeys(on: "missing") + XCTFail("Expected DatabaseError") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "no such table: missing") + } + do { let foreignKeys = try db.foreignKeys(on: "parents1") XCTAssert(foreignKeys.isEmpty) diff --git a/Tests/GRDBTests/FoundationDateComponentsTests.swift b/Tests/GRDBTests/FoundationDateComponentsTests.swift index 417a2af69..dc2c9dc78 100644 --- a/Tests/GRDBTests/FoundationDateComponentsTests.swift +++ b/Tests/GRDBTests/FoundationDateComponentsTests.swift @@ -376,140 +376,136 @@ class FoundationDateComponentsTests : GRDBTestCase { "0000-01-01", DatabaseDateComponents( DateComponents(year: 0, month: 1, day: 1, hour: nil, minute: nil, second: nil, nanosecond: nil), - format: .YMD)!) + format: .YMD)) assertParse( "2018-12-31", DatabaseDateComponents( DateComponents(year: 2018, month: 12, day: 31, hour: nil, minute: nil, second: nil, nanosecond: nil), - format: .YMD)!) + format: .YMD)) assertParse( "2018-04-21 00:00", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: nil, nanosecond: nil), - format: .YMD_HM)!) + format: .YMD_HM)) assertParse( "2018-04-21T23:59", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: nil, nanosecond: nil), - format: .YMD_HM)!) + format: .YMD_HM)) assertParse( "2018-04-21 00:00:00", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: nil), - format: .YMD_HMS)!) + format: .YMD_HMS)) assertParse( "2018-04-21T23:59:59", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: nil), - format: .YMD_HMS)!) + format: .YMD_HMS)) assertParse( "2018-04-21 00:00:00.0", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.9", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 900_000_000), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21 00:00:00.00", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21 00:00:00.01", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 10_000_000), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.99", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 990_000_000), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21 00:00:00.000", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21 00:00:00.001", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 1_000_000), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.999", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "00:00", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: nil, nanosecond: nil), - format: .HM)!) + format: .HM)) assertParse( "23:59", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: nil, nanosecond: nil), - format: .HM)!) + format: .HM)) assertParse( "00:00:00", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: nil), - format: .HMS)!) + format: .HMS)) assertParse( "23:59:59", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: nil), - format: .HMS)!) + format: .HMS)) assertParse( "00:00:00.0", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), - format: .HMSS)!) + format: .HMSS)) assertParse( "23:59:59.9", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 900_000_000), - format: .HMSS)!) + format: .HMSS)) assertParse( "00:00:00.00", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), - format: .HMSS)!) + format: .HMSS)) assertParse( "00:00:00.01", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 10_000_000), - format: .HMSS)!) + format: .HMSS)) assertParse( "23:59:59.99", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 990_000_000), - format: .HMSS)!) + format: .HMSS)) assertParse( "00:00:00.000", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), - format: .HMSS)!) + format: .HMSS)) assertParse( "00:00:00.001", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 1_000_000), - format: .HMSS)!) + format: .HMSS)) assertParse( "23:59:59.999", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), - format: .HMSS)!) + format: .HMSS)) } func testDatabaseDateComponentsFromUnparsableString() { let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue("foo".databaseValue) XCTAssertTrue(databaseDateComponents == nil) } - - func testDatabaseDateComponentsFailureFromNilDateComponents() { - XCTAssertNil(DatabaseDateComponents(nil, format: .YMD)) - } } diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 0a02d380f..314cb5b67 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -131,7 +131,7 @@ class GRDBTestCase: XCTestCase { XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)") } - func assert(_ record: MutablePersistable, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) { + func assert(_ record: MutablePersistableRecord, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) { let recordDict = record.databaseDictionary let rowDict = Dictionary(row, uniquingKeysWith: { (left, _) in left }) XCTAssertEqual(recordDict, rowDict, file: file, line: line) @@ -145,21 +145,23 @@ class GRDBTestCase: XCTestCase { } // Compare SQL strings (ignoring leading and trailing white space and semicolons. - func assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { - _ = try Row.fetchOne(db, request) + func assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { + let (statement, _) = try request.prepare(db) + try statement.cursor().next() assertEqualSQL(lastSQLQuery, sql, file: file, line: line) } // Compare SQL strings (ignoring leading and trailing white space and semicolons. - func assertEqualSQL(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { + func assertEqualSQL(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { try databaseReader.unsafeRead { db in try assertEqualSQL(db, request, sql, file: file, line: line) } } - func sql(_ databaseReader: DatabaseReader, _ request: Request) -> String { + func sql(_ databaseReader: DatabaseReader, _ request: Request) -> String { return try! databaseReader.unsafeRead { db in - _ = try Row.fetchOne(db, request) + let (statement, _) = try request.prepare(db) + try statement.cursor().next() return lastSQLQuery } } diff --git a/Tests/GRDBTests/IndexInfoTests.swift b/Tests/GRDBTests/IndexInfoTests.swift index f1a51c5cc..5fc09de3c 100644 --- a/Tests/GRDBTests/IndexInfoTests.swift +++ b/Tests/GRDBTests/IndexInfoTests.swift @@ -12,6 +12,14 @@ class IndexInfoTests: GRDBTestCase { func testIndexes() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in + do { + _ = try db.indexes(on: "missing") + XCTFail("Expected DatabaseError") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "no such table: missing") + } + do { try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)") let indexes = try db.indexes(on: "persons") diff --git a/Tests/GRDBTests/IteratorCursorTests.swift b/Tests/GRDBTests/IteratorCursorTests.swift deleted file mode 100644 index 39b01dd8f..000000000 --- a/Tests/GRDBTests/IteratorCursorTests.swift +++ /dev/null @@ -1,27 +0,0 @@ -import XCTest -#if GRDBCIPHER - import GRDBCipher -#elseif GRDBCUSTOMSQLITE - import GRDBCustomSQLite -#else - import GRDB -#endif - -class IteratorCursorTests: GRDBTestCase { - - func testIteratorCursorFromIterator() { - let cursor = IteratorCursor([0, 1].makeIterator()) - XCTAssertEqual(cursor.next()!, 0) - XCTAssertEqual(cursor.next()!, 1) - XCTAssertTrue(cursor.next() == nil) // end - XCTAssertTrue(cursor.next() == nil) // past the end - } - - func testIteratorCursorFromSequence() { - let cursor = IteratorCursor([0, 1]) - XCTAssertEqual(cursor.next()!, 0) - XCTAssertEqual(cursor.next()!, 1) - XCTAssertTrue(cursor.next() == nil) // end - XCTAssertTrue(cursor.next() == nil) // past the end - } -} diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index 6a1c2419a..f436c4965 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -41,33 +41,33 @@ let testedSQL = """ ORDER BY t1.id """ -private struct T1: Codable, RowConvertible, TableMapping { +private struct T1: Codable, FetchableRecord, TableRecord { static let databaseTableName = "t1" var id: Int64 var name: String } -private struct T2: Codable, RowConvertible, TableMapping { +private struct T2: Codable, FetchableRecord, TableRecord { static let databaseTableName = "t2" var id: Int64 var t1id: Int64 var name: String } -private struct T3: Codable, RowConvertible, TableMapping { +private struct T3: Codable, FetchableRecord, TableRecord { static let databaseTableName = "t3" static let databaseSelection: [SQLSelectable] = [Column("t1id"), Column("name")] var t1id: Int64 var name: String } -private struct T4: Codable, RowConvertible, TableMapping { +private struct T4: Codable, FetchableRecord, TableRecord { static let databaseTableName = "t4" var t1id: Int64 var name: String } -private struct T5: Codable, RowConvertible, TableMapping { +private struct T5: Codable, FetchableRecord, TableRecord { static let databaseTableName = "t5" var id: Int64 var t3id: Int64? @@ -75,7 +75,7 @@ private struct T5: Codable, RowConvertible, TableMapping { var name: String } -private struct FlatModel: RowConvertible { +private struct FlatModel: FetchableRecord { private enum Scopes { static let t1 = "t1" static let t2Left = "t2Left" @@ -95,11 +95,11 @@ private struct FlatModel: RowConvertible { self.t2Left = row[Scopes.t2Left] self.t2Right = row[Scopes.t2Right] self.t3 = row[Scopes.t3] - self.t5count = row.scoped(on: Scopes.suffix)!["t5count"] + self.t5count = row.scopes[Scopes.suffix]!["t5count"] } - static func all() -> AnyTypedRequest { - return SQLRequest(testedSQL).adapted { db in + static func all() -> AdaptedFetchRequest> { + return SQLRequest(testedSQL).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), @@ -110,21 +110,37 @@ private struct FlatModel: RowConvertible { Scopes.t2Left: adapters[1], Scopes.t2Right: adapters[2], Scopes.t3: adapters[3], - Scopes.suffix: adapters[4]]) // The only test for adapters[4] - } - .asRequest(of: FlatModel.self) + Scopes.suffix: adapters[4]]) + } + } + + static func hierarchicalAll() -> AdaptedFetchRequest> { + return SQLRequest(testedSQL).adapted { db in + let adapters = try splittingRowAdapters(columnCounts: [ + T1.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T3.numberOfSelectedColumns(db)]) + return ScopeAdapter([ + Scopes.t1: adapters[0], + "t2": ScopeAdapter(base: EmptyRowAdapter(), scopes: [ + Scopes.t2Left: adapters[1], + Scopes.t2Right: adapters[2]]), + Scopes.t3: adapters[3], + Scopes.suffix: adapters[4]]) + } } } -private struct CodableFlatModel: RowConvertible, Codable { +private struct CodableFlatModel: FetchableRecord, Codable { var t1: T1 var t2Left: T2? var t2Right: T2? var t3: T3? var t5count: Int - static func all() -> AnyTypedRequest { - return SQLRequest(testedSQL).adapted { db in + static func all() -> AdaptedFetchRequest> { + return SQLRequest(testedSQL).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), @@ -135,12 +151,27 @@ private struct CodableFlatModel: RowConvertible, Codable { CodingKeys.t2Left.stringValue: adapters[1], CodingKeys.t2Right.stringValue: adapters[2], CodingKeys.t3.stringValue: adapters[3]]) - } - .asRequest(of: CodableFlatModel.self) + } + } + + static func hierarchicalAll() -> AdaptedFetchRequest> { + return SQLRequest(testedSQL).adapted { db in + let adapters = try splittingRowAdapters(columnCounts: [ + T1.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T3.numberOfSelectedColumns(db)]) + return ScopeAdapter([ + CodingKeys.t1.stringValue: adapters[0], + "t2": ScopeAdapter(base: EmptyRowAdapter(), scopes: [ + CodingKeys.t2Left.stringValue: adapters[1], + CodingKeys.t2Right.stringValue: adapters[2]]), + CodingKeys.t3.stringValue: adapters[3]]) + } } } -private struct CodableNestedModel: RowConvertible, Codable { +private struct CodableNestedModel: FetchableRecord, Codable { struct T2Pair: Codable { var left: T2? var right: T2? @@ -151,8 +182,8 @@ private struct CodableNestedModel: RowConvertible, Codable { var t3: T3? var t5count: Int - static func all() -> AnyTypedRequest { - return SQLRequest(testedSQL).adapted { db in + static func all() -> AdaptedFetchRequest> { + return SQLRequest(testedSQL).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), @@ -167,8 +198,7 @@ private struct CodableNestedModel: RowConvertible, Codable { "left": adapters[1], "right": adapters[2]]), CodingKeys.t3.stringValue: adapters[3]]) - } - .asRequest(of: CodableNestedModel.self) + } } } @@ -274,7 +304,7 @@ class JoinSupportTests: GRDBTestCase { func testSplittingRowAdapters() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let request = SQLRequest(testedSQL).adapted { db in + let request = SQLRequest(testedSQL).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), @@ -288,7 +318,7 @@ class JoinSupportTests: GRDBTestCase { "t3": adapters[3], "suffix": adapters[4]]) } - let rows = try Row.fetchAll(db, request) + let rows = try request.fetchAll(db) XCTAssertEqual(rows.count, 3) XCTAssertEqual(rows[0].unscoped, [ @@ -302,11 +332,11 @@ class JoinSupportTests: GRDBTestCase { "t1id": 1, "name": "A3", // t5count "t5count": 5]) - XCTAssertEqual(rows[0].scoped(on: "t1")!, ["id": 1, "name": "A1"]) - XCTAssertEqual(rows[0].scoped(on: "t2Left")!, ["id": 1, "t1id": 1, "name": "left"]) - XCTAssertEqual(rows[0].scoped(on: "t2Right")!, ["id": 2, "t1id": 1, "name": "right"]) - XCTAssertEqual(rows[0].scoped(on: "t3")!, ["t1id": 1, "name": "A3"]) - XCTAssertEqual(rows[0].scoped(on: "suffix")!, ["t5count": 5]) + XCTAssertEqual(rows[0].scopes["t1"]!, ["id": 1, "name": "A1"]) + XCTAssertEqual(rows[0].scopes["t2Left"]!, ["id": 1, "t1id": 1, "name": "left"]) + XCTAssertEqual(rows[0].scopes["t2Right"]!, ["id": 2, "t1id": 1, "name": "right"]) + XCTAssertEqual(rows[0].scopes["t3"]!, ["t1id": 1, "name": "A3"]) + XCTAssertEqual(rows[0].scopes["suffix"]!, ["t5count": 5]) XCTAssertEqual(rows[1].unscoped, [ // t1.* @@ -319,11 +349,11 @@ class JoinSupportTests: GRDBTestCase { "t1id": nil, "name": nil, // t5count "t5count": 2]) - XCTAssertEqual(rows[1].scoped(on: "t1")!, ["id": 2, "name": "A2"]) - XCTAssertEqual(rows[1].scoped(on: "t2Left")!, ["id": 3, "t1id": 2, "name": "left"]) - XCTAssertEqual(rows[1].scoped(on: "t2Right")!, ["id": nil, "t1id": nil, "name": nil]) - XCTAssertEqual(rows[1].scoped(on: "t3")!, ["t1id": nil, "name": nil]) - XCTAssertEqual(rows[1].scoped(on: "suffix")!, ["t5count": 2]) + XCTAssertEqual(rows[1].scopes["t1"]!, ["id": 2, "name": "A2"]) + XCTAssertEqual(rows[1].scopes["t2Left"]!, ["id": 3, "t1id": 2, "name": "left"]) + XCTAssertEqual(rows[1].scopes["t2Right"]!, ["id": nil, "t1id": nil, "name": nil]) + XCTAssertEqual(rows[1].scopes["t3"]!, ["t1id": nil, "name": nil]) + XCTAssertEqual(rows[1].scopes["suffix"]!, ["t5count": 2]) XCTAssertEqual(rows[2].unscoped, [ // t1.* @@ -336,11 +366,11 @@ class JoinSupportTests: GRDBTestCase { "t1id": nil, "name": nil, // t5count "t5count": 0]) - XCTAssertEqual(rows[2].scoped(on: "t1")!, ["id": 3, "name": "A3"]) - XCTAssertEqual(rows[2].scoped(on: "t2Left")!, ["id": nil, "t1id": nil, "name": nil]) - XCTAssertEqual(rows[2].scoped(on: "t2Right")!, ["id": nil, "t1id": nil, "name": nil]) - XCTAssertEqual(rows[2].scoped(on: "t3")!, ["t1id": nil, "name": nil]) - XCTAssertEqual(rows[2].scoped(on: "suffix")!, ["t5count": 0]) + XCTAssertEqual(rows[2].scopes["t1"]!, ["id": 3, "name": "A3"]) + XCTAssertEqual(rows[2].scopes["t2Left"]!, ["id": nil, "t1id": nil, "name": nil]) + XCTAssertEqual(rows[2].scopes["t2Right"]!, ["id": nil, "t1id": nil, "name": nil]) + XCTAssertEqual(rows[2].scopes["t3"]!, ["t1id": nil, "name": nil]) + XCTAssertEqual(rows[2].scopes["suffix"]!, ["t5count": 0]) } } @@ -380,6 +410,42 @@ class JoinSupportTests: GRDBTestCase { } } + func testFlatModelFromHierarchicalRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let models = try FlatModel.hierarchicalAll().fetchAll(db) + XCTAssertEqual(models.count, 3) + + XCTAssertEqual(models[0].t1.id, 1) + XCTAssertEqual(models[0].t1.name, "A1") + XCTAssertEqual(models[0].t2Left!.id, 1) + XCTAssertEqual(models[0].t2Left!.t1id, 1) + XCTAssertEqual(models[0].t2Left!.name, "left") + XCTAssertEqual(models[0].t2Right!.id, 2) + XCTAssertEqual(models[0].t2Right!.t1id, 1) + XCTAssertEqual(models[0].t2Right!.name, "right") + XCTAssertEqual(models[0].t3!.t1id, 1) + XCTAssertEqual(models[0].t3!.name, "A3") + XCTAssertEqual(models[0].t5count, 5) + + XCTAssertEqual(models[1].t1.id, 2) + XCTAssertEqual(models[1].t1.name, "A2") + XCTAssertEqual(models[1].t2Left!.id, 3) + XCTAssertEqual(models[1].t2Left!.t1id, 2) + XCTAssertEqual(models[1].t2Left!.name, "left") + XCTAssertNil(models[1].t2Right) + XCTAssertNil(models[1].t3) + XCTAssertEqual(models[1].t5count, 2) + + XCTAssertEqual(models[2].t1.id, 3) + XCTAssertEqual(models[2].t1.name, "A3") + XCTAssertNil(models[2].t2Left) + XCTAssertNil(models[2].t2Right) + XCTAssertNil(models[2].t3) + XCTAssertEqual(models[2].t5count, 0) + } + } + func testCodableFlatModel() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -416,6 +482,42 @@ class JoinSupportTests: GRDBTestCase { } } + func testCodableFlatModelFromHierarchicalRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let models = try CodableFlatModel.hierarchicalAll().fetchAll(db) + XCTAssertEqual(models.count, 3) + + XCTAssertEqual(models[0].t1.id, 1) + XCTAssertEqual(models[0].t1.name, "A1") + XCTAssertEqual(models[0].t2Left!.id, 1) + XCTAssertEqual(models[0].t2Left!.t1id, 1) + XCTAssertEqual(models[0].t2Left!.name, "left") + XCTAssertEqual(models[0].t2Right!.id, 2) + XCTAssertEqual(models[0].t2Right!.t1id, 1) + XCTAssertEqual(models[0].t2Right!.name, "right") + XCTAssertEqual(models[0].t3!.t1id, 1) + XCTAssertEqual(models[0].t3!.name, "A3") + XCTAssertEqual(models[0].t5count, 5) + + XCTAssertEqual(models[1].t1.id, 2) + XCTAssertEqual(models[1].t1.name, "A2") + XCTAssertEqual(models[1].t2Left!.id, 3) + XCTAssertEqual(models[1].t2Left!.t1id, 2) + XCTAssertEqual(models[1].t2Left!.name, "left") + XCTAssertNil(models[1].t2Right) + XCTAssertNil(models[1].t3) + XCTAssertEqual(models[1].t5count, 2) + + XCTAssertEqual(models[2].t1.id, 3) + XCTAssertEqual(models[2].t1.name, "A3") + XCTAssertNil(models[2].t2Left) + XCTAssertNil(models[2].t2Right) + XCTAssertNil(models[2].t3) + XCTAssertEqual(models[2].t5count, 0) + } + } + func testCodableNestedModel() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/MapCursorTests.swift b/Tests/GRDBTests/MapCursorTests.swift index 52789379c..56a647325 100644 --- a/Tests/GRDBTests/MapCursorTests.swift +++ b/Tests/GRDBTests/MapCursorTests.swift @@ -12,7 +12,7 @@ private struct TestError : Error { } class MapCursorTests: GRDBTestCase { func testMap() { - let base = IteratorCursor([1, 2]) + let base = AnyCursor([1, 2]) let cursor = base.map { $0 * $0 } XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 4) diff --git a/Tests/GRDBTests/MutablePersistableChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift similarity index 91% rename from Tests/GRDBTests/MutablePersistableChangesTests.swift rename to Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index a79a2d185..f8b01ebce 100644 --- a/Tests/GRDBTests/MutablePersistableChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private struct Player: RowConvertible, MutablePersistable, Codable { +private struct Player: FetchableRecord, MutablePersistableRecord, Codable { static let databaseTableName = "players" var id: Int64? @@ -34,7 +34,7 @@ private struct Player: RowConvertible, MutablePersistable, Codable { } } -class MutablePersistableChangesTests: GRDBTestCase { +class MutablePersistableRecordChangesTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "players") { t in @@ -46,14 +46,14 @@ class MutablePersistableChangesTests: GRDBTestCase { } } - func testDegenerateDatabaseEqualWithSelf() throws { - struct DegenerateRecord: MutablePersistable { + func testDegenerateDatabaseEqualsWithSelf() throws { + struct DegenerateRecord: MutablePersistableRecord { static let databaseTableName = "ignored" func encode(to container: inout PersistenceContainer) { } } let record = DegenerateRecord() - XCTAssertTrue(record.databaseEqual(record)) + XCTAssertTrue(record.databaseEquals(record)) XCTAssertTrue(record.databaseChanges(from: record).isEmpty) let dbQueue = try makeDatabaseQueue() @@ -64,10 +64,10 @@ class MutablePersistableChangesTests: GRDBTestCase { } } - func testDatabaseEqualWithSelf() throws { + func testDatabaseEqualsWithSelf() throws { do { let player = Player(id: nil, name: nil, score: nil, creationDate: nil) - XCTAssertTrue(player.databaseEqual(player)) + XCTAssertTrue(player.databaseEquals(player)) XCTAssertTrue(player.databaseChanges(from: player).isEmpty) let dbQueue = try makeDatabaseQueue() @@ -79,7 +79,7 @@ class MutablePersistableChangesTests: GRDBTestCase { } do { let player = Player(id: 1, name: "foo", score: 42, creationDate: Date()) - XCTAssertTrue(player.databaseEqual(player)) + XCTAssertTrue(player.databaseEquals(player)) XCTAssertTrue(player.databaseChanges(from: player).isEmpty) let dbQueue = try makeDatabaseQueue() @@ -103,7 +103,7 @@ class MutablePersistableChangesTests: GRDBTestCase { var newPlayer = player newPlayer.name = "Bobby" - XCTAssertFalse(newPlayer.databaseEqual(player)) + XCTAssertFalse(newPlayer.databaseEquals(player)) let changes = newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["name"]!, "Arthur".databaseValue) @@ -120,7 +120,7 @@ class MutablePersistableChangesTests: GRDBTestCase { var newPlayer = player newPlayer.name = nil - XCTAssertFalse(newPlayer.databaseEqual(player)) + XCTAssertFalse(newPlayer.databaseEquals(player)) let changes = newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["name"]!, "Arthur".databaseValue) @@ -137,7 +137,7 @@ class MutablePersistableChangesTests: GRDBTestCase { var newPlayer = player newPlayer.score = 41 - XCTAssertFalse(newPlayer.databaseEqual(player)) + XCTAssertFalse(newPlayer.databaseEquals(player)) let changes = newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["score"]!, .null) @@ -155,7 +155,7 @@ class MutablePersistableChangesTests: GRDBTestCase { newPlayer.name = "Bobby" newPlayer.score = 41 - XCTAssertFalse(newPlayer.databaseEqual(player)) + XCTAssertFalse(newPlayer.databaseEquals(player)) let changes = newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 2) XCTAssertEqual(changes["name"]!, "Arthur".databaseValue) @@ -172,9 +172,9 @@ class MutablePersistableChangesTests: GRDBTestCase { } } - func testDatabaseEqualWithDifferentTypesAndDifferentWidth() throws { + func testDatabaseEqualsWithDifferentTypesAndDifferentWidth() throws { // Mangle column case as well, for fun ;-) - struct NarrowPlayer: MutablePersistable, Codable { + struct NarrowPlayer: MutablePersistableRecord, Codable { static let databaseTableName = "players" var ID: Int64? var NAME: String? @@ -264,7 +264,7 @@ class MutablePersistableChangesTests: GRDBTestCase { let totalChangesCount = db.totalChangesCount try XCTAssertTrue(newPlayer.updateChanges(db, from: oldPlayer)) XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1) - XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"NAME\"='Bobby' WHERE \"id\"=1") + XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"name\"='Bobby' WHERE \"id\"=1") return .rollback } } diff --git a/Tests/GRDBTests/MutablePersistableDeleteTests.swift b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift similarity index 97% rename from Tests/GRDBTests/MutablePersistableDeleteTests.swift rename to Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift index db1b2d276..2a8318ae7 100644 --- a/Tests/GRDBTests/MutablePersistableDeleteTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift @@ -7,23 +7,23 @@ import XCTest import GRDB #endif -private struct Hacker : MutablePersistable { +private struct Hacker : MutablePersistableRecord { static let databaseTableName = "hackers" func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } } -private struct Person : MutablePersistable { +private struct Person : MutablePersistableRecord { static let databaseTableName = "persons" func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } } -private struct Citizenship : MutablePersistable { +private struct Citizenship : MutablePersistableRecord { static let databaseTableName = "citizenships" func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } } -class MutablePersistableDeleteTests: GRDBTestCase { +class MutablePersistableRecordDeleteTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in @@ -151,7 +151,7 @@ class MutablePersistableDeleteTests: GRDBTestCase { XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (\"name\" = 'Arthur')") try Person.filter(sql: "id = 1").deleteAll(db) - XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE id = 1") + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (id = 1)") try Person.select(Column("name")).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\"") @@ -172,7 +172,7 @@ class MutablePersistableDeleteTests: GRDBTestCase { XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" ORDER BY \"name\" DESC LIMIT 1 OFFSET 2") try Person.limit(1, offset: 2).reversed().deleteAll(db) - XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" ORDER BY \"rowid\" DESC LIMIT 1 OFFSET 2") + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" LIMIT 1 OFFSET 2") } } } diff --git a/Tests/GRDBTests/MutablePersistableEncodableTests.swift b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift similarity index 92% rename from Tests/GRDBTests/MutablePersistableEncodableTests.swift rename to Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift index 0f128339d..70f238d7a 100644 --- a/Tests/GRDBTests/MutablePersistableEncodableTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift @@ -8,14 +8,14 @@ import Foundation import GRDB #endif -class MutablePersistableEncodableTests: GRDBTestCase { } +class MutablePersistableRecordEncodableTests: GRDBTestCase { } -// MARK: - MutablePersistable conformance derived from Encodable +// MARK: - MutablePersistableRecord conformance derived from Encodable -extension MutablePersistableEncodableTests { +extension MutablePersistableRecordEncodableTests { func testTrivialEncodable() throws { - struct Struct : MutablePersistable, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: String } @@ -36,7 +36,7 @@ extension MutablePersistableEncodableTests { } func testCustomEncodable() throws { - struct Struct : MutablePersistable, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: String @@ -65,13 +65,13 @@ extension MutablePersistableEncodableTests { } } - func testCustomMutablePersistable() throws { - struct Struct : MutablePersistable, Encodable { + func testCustomMutablePersistableRecord() throws { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: String func encode(to container: inout PersistenceContainer) { - container["value"] = value + " (MutablePersistable)" + container["value"] = value + " (MutablePersistableRecord)" } } @@ -82,21 +82,21 @@ extension MutablePersistableEncodableTests { } var value = Struct(value: "foo") - assert(value, isEncodedIn: ["value": "foo (MutablePersistable)"]) + assert(value, isEncodedIn: ["value": "foo (MutablePersistableRecord)"]) try value.insert(db) let string = try String.fetchOne(db, "SELECT value FROM t1")! - XCTAssertEqual(string, "foo (MutablePersistable)") + XCTAssertEqual(string, "foo (MutablePersistableRecord)") } } } // MARK: - Different kinds of single-value properties -extension MutablePersistableEncodableTests { +extension MutablePersistableRecordEncodableTests { func testTrivialProperty() throws { - struct Struct : MutablePersistable, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let int64: Int64 let optionalInt64: Int64? @@ -141,7 +141,7 @@ extension MutablePersistableEncodableTests { } } - struct Struct : MutablePersistable, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: Value let optionalValue: Value? @@ -195,7 +195,7 @@ extension MutablePersistableEncodableTests { } } - struct Struct : MutablePersistable, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: Value let optionalValue: Value? @@ -240,7 +240,7 @@ extension MutablePersistableEncodableTests { case foo, bar } - struct Struct : MutablePersistable, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: Value let optionalValue: Value? @@ -303,7 +303,7 @@ extension MutablePersistableEncodableTests { } } - struct Struct : MutablePersistable, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: Value let optionalValue: Value? @@ -341,10 +341,10 @@ extension MutablePersistableEncodableTests { // MARK: - Foundation Codable Types -extension MutablePersistableEncodableTests { +extension MutablePersistableRecordEncodableTests { func testStructWithDate() throws { - struct StructWithDate : Persistable, Encodable { + struct StructWithDate : PersistableRecord, Encodable { static let databaseTableName = "t1" let date: Date } @@ -371,7 +371,7 @@ extension MutablePersistableEncodableTests { } func testStructWithURL() throws { - struct StructWithURL : Persistable, Encodable { + struct StructWithURL : PersistableRecord, Encodable { static let databaseTableName = "t1" let url: URL } @@ -394,7 +394,7 @@ extension MutablePersistableEncodableTests { } func testStructWithUUID() throws { - struct StructWithUUID : Persistable, Encodable { + struct StructWithUUID : PersistableRecord, Encodable { static let databaseTableName = "t1" let uuid: UUID } diff --git a/Tests/GRDBTests/MutablePersistablePersistenceConflictPolicyTests.swift b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift similarity index 95% rename from Tests/GRDBTests/MutablePersistablePersistenceConflictPolicyTests.swift rename to Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift index a076d0f49..02deef3a3 100644 --- a/Tests/GRDBTests/MutablePersistablePersistenceConflictPolicyTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private struct DefaultPolicy: MutablePersistable { +private struct DefaultPolicy: MutablePersistableRecord { var id: Int64? static let databaseTableName = "records" @@ -21,7 +21,7 @@ private struct DefaultPolicy: MutablePersistable { } } -private struct MixedPolicy: MutablePersistable { +private struct MixedPolicy: MutablePersistableRecord { var id: Int64? static let databaseTableName = "records" @@ -36,7 +36,7 @@ private struct MixedPolicy: MutablePersistable { } } -private struct ReplacePolicy: MutablePersistable { +private struct ReplacePolicy: MutablePersistableRecord { var id: Int64? var email: String @@ -53,7 +53,7 @@ private struct ReplacePolicy: MutablePersistable { } } -private struct IgnorePolicy: MutablePersistable { +private struct IgnorePolicy: MutablePersistableRecord { var id: Int64? static let databaseTableName = "records" @@ -68,7 +68,7 @@ private struct IgnorePolicy: MutablePersistable { } } -private struct FailPolicy: MutablePersistable { +private struct FailPolicy: MutablePersistableRecord { var id: Int64? static let databaseTableName = "records" @@ -83,7 +83,7 @@ private struct FailPolicy: MutablePersistable { } } -private struct AbortPolicy: MutablePersistable { +private struct AbortPolicy: MutablePersistableRecord { var id: Int64? static let databaseTableName = "records" @@ -98,7 +98,7 @@ private struct AbortPolicy: MutablePersistable { } } -private struct RollbackPolicy: MutablePersistable { +private struct RollbackPolicy: MutablePersistableRecord { var id: Int64? static let databaseTableName = "records" @@ -113,7 +113,7 @@ private struct RollbackPolicy: MutablePersistable { } } -class MutablePersistablePersistenceConflictPolicyTests: GRDBTestCase { +class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { func testPolicyDefaultArguments() { let policy = PersistenceConflictPolicy() @@ -189,7 +189,7 @@ class MutablePersistablePersistenceConflictPolicyTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.create(table: "records") { t in t.column("id", .integer).primaryKey() t.column("email", .text).unique() diff --git a/Tests/GRDBTests/MutablePersistableTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift similarity index 85% rename from Tests/GRDBTests/MutablePersistableTests.swift rename to Tests/GRDBTests/MutablePersistableRecordTests.swift index 5638f3d0d..1f2175db2 100644 --- a/Tests/GRDBTests/MutablePersistableTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private struct MutablePersistablePerson : MutablePersistable { +private struct MutablePersistableRecordPerson : MutablePersistableRecord { var id: Int64? var name: String? var age: Int? @@ -26,7 +26,7 @@ private struct MutablePersistablePerson : MutablePersistable { } } -private struct MutablePersistableCountry : MutablePersistable { +private struct MutablePersistableRecordCountry : MutablePersistableRecord { var rowID: Int64? var isoCode: String var name: String @@ -43,7 +43,7 @@ private struct MutablePersistableCountry : MutablePersistable { } } -private struct MutablePersistableCustomizedCountry : MutablePersistable { +private struct MutablePersistableRecordCustomizedCountry : MutablePersistableRecord { var rowID: Int64? var isoCode: String var name: String @@ -90,7 +90,7 @@ private struct MutablePersistableCustomizedCountry : MutablePersistable { } } -class MutablePersistableTests: GRDBTestCase { +class MutablePersistableRecordTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { var migrator = DatabaseMigrator() @@ -109,12 +109,12 @@ class MutablePersistableTests: GRDBTestCase { } - // MARK: - MutablePersistablePerson + // MARK: - MutablePersistableRecordPerson - func testInsertMutablePersistablePerson() throws { + func testInsertMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + var person = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) try person.insert(db) let rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -124,12 +124,12 @@ class MutablePersistableTests: GRDBTestCase { } } - func testUpdateMutablePersistablePerson() throws { + func testUpdateMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + var person1 = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) try person1.insert(db) - var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 24) + var person2 = MutablePersistableRecordPerson(id: nil, name: "Barbara", age: 24) try person2.insert(db) person1.name = "Craig" @@ -148,12 +148,12 @@ class MutablePersistableTests: GRDBTestCase { } } - func testPartialUpdateMutablePersistablePerson() throws { + func testPartialUpdateMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + var person1 = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) try person1.insert(db) - var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 36) + var person2 = MutablePersistableRecordPerson(id: nil, name: "Barbara", age: 36) try person2.insert(db) do { @@ -190,7 +190,7 @@ class MutablePersistableTests: GRDBTestCase { do { person1.name = "David" try person1.update(db, columns: ["AgE"]) // case insensitivity - XCTAssertEqual(self.lastSQLQuery, "UPDATE \"persons\" SET \"AgE\"=25 WHERE \"id\"=1") + XCTAssertEqual(self.lastSQLQuery, "UPDATE \"persons\" SET \"age\"=25 WHERE \"id\"=1") let rows = try Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) @@ -204,10 +204,10 @@ class MutablePersistableTests: GRDBTestCase { } } - func testSaveMutablePersistablePerson() throws { + func testSaveMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + var person1 = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) try person1.save(db) var rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -215,7 +215,7 @@ class MutablePersistableTests: GRDBTestCase { XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) XCTAssertEqual(rows[0]["name"] as String, "Arthur") - var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 24) + var person2 = MutablePersistableRecordPerson(id: nil, name: "Barbara", age: 24) try person2.save(db) person1.name = "Craig" @@ -240,12 +240,12 @@ class MutablePersistableTests: GRDBTestCase { } } - func testDeleteMutablePersistablePerson() throws { + func testDeleteMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + var person1 = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) try person1.insert(db) - var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 24) + var person2 = MutablePersistableRecordPerson(id: nil, name: "Barbara", age: 24) try person2.insert(db) var deleted = try person1.delete(db) @@ -260,10 +260,10 @@ class MutablePersistableTests: GRDBTestCase { } } - func testExistsMutablePersistablePerson() throws { + func testExistsMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + var person = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) try person.insert(db) XCTAssertTrue(try person.exists(db)) @@ -272,18 +272,18 @@ class MutablePersistableTests: GRDBTestCase { } } - func testMutablePersistablePersonDatabaseDictionary() { - let person = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + func testMutablePersistableRecordPersonDatabaseDictionary() { + let person = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) let dict = person.databaseDictionary XCTAssertEqual(dict, ["iD": DatabaseValue.null, "NAme": "Arthur".databaseValue, "aGe": 24.databaseValue]) } - // MARK: - MutablePersistableCountry + // MARK: - MutablePersistableRecordCountry - func testInsertMutablePersistableCountry() throws { + func testInsertMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + var country = MutablePersistableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country.insert(db) let rows = try Row.fetchAll(db, "SELECT rowID, * FROM countries") @@ -293,12 +293,12 @@ class MutablePersistableTests: GRDBTestCase { } } - func testUpdateMutablePersistableCountry() throws { + func testUpdateMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + var country1 = MutablePersistableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country1.insert(db) - var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + var country2 = MutablePersistableRecordCountry(rowID: nil, isoCode: "US", name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" @@ -314,10 +314,10 @@ class MutablePersistableTests: GRDBTestCase { } } - func testSaveMutablePersistableCountry() throws { + func testSaveMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + var country1 = MutablePersistableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country1.save(db) var rows = try Row.fetchAll(db, "SELECT rowID, * FROM countries") @@ -325,7 +325,7 @@ class MutablePersistableTests: GRDBTestCase { XCTAssertEqual(rows[0]["rowID"] as Int64, country1.rowID!) XCTAssertEqual(rows[0]["name"] as String, "France") - var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + var country2 = MutablePersistableRecordCountry(rowID: nil, isoCode: "US", name: "United States") try country2.save(db) country1.name = "France Métropolitaine" @@ -350,12 +350,12 @@ class MutablePersistableTests: GRDBTestCase { } } - func testDeleteMutablePersistableCountry() throws { + func testDeleteMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + var country1 = MutablePersistableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country1.insert(db) - var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + var country2 = MutablePersistableRecordCountry(rowID: nil, isoCode: "US", name: "United States") try country2.insert(db) var deleted = try country1.delete(db) @@ -370,10 +370,10 @@ class MutablePersistableTests: GRDBTestCase { } } - func testExistsMutablePersistableCountry() throws { + func testExistsMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + var country = MutablePersistableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country.insert(db) XCTAssertTrue(try country.exists(db)) @@ -383,9 +383,9 @@ class MutablePersistableTests: GRDBTestCase { } - // MARK: - MutablePersistableCustomizedCountry + // MARK: - MutablePersistableRecordCustomizedCountry - func testInsertMutablePersistableCustomizedCountry() throws { + func testInsertMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -393,7 +393,7 @@ class MutablePersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country = MutablePersistableCustomizedCountry( + var country = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -417,7 +417,7 @@ class MutablePersistableTests: GRDBTestCase { } } - func testUpdateMutablePersistableCustomizedCountry() throws { + func testUpdateMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -425,7 +425,7 @@ class MutablePersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = MutablePersistableCustomizedCountry( + var country1 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -435,7 +435,7 @@ class MutablePersistableTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - var country2 = MutablePersistableCustomizedCountry( + var country2 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "US", name: "United States", @@ -465,7 +465,7 @@ class MutablePersistableTests: GRDBTestCase { } } - func testSaveMutablePersistableCustomizedCountry() throws { + func testSaveMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -473,7 +473,7 @@ class MutablePersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = MutablePersistableCustomizedCountry( + var country1 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -495,7 +495,7 @@ class MutablePersistableTests: GRDBTestCase { XCTAssertEqual(rows[0]["rowID"] as Int64, country1.rowID!) XCTAssertEqual(rows[0]["name"] as String, "France") - var country2 = MutablePersistableCustomizedCountry( + var country2 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "US", name: "United States", @@ -540,7 +540,7 @@ class MutablePersistableTests: GRDBTestCase { } } - func testDeleteMutablePersistableCustomizedCountry() throws { + func testDeleteMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -548,7 +548,7 @@ class MutablePersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = MutablePersistableCustomizedCountry( + var country1 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -558,7 +558,7 @@ class MutablePersistableTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - var country2 = MutablePersistableCustomizedCountry( + var country2 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "US", name: "United States", @@ -587,7 +587,7 @@ class MutablePersistableTests: GRDBTestCase { } } - func testExistsMutablePersistableCustomizedCountry() throws { + func testExistsMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -595,7 +595,7 @@ class MutablePersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country = MutablePersistableCustomizedCountry( + var country = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -627,7 +627,7 @@ class MutablePersistableTests: GRDBTestCase { // MARK: - Misc func testPartiallyEncodedRecord() throws { - struct PartialRecord : MutablePersistable { + struct PartialRecord : MutablePersistableRecord { var id: Int64? var a: String diff --git a/Tests/GRDBTests/PersistableTests.swift b/Tests/GRDBTests/PersistableRecordTests.swift similarity index 85% rename from Tests/GRDBTests/PersistableTests.swift rename to Tests/GRDBTests/PersistableRecordTests.swift index e615cdae6..3d101212f 100644 --- a/Tests/GRDBTests/PersistableTests.swift +++ b/Tests/GRDBTests/PersistableRecordTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private struct PersistablePerson : Persistable { +private struct PersistableRecordPerson : PersistableRecord { var name: String? var age: Int? @@ -19,7 +19,7 @@ private struct PersistablePerson : Persistable { } } -private class PersistablePersonClass : Persistable { +private class PersistableRecordPersonClass : PersistableRecord { var id: Int64? var name: String? var age: Int? @@ -44,7 +44,7 @@ private class PersistablePersonClass : Persistable { } } -private struct PersistableCountry : Persistable { +private struct PersistableRecordCountry : PersistableRecord { var isoCode: String var name: String @@ -56,7 +56,7 @@ private struct PersistableCountry : Persistable { } } -private struct PersistableCustomizedCountry : Persistable { +private struct PersistableRecordCustomizedCountry : PersistableRecord { var isoCode: String var name: String let willInsert: () -> Void @@ -98,7 +98,7 @@ private struct PersistableCustomizedCountry : Persistable { } } -private struct Citizenship : Persistable { +private struct Citizenship : PersistableRecord { let personID: Int64 let countryIsoCode: String @@ -110,7 +110,7 @@ private struct Citizenship : Persistable { } } -class PersistableTests: GRDBTestCase { +class PersistableRecordTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { var migrator = DatabaseMigrator() @@ -132,12 +132,12 @@ class PersistableTests: GRDBTestCase { } - // MARK: - PersistablePerson + // MARK: - PersistableRecordPerson - func testInsertPersistablePerson() throws { + func testInsertPersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = PersistablePerson(name: "Arthur", age: 42) + let person = PersistableRecordPerson(name: "Arthur", age: 42) try person.insert(db) let rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -146,10 +146,10 @@ class PersistableTests: GRDBTestCase { } } - func testSavePersistablePerson() throws { + func testSavePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = PersistablePerson(name: "Arthur", age: 42) + let person = PersistableRecordPerson(name: "Arthur", age: 42) try person.save(db) let rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -159,12 +159,12 @@ class PersistableTests: GRDBTestCase { } - // MARK: - PersistablePersonClass + // MARK: - PersistableRecordPersonClass - func testInsertPersistablePersonClass() throws { + func testInsertPersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + let person = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person.insert(db) let rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -174,12 +174,12 @@ class PersistableTests: GRDBTestCase { } } - func testUpdatePersistablePersonClass() throws { + func testUpdatePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + let person1 = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person1.insert(db) - let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + let person2 = PersistableRecordPersonClass(id: nil, name: "Barbara", age: 39) try person2.insert(db) person1.name = "Craig" @@ -198,12 +198,12 @@ class PersistableTests: GRDBTestCase { } } - func testPartialUpdatePersistablePersonClass() throws { + func testPartialUpdatePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 24) + let person1 = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 24) try person1.insert(db) - let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 36) + let person2 = PersistableRecordPersonClass(id: nil, name: "Barbara", age: 36) try person2.insert(db) do { @@ -240,7 +240,7 @@ class PersistableTests: GRDBTestCase { do { person1.name = "David" try person1.update(db, columns: ["AgE"]) // case insensitivity - XCTAssertEqual(self.lastSQLQuery, "UPDATE \"persons\" SET \"AgE\"=25 WHERE \"id\"=1") + XCTAssertEqual(self.lastSQLQuery, "UPDATE \"persons\" SET \"age\"=25 WHERE \"id\"=1") let rows = try Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) @@ -254,10 +254,10 @@ class PersistableTests: GRDBTestCase { } } - func testSavePersistablePersonClass() throws { + func testSavePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + let person1 = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person1.save(db) var rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -265,7 +265,7 @@ class PersistableTests: GRDBTestCase { XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) XCTAssertEqual(rows[0]["name"] as String, "Arthur") - let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + let person2 = PersistableRecordPersonClass(id: nil, name: "Barbara", age: 39) try person2.save(db) person1.name = "Craig" @@ -290,12 +290,12 @@ class PersistableTests: GRDBTestCase { } } - func testDeletePersistablePersonClass() throws { + func testDeletePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + let person1 = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person1.insert(db) - let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + let person2 = PersistableRecordPersonClass(id: nil, name: "Barbara", age: 39) try person2.insert(db) var deleted = try person1.delete(db) @@ -310,10 +310,10 @@ class PersistableTests: GRDBTestCase { } } - func testExistsPersistablePersonClass() throws { + func testExistsPersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + let person = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person.insert(db) XCTAssertTrue(try person.exists(db)) @@ -323,12 +323,12 @@ class PersistableTests: GRDBTestCase { } - // MARK: - PersistableCountry + // MARK: - PersistableRecordCountry - func testInsertPersistableCountry() throws { + func testInsertPersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let country = PersistableCountry(isoCode: "FR", name: "France") + let country = PersistableRecordCountry(isoCode: "FR", name: "France") try country.insert(db) let rows = try Row.fetchAll(db, "SELECT * FROM countries") @@ -338,12 +338,12 @@ class PersistableTests: GRDBTestCase { } } - func testUpdatePersistableCountry() throws { + func testUpdatePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = PersistableCountry(isoCode: "FR", name: "France") + var country1 = PersistableRecordCountry(isoCode: "FR", name: "France") try country1.insert(db) - let country2 = PersistableCountry(isoCode: "US", name: "United States") + let country2 = PersistableRecordCountry(isoCode: "US", name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" @@ -359,12 +359,12 @@ class PersistableTests: GRDBTestCase { } } - func testPartialUpdatePersistableCountry() throws { + func testPartialUpdatePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = PersistableCountry(isoCode: "FR", name: "France") + var country1 = PersistableRecordCountry(isoCode: "FR", name: "France") try country1.insert(db) - let country2 = PersistableCountry(isoCode: "US", name: "United States") + let country2 = PersistableRecordCountry(isoCode: "US", name: "United States") try country2.insert(db) do { @@ -395,10 +395,10 @@ class PersistableTests: GRDBTestCase { } } - func testSavePersistableCountry() throws { + func testSavePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = PersistableCountry(isoCode: "FR", name: "France") + var country1 = PersistableRecordCountry(isoCode: "FR", name: "France") try country1.save(db) var rows = try Row.fetchAll(db, "SELECT * FROM countries") @@ -406,7 +406,7 @@ class PersistableTests: GRDBTestCase { XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France") - let country2 = PersistableCountry(isoCode: "US", name: "United States") + let country2 = PersistableRecordCountry(isoCode: "US", name: "United States") try country2.save(db) country1.name = "France Métropolitaine" @@ -431,12 +431,12 @@ class PersistableTests: GRDBTestCase { } } - func testDeletePersistableCountry() throws { + func testDeletePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let country1 = PersistableCountry(isoCode: "FR", name: "France") + let country1 = PersistableRecordCountry(isoCode: "FR", name: "France") try country1.insert(db) - let country2 = PersistableCountry(isoCode: "US", name: "United States") + let country2 = PersistableRecordCountry(isoCode: "US", name: "United States") try country2.insert(db) var deleted = try country1.delete(db) @@ -451,10 +451,10 @@ class PersistableTests: GRDBTestCase { } } - func testExistsPersistableCountry() throws { + func testExistsPersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let country = PersistableCountry(isoCode: "FR", name: "France") + let country = PersistableRecordCountry(isoCode: "FR", name: "France") try country.insert(db) XCTAssertTrue(try country.exists(db)) @@ -464,9 +464,9 @@ class PersistableTests: GRDBTestCase { } - // MARK: - PersistableCustomizedCountry + // MARK: - PersistableRecordCustomizedCountry - func testInsertPersistableCustomizedCountry() throws { + func testInsertPersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -474,7 +474,7 @@ class PersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - let country = PersistableCustomizedCountry( + let country = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -497,7 +497,7 @@ class PersistableTests: GRDBTestCase { } } - func testUpdatePersistableCustomizedCountry() throws { + func testUpdatePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -505,7 +505,7 @@ class PersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = PersistableCustomizedCountry( + var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -514,7 +514,7 @@ class PersistableTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - let country2 = PersistableCustomizedCountry( + let country2 = PersistableRecordCustomizedCountry( isoCode: "US", name: "United States", willInsert: { }, @@ -543,7 +543,7 @@ class PersistableTests: GRDBTestCase { } } - func testPartialUpdatePersistableCustomizedCountry() throws { + func testPartialUpdatePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -551,7 +551,7 @@ class PersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = PersistableCustomizedCountry( + var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -560,7 +560,7 @@ class PersistableTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - let country2 = PersistableCustomizedCountry( + let country2 = PersistableRecordCustomizedCountry( isoCode: "US", name: "United States", willInsert: { }, @@ -589,7 +589,7 @@ class PersistableTests: GRDBTestCase { } } - func testSavePersistableCustomizedCountry() throws { + func testSavePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -597,7 +597,7 @@ class PersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = PersistableCustomizedCountry( + var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -618,7 +618,7 @@ class PersistableTests: GRDBTestCase { XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France") - let country2 = PersistableCustomizedCountry( + let country2 = PersistableRecordCustomizedCountry( isoCode: "US", name: "United States", willInsert: { }, @@ -662,7 +662,7 @@ class PersistableTests: GRDBTestCase { } } - func testDeletePersistableCustomizedCountry() throws { + func testDeletePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -670,7 +670,7 @@ class PersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - let country1 = PersistableCustomizedCountry( + let country1 = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -679,7 +679,7 @@ class PersistableTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - let country2 = PersistableCustomizedCountry( + let country2 = PersistableRecordCustomizedCountry( isoCode: "US", name: "United States", willInsert: { }, @@ -707,7 +707,7 @@ class PersistableTests: GRDBTestCase { } } - func testExistsPersistableCustomizedCountry() throws { + func testExistsPersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -715,7 +715,7 @@ class PersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - let country = PersistableCustomizedCountry( + let country = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -749,9 +749,9 @@ class PersistableTests: GRDBTestCase { func testInsertErrorDoesNotPreventSubsequentInserts() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = PersistablePersonClass(id: nil, name: "Arthur", age: 12) + let person = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 12) try person.insert(db) - try PersistableCountry(isoCode: "FR", name: "France").insert(db) + try PersistableRecordCountry(isoCode: "FR", name: "France").insert(db) do { try Citizenship(personID: person.id!, countryIsoCode: "US").insert(db) } catch let error as DatabaseError { diff --git a/Tests/GRDBTests/PrefixCursorTests.swift b/Tests/GRDBTests/PrefixCursorTests.swift index fdffab97d..5ee9d2094 100644 --- a/Tests/GRDBTests/PrefixCursorTests.swift +++ b/Tests/GRDBTests/PrefixCursorTests.swift @@ -13,13 +13,13 @@ class PrefixCursorTests: GRDBTestCase { func testPrefixCursorFromCursor() throws { do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.prefix(0) XCTAssertTrue(try cursor.next() == nil) // end XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.prefix(2) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 2) @@ -27,7 +27,7 @@ class PrefixCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.prefix(10) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 2) @@ -60,7 +60,7 @@ class PrefixCursorTests: GRDBTestCase { } func testPrefixCursorChain() throws { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.prefix(2).prefix(1) try XCTAssertEqual(cursor.next()!, 1) XCTAssertTrue(try cursor.next() == nil) // end diff --git a/Tests/GRDBTests/PrefixWhileCursorTests.swift b/Tests/GRDBTests/PrefixWhileCursorTests.swift index 9c0228938..9300b5faf 100644 --- a/Tests/GRDBTests/PrefixWhileCursorTests.swift +++ b/Tests/GRDBTests/PrefixWhileCursorTests.swift @@ -13,7 +13,7 @@ class PrefixWhileCursorTests: GRDBTestCase { func testPrefixWhileCursorFromCursor() throws { do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.prefix(while: { $0 < 3 }) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 2) @@ -21,7 +21,7 @@ class PrefixWhileCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.prefix(while: { _ in true }) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 2) @@ -32,13 +32,13 @@ class PrefixWhileCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.prefix(while: { _ in false }) XCTAssertTrue(try cursor.next() == nil) // end XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.prefix(while: { _ in throw TestError() }) _ = try cursor.next() XCTFail() diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 2dbdfa946..f2c8e18e0 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -14,7 +14,7 @@ private struct Col { static let readerId = Column("readerId") } -private struct Reader : TableMapping { +private struct Reader : TableRecord { static let databaseTableName = "readers" } private let tableRequest = Reader.all() @@ -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) @@ -727,6 +723,40 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE (NOT (\"age\" > 18) AND NOT (\"name\" > 'foo'))") } + func testJoinedOperatorAnd() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([].joined(operator: .and))), + "SELECT * FROM \"readers\" WHERE 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.id == 1].joined(operator: .and))), + "SELECT * FROM \"readers\" WHERE (\"id\" = 1)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil].joined(operator: .and))), + "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) AND (\"name\" IS NOT NULL))") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil, Col.age == nil].joined(operator: .and))), + "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) AND (\"name\" IS NOT NULL) AND (\"age\" IS NULL))") + } + + func testJoinedOperatorOr() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([].joined(operator: .or))), + "SELECT * FROM \"readers\" WHERE 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.id == 1].joined(operator: .or))), + "SELECT * FROM \"readers\" WHERE (\"id\" = 1)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil].joined(operator: .or))), + "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) OR (\"name\" IS NOT NULL))") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil, Col.age == nil].joined(operator: .or))), + "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) OR (\"name\" IS NOT NULL) OR (\"age\" IS NULL))") + } + // MARK: - String functions diff --git a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift index 8fc0c11f0..f2d5c55c6 100644 --- a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift @@ -60,7 +60,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { try db.create(table: "records") { t in t.column("date", .datetime) } - struct Record : TableMapping { + struct Record : TableRecord { static let databaseTableName = "records" } @@ -78,7 +78,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE VIRTUAL TABLE records USING fts3(content TEXT)") - struct Record : TableMapping { + struct Record : TableRecord { static let databaseTableName = "records" } @@ -98,7 +98,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { try db.create(table: "records") { t in t.column("text", .text) } - struct Record : TableMapping { + struct Record : TableRecord { static let databaseTableName = "records" } @@ -112,7 +112,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { default: XCTFail("Expected data blob") } - XCTAssertEqual(self.lastSQLQuery, "SELECT CAST(\"text\" AS BLOB) FROM \"records\"") + XCTAssertEqual(self.lastSQLQuery, "SELECT (CAST(\"text\" AS BLOB)) FROM \"records\"") } } } diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index b2f18fd74..8b28d4046 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -14,7 +14,7 @@ private struct Col { static let readerId = Column("readerId") } -private struct Reader : TableMapping { +private struct Reader : TableRecord { static let databaseTableName = "readers" } private let tableRequest = Reader.all() @@ -237,21 +237,21 @@ class QueryInterfaceRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.filter(sql: "id <> 1")), - "SELECT * FROM \"readers\" WHERE id <> 1") + "SELECT * FROM \"readers\" WHERE (id <> 1)") } func testFilterLiteralWithPositionalArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.filter(sql: "id <> ?", arguments: [1])), - "SELECT * FROM \"readers\" WHERE id <> 1") + "SELECT * FROM \"readers\" WHERE (id <> 1)") } func testFilterLiteralWithNamedArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.filter(sql: "id <> :id", arguments: ["id": 1])), - "SELECT * FROM \"readers\" WHERE id <> 1") + "SELECT * FROM \"readers\" WHERE (id <> 1)") } func testFilter() throws { @@ -316,21 +316,21 @@ class QueryInterfaceRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.name).having(sql: "min(age) > 18")), - "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING min(age) > 18") + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (min(age) > 18)") } func testHavingLiteralWithPositionalArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.name).having(sql: "min(age) > ?", arguments: [18])), - "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING min(age) > 18") + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (min(age) > 18)") } func testHavingLiteralWithNamedArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.name).having(sql: "min(age) > :age", arguments: ["age": 18])), - "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING min(age) > 18") + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (min(age) > 18)") } func testHaving() throws { @@ -417,7 +417,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.reversed()), - "SELECT * FROM \"readers\" ORDER BY \"rowid\" DESC") + "SELECT * FROM \"readers\"") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age).reversed()), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") diff --git a/Tests/GRDBTests/RecordBoxTests.swift b/Tests/GRDBTests/RecordBoxTests.swift deleted file mode 100644 index 7c7af40bc..000000000 --- a/Tests/GRDBTests/RecordBoxTests.swift +++ /dev/null @@ -1,483 +0,0 @@ -import XCTest -#if GRDBCIPHER - import GRDBCipher - typealias RecordBox = GRDBCipher.RecordBox // Single deprecation warning -#elseif GRDBCUSTOMSQLITE - import GRDBCustomSQLite - typealias RecordBox = GRDBCustomSQLite.RecordBox // Single deprecation warning -#else - import GRDB - typealias RecordBox = GRDB.RecordBox // Single deprecation warning -#endif - -private struct Player: RowConvertible, MutablePersistable, Codable { - static let databaseTableName = "players" - - var id: Int64? - var name: String? - var score: Int? - var creationDate: Date? - - init(id: Int64? = nil, name: String? = nil, score: Int? = nil, creationDate: Date? = nil) { - self.id = id - self.name = name - self.score = score - self.creationDate = creationDate - } - - mutating func insert(_ db: Database) throws { - if creationDate == nil { - creationDate = Date() - } - try performInsert(db) - } - - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID - } -} - -class RecordBoxTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { - try dbWriter.write { db in - try db.create(table: "players") { t in - t.column("id", .integer).primaryKey() - t.column("name", .text) - t.column("score", .integer) - t.column("creationDate", .datetime) - } - } - } - - func testRecordIsEditedAfterInit() { - // Create a Record. No fetch has happen, so we don't know if it is - // identical to its eventual row in the database. So it is edited. - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - XCTAssertTrue(player.hasDatabaseChanges) - } - - func testRecordIsEditedAfterInitFromRow() { - // Create a Record from a row. The row may not come from the database. - // So it is edited. - let row = Row(["name": "Arthur", "score": 41]) - let player = RecordBox(row: row) - XCTAssertTrue(player.hasDatabaseChanges) - } - - func testRecordIsNotEditedAfterFullFetch() throws { - // Fetch a record from a row that contains all the columns in - // persistence container: An update statement, which only saves the - // columns in persistence container would perform no change. So the - // record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try RecordBox(value: Player(name: "Arthur", score: 41)).insert(db) - let player = try RecordBox.fetchOne(db, "SELECT * FROM players")! - XCTAssertFalse(player.hasDatabaseChanges) - } - } - - func testRecordIsNotEditedAfterWiderThanFullFetch() throws { - // Fetch a record from a row that contains all the columns in - // persistence container, plus extra ones: An update statement, - // which only saves the columns in persistence container would - // perform no change. So the record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try RecordBox(value: Player(name: "Arthur", score: 41)).insert(db) - let player = try RecordBox.fetchOne(db, "SELECT *, 1 AS foo FROM players")! - XCTAssertFalse(player.hasDatabaseChanges) - } - } - - func testRecordIsEditedAfterPartialFetch() throws { - // Fetch a record from a row that does not contain all the columns in - // persistence container: An update statement saves the columns in - // persistence container, so it may perform unpredictable change. - // So the record is edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try RecordBox(value: Player(name: "Arthur", score: 41)).insert(db) - let player = try RecordBox.fetchOne(db, "SELECT name FROM players")! - XCTAssertTrue(player.hasDatabaseChanges) - } - } - - func testRecordIsNotEditedAfterInsert() throws { - // After insertion, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.insert(db) - XCTAssertFalse(player.hasDatabaseChanges) - } - } - - func testRecordIsEditedAfterValueChange() throws { - // Any change in a value exposed in persistence container yields a - // record that is edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - do { - let player = RecordBox(value: Player(name: "Arthur")) - try player.insert(db) - XCTAssertTrue(player.value.name != nil) - player.value.name = "Bobby" // non-nil vs. non-nil - XCTAssertTrue(player.hasDatabaseChanges) - } - do { - let player = RecordBox(value: Player(name: "Arthur")) - try player.insert(db) - XCTAssertTrue(player.value.name != nil) - player.value.name = nil // non-nil vs. nil - XCTAssertTrue(player.hasDatabaseChanges) - } - do { - let player = RecordBox(value: Player(name: "Arthur")) - try player.insert(db) - XCTAssertTrue(player.value.score == nil) - player.value.score = 41 // nil vs. non-nil - XCTAssertTrue(player.hasDatabaseChanges) - } - } - } - - func testRecordIsNotEditedAfterSameValueChange() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - do { - let player = RecordBox(value: Player(name: "Arthur")) - try player.insert(db) - XCTAssertTrue(player.value.name != nil) - player.value.name = "Arthur" // non-nil vs. non-nil - XCTAssertFalse(player.hasDatabaseChanges) - } - do { - let player = RecordBox(value: Player(name: "Arthur")) - try player.insert(db) - XCTAssertTrue(player.value.score == nil) - player.value.score = nil // nil vs. nil - XCTAssertFalse(player.hasDatabaseChanges) - } - } - } - - func testRecordIsNotEditedAfterUpdate() throws { - // After update, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.insert(db) - player.value.name = "Bobby" - try player.update(db) - XCTAssertFalse(player.hasDatabaseChanges) - } - } - - func testRecordIsNotEditedAfterSave() throws { - // After save, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.save(db) - XCTAssertFalse(player.hasDatabaseChanges) - player.value.name = "Bobby" - XCTAssertTrue(player.hasDatabaseChanges) - try player.save(db) - XCTAssertFalse(player.hasDatabaseChanges) - } - } - - func testRecordIsEditedAfterPrimaryKeyChange() throws { - // After reload, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.insert(db) - player.value.id = player.value.id! + 1 - XCTAssertTrue(player.hasDatabaseChanges) - } - } - - func testCopyTransfersEditedFlag() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - - try player.insert(db) - XCTAssertFalse(player.hasDatabaseChanges) - XCTAssertFalse(player.copy().hasDatabaseChanges) - - player.value.name = "Barbara" - XCTAssertTrue(player.hasDatabaseChanges) - XCTAssertTrue(player.copy().hasDatabaseChanges) - - player.hasDatabaseChanges = false - XCTAssertFalse(player.hasDatabaseChanges) - XCTAssertFalse(player.copy().hasDatabaseChanges) - - player.hasDatabaseChanges = true - XCTAssertTrue(player.hasDatabaseChanges) - XCTAssertTrue(player.copy().hasDatabaseChanges) - } - } - - func testChangesAfterInit() { - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 4) - for (column, old) in changes { - switch column { - case "id": - XCTAssertTrue(old == nil) - case "name": - XCTAssertTrue(old == nil) - case "score": - XCTAssertTrue(old == nil) - case "creationDate": - XCTAssertTrue(old == nil) - default: - XCTFail("Unexpected column: \(column)") - } - } - } - - func testChangesAfterInitFromRow() { - let player = RecordBox(row: Row(["name": "Arthur", "score": 41])) - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 4) - for (column, old) in changes { - switch column { - case "id": - XCTAssertTrue(old == nil) - case "name": - XCTAssertTrue(old == nil) - case "score": - XCTAssertTrue(old == nil) - case "creationDate": - XCTAssertTrue(old == nil) - default: - XCTFail("Unexpected column: \(column)") - } - } - } - - func testChangesAfterFullFetch() throws { - // Fetch a record from a row that contains all the columns in - // persistence container: An update statement, which only saves the - // columns in persistence container would perform no change. So the - // record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try RecordBox(value: Player(name: "Arthur", score: 41)).insert(db) - do { - let player = try RecordBox.fetchOne(db, "SELECT * FROM players")! - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 0) - } - do { - let players = try RecordBox.fetchAll(db, "SELECT * FROM players") - let changes = players[0].databaseChanges - XCTAssertEqual(changes.count, 0) - } - do { - let players = try RecordBox.fetchCursor(db, "SELECT * FROM players") - let changes = try players.next()!.databaseChanges - XCTAssertEqual(changes.count, 0) - } - do { - let player = try RecordBox.fetchOne(db, "SELECT * FROM players", adapter: SuffixRowAdapter(fromIndex: 0))! - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 0) - } - } - } - - func testChangesAfterPartialFetch() throws { - // Fetch a record from a row that does not contain all the columns in - // persistence container: An update statement saves the columns in - // persistence container, so it may perform unpredictable change. - // So the record is edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try RecordBox(value: Player(name: "Arthur", score: 41)).insert(db) - let player = try RecordBox.fetchOne(db, "SELECT name FROM players")! - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 3) - for (column, old) in changes { - switch column { - case "id": - XCTAssertTrue(old == nil) - case "score": - XCTAssertTrue(old == nil) - case "creationDate": - XCTAssertTrue(old == nil) - default: - XCTFail("Unexpected column: \(column)") - } - } - } - } - - func testChangesAfterInsert() throws { - // After insertion, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.insert(db) - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 0) - } - } - - func testChangesAfterValueChange() throws { - // Any change in a value exposed in persistence container yields a - // record that is edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur")) - try player.insert(db) - - player.value.name = "Bobby" // non-nil -> non-nil - player.value.score = 41 // nil -> non-nil - player.value.creationDate = nil // non-nil -> nil - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 3) - for (column, old) in changes { - switch column { - case "name": - XCTAssertEqual(old, "Arthur".databaseValue) - case "score": - XCTAssertEqual(old, DatabaseValue.null) - case "creationDate": - XCTAssertTrue(Date.fromDatabaseValue(old!) != nil) - default: - XCTFail("Unexpected column: \(column)") - } - } - } - } - - func testChangesAfterUpdate() throws { - // After update, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.insert(db) - player.value.name = "Bobby" - try player.update(db) - XCTAssertEqual(player.databaseChanges.count, 0) - } - } - - func testChangesAfterSave() throws { - // After save, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.save(db) - XCTAssertEqual(player.databaseChanges.count, 0) - - player.value.name = "Bobby" - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 1) - for (column, old) in changes { - switch column { - case "name": - XCTAssertEqual(old, "Arthur".databaseValue) - default: - XCTFail("Unexpected column: \(column)") - } - } - try player.save(db) - XCTAssertEqual(player.databaseChanges.count, 0) - } - } - - func testChangesAfterPrimaryKeyChange() throws { - // After reload, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.insert(db) - player.value.id = player.value.id! + 1 - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 1) - for (column, old) in changes { - switch column { - case "id": - XCTAssertEqual(old, (player.value.id! - 1).databaseValue) - default: - XCTFail("Unexpected column: \(column)") - } - } - } - } - - func testCopyTransfersChanges() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - - try player.insert(db) - XCTAssertEqual(player.databaseChanges.count, 0) - XCTAssertEqual(player.copy().databaseChanges.count, 0) - - player.value.name = "Barbara" - XCTAssertTrue(player.databaseChanges.count > 0) // TODO: compare actual changes - XCTAssertEqual(player.databaseChanges.count, player.copy().databaseChanges.count) - - player.hasDatabaseChanges = false - XCTAssertEqual(player.databaseChanges.count, 0) - XCTAssertEqual(player.copy().databaseChanges.count, 0) - - player.hasDatabaseChanges = true - XCTAssertTrue(player.databaseChanges.count > 0) // TODO: compare actual changes - XCTAssertEqual(player.databaseChanges.count, player.copy().databaseChanges.count) - } - } - - func testUpdateChanges() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - - do { - XCTAssertTrue(player.hasDatabaseChanges) - try player.updateChanges(db) - XCTFail("Expected PersistenceError") - } catch is PersistenceError { } - - try player.insert(db) - - // Nothing to update - let initialChangesCount = db.totalChangesCount - XCTAssertFalse(player.hasDatabaseChanges) - try XCTAssertFalse(player.updateChanges(db)) - XCTAssertEqual(db.totalChangesCount, initialChangesCount) - - // Nothing to update - player.value.score = 41 - XCTAssertFalse(player.hasDatabaseChanges) - try XCTAssertFalse(player.updateChanges(db)) - XCTAssertEqual(db.totalChangesCount, initialChangesCount) - - // Update single column - player.value.score = 42 - XCTAssertEqual(Set(player.databaseChanges.keys), ["score"]) - try XCTAssertTrue(player.updateChanges(db)) - XCTAssertEqual(db.totalChangesCount, initialChangesCount + 1) - XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"score\"=42 WHERE \"id\"=1") - - // Update two columns - player.value.name = "Barbara" - player.value.score = 43 - XCTAssertEqual(Set(player.databaseChanges.keys), ["score", "name"]) - try XCTAssertTrue(player.updateChanges(db)) - XCTAssertEqual(db.totalChangesCount, initialChangesCount + 2) - let fetchedPlayer = try RecordBox.fetchOne(db, key: player.value.id)! - XCTAssertEqual(fetchedPlayer.value.name, player.value.name) - XCTAssertEqual(fetchedPlayer.value.score, player.value.score) - } - } -} diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 9c4e9eb64..65dd3e4ca 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -379,7 +379,19 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertTrue(fetchedRecord.id == record.id) } } - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = MinimalRowID.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"minimalRowIDs\" ORDER BY \"id\"") + } + } + // MARK: - Fetch With Primary Key diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 53de5100e..1615624cd 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -395,8 +395,20 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(fetchedRecord.UUID == record.UUID) } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = MinimalSingle.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"minimalSingles\" ORDER BY \"UUID\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift b/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift index 619322d4c..27f9adc71 100644 --- a/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift +++ b/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift @@ -20,14 +20,14 @@ class RecordPersistenceConflictPolicyTests: GRDBTestCase { func testDefaultPersistenceConflictPolicy() { let record = RecordWithoutPersistenceConflictPolicy() - let policy = type(of: record as MutablePersistable).persistenceConflictPolicy + let policy = type(of: record as MutablePersistableRecord).persistenceConflictPolicy XCTAssertEqual(policy.conflictResolutionForInsert, .abort) XCTAssertEqual(policy.conflictResolutionForUpdate, .abort) } func testConfigurablePersistenceConflictPolicy() { let record = RecordWithPersistenceConflictPolicy() - let policy = type(of: record as MutablePersistable).persistenceConflictPolicy + let policy = type(of: record as MutablePersistableRecord).persistenceConflictPolicy XCTAssertEqual(policy.conflictResolutionForInsert, .fail) XCTAssertEqual(policy.conflictResolutionForUpdate, .ignore) } diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 4b6f1be62..4a8ab4b90 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -42,7 +42,7 @@ private class Person : Record { } required init(row: Row) { - id = row[.rowID] + id = row[Column.rowID] age = row["age"] name = row["name"] creationDate = row["creationDate"] @@ -50,7 +50,7 @@ private class Person : Record { } override func encode(to container: inout PersistenceContainer) { - container[.rowID] = id + container[Column.rowID] = id container["name"] = name container["age"] = age container["creationDate"] = creationDate @@ -462,8 +462,20 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Person.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT *, \"rowid\" FROM \"persons\" ORDER BY \"rowid\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index 486610a9e..c153f6ffc 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -415,8 +415,20 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { XCTAssertTrue(fetchedRecord.native == record.native) } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Citizenship.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"citizenships\" ORDER BY \"personName\", \"countryName\"") + } + } + + // MARK: - Exists func testExistsWithNilPrimaryKeyReturnsFalse() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index 76890fa94..34f15af93 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -116,8 +116,20 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { XCTAssertTrue(fetchedRecord.email == record.email) } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Item.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"items\" ORDER BY \"rowid\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index 8ca0f792e..df044d945 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -458,8 +458,20 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Person.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"persons\" ORDER BY \"id\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index 37e7f840a..fdd2ae692 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -406,8 +406,20 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(fetchedRecord.name == record.name) } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Pet.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"pets\" ORDER BY \"UUID\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index 39c99e05c..3a550c14c 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -401,8 +401,20 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { XCTAssertTrue(fetchedRecord.email == record.email) } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Email.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"emails\" ORDER BY \"email\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordUniqueIndexTests.swift b/Tests/GRDBTests/RecordUniqueIndexTests.swift index efee44855..6633e444f 100644 --- a/Tests/GRDBTests/RecordUniqueIndexTests.swift +++ b/Tests/GRDBTests/RecordUniqueIndexTests.swift @@ -7,7 +7,7 @@ import XCTest @testable import GRDB #endif -private struct Person : RowConvertible, TableMapping { +private struct Person : FetchableRecord, TableRecord { static let databaseTableName = "persons" init(row: Row) { } diff --git a/Tests/GRDBTests/RequestTests.swift b/Tests/GRDBTests/RequestTests.swift deleted file mode 100644 index 93f5d74a8..000000000 --- a/Tests/GRDBTests/RequestTests.swift +++ /dev/null @@ -1,83 +0,0 @@ -import XCTest -#if GRDBCIPHER - import GRDBCipher -#elseif GRDBCUSTOMSQLITE - import GRDBCustomSQLite -#else - import GRDB -#endif - -class RequestTests: GRDBTestCase { - - func testRequestFetch() throws { - struct CustomRequest : Request { - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try (db.makeSelectStatement("SELECT * FROM table1"), nil) - } - } - - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() - } - try db.execute("INSERT INTO table1 DEFAULT VALUES") - try db.execute("INSERT INTO table1 DEFAULT VALUES") - - let request: Request = CustomRequest() // Lose type - let rows = try Row.fetchAll(db, request) - XCTAssertEqual(lastSQLQuery, "SELECT * FROM table1") - XCTAssertEqual(rows.count, 2) - XCTAssertEqual(rows[0], ["id": 1]) - XCTAssertEqual(rows[1], ["id": 2]) - } - } - - func testRequestFetchCount() throws { - struct CustomRequest : Request { - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try (db.makeSelectStatement("SELECT * FROM table1"), nil) - } - } - - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() - } - try db.execute("INSERT INTO table1 DEFAULT VALUES") - try db.execute("INSERT INTO table1 DEFAULT VALUES") - - let request: Request = CustomRequest() // Lose type - let count = try request.fetchCount(db) - XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT * FROM table1)") - XCTAssertEqual(count, 2) - } - } - - func testRequestCustomizedFetchCount() throws { - struct CustomRequest : Request { - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try (db.makeSelectStatement("INVALID"), nil) - } - - func fetchCount(_ db: Database) throws -> Int { - return 2 - } - } - - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() - } - try db.execute("INSERT INTO table1 DEFAULT VALUES") - try db.execute("INSERT INTO table1 DEFAULT VALUES") - - let request: Request = CustomRequest() // Lose type - let count = try request.fetchCount(db) - XCTAssertEqual(lastSQLQuery, "INSERT INTO table1 DEFAULT VALUES") - XCTAssertEqual(count, 2) - } - } -} diff --git a/Tests/GRDBTests/RowAdapterTests.swift b/Tests/GRDBTests/RowAdapterTests.swift index 3cda7f89a..c5c79e8a7 100644 --- a/Tests/GRDBTests/RowAdapterTests.swift +++ b/Tests/GRDBTests/RowAdapterTests.swift @@ -275,24 +275,33 @@ class AdapterRowTests : RowTestCase { XCTAssertEqual(row["id2"] as Int, 2) XCTAssertEqual(row["val2"] as String, "foo2") - if let scope = row.scoped(on: "sub1") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 1) - XCTAssertEqual(scope["val"] as String, "foo1") - } else { - XCTFail() + XCTAssertEqual(Set(row.scopes.names), ["sub1", "sub2"]) + XCTAssertEqual(row.scopes.count, 2) + for (name, scopedRow) in row.scopes { + if name == "sub1" { + XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) + } else if name == "sub2" { + XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) + } else { + XCTFail() + } } - if let scope = row.scoped(on: "sub2") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 2) - XCTAssertEqual(scope["val"] as String, "foo2") - } else { - XCTFail() - } + XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) - XCTAssertTrue(row.scoped(on: "SUB1") == nil) // case-insensitivity is not really required here, and case-sensitivity helps the implementation because it allows the use of a dictionary. So let's enforce this with a public test. - XCTAssertTrue(row.scoped(on: "missing") == nil) + XCTAssertEqual(row.scopes["sub1"]!, ["id": 1, "val": "foo1"]) + XCTAssertTrue(row.scopes["sub1"]!.scopes.isEmpty) + XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) + + XCTAssertEqual(row.scopes["sub2"]!, ["id": 2, "val": "foo2"]) + XCTAssertTrue(row.scopes["sub2"]!.scopes.isEmpty) + XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub2"]) + + XCTAssertTrue(row.scopes["SUB1"] == nil) + XCTAssertTrue(row.scopesTree["SUB1"] == nil) + + XCTAssertTrue(row.scopes["missing"] == nil) + XCTAssertTrue(row.scopesTree["missing"] == nil) } } @@ -309,24 +318,33 @@ class AdapterRowTests : RowTestCase { XCTAssertEqual(row["id"] as Int, 0) XCTAssertEqual(row["val"] as String, "foo0") - if let scope = row.scoped(on: "sub1") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 1) - XCTAssertEqual(scope["val"] as String, "foo1") - } else { - XCTFail() + XCTAssertEqual(Set(row.scopes.names), ["sub1", "sub2"]) + XCTAssertEqual(row.scopes.count, 2) + for (name, scopedRow) in row.scopes { + if name == "sub1" { + XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) + } else if name == "sub2" { + XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) + } else { + XCTFail() + } } - if let scope = row.scoped(on: "sub2") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 2) - XCTAssertEqual(scope["val"] as String, "foo2") - } else { - XCTFail() - } + XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) - XCTAssertTrue(row.scoped(on: "SUB1") == nil) // case-insensitivity is not really required here, and case-sensitivity helps the implementation because it allows the use of a dictionary. So let's enforce this with a public test. - XCTAssertTrue(row.scoped(on: "missing") == nil) + XCTAssertEqual(row.scopes["sub1"]!, ["id": 1, "val": "foo1"]) + XCTAssertTrue(row.scopes["sub1"]!.scopes.isEmpty) + XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) + + XCTAssertEqual(row.scopes["sub2"], ["id": 2, "val": "foo2"]) + XCTAssertTrue(row.scopes["sub2"]!.scopes.isEmpty) + XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub2"]) + + XCTAssertTrue(row.scopes["SUB1"] == nil) + XCTAssertTrue(row.scopesTree["SUB1"] == nil) + + XCTAssertTrue(row.scopes["missing"] == nil) + XCTAssertTrue(row.scopesTree["missing"] == nil) } } @@ -337,37 +355,41 @@ class AdapterRowTests : RowTestCase { let adapter1 = ColumnMapping(["id": "id1", "val": "val1"]) let adapter2 = ColumnMapping(["id": "id2", "val": "val2"]) + // - sub0 is defined in the the first scoped adapter + // - sub1 is defined in the the first scoped adapter, and then + // redefined in the second + // - sub2 is defined in the the second scoped adapter let mainAdapter = ScopeAdapter(["sub0": adapter0, "sub1": adapter2]) let adapter = mainAdapter.addingScopes(["sub1": adapter1, "sub2": adapter2]) let row = try Row.fetchOne(db, "SELECT 0 AS id0, 'foo0' AS val0, 1 AS id1, 'foo1' AS val1, 2 as id2, 'foo2' AS val2", adapter: adapter)! - // sub0 is defined in the the first scoped adapter - if let scope = row.scoped(on: "sub0") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 0) - XCTAssertEqual(scope["val"] as String, "foo0") - } else { - XCTFail() + XCTAssertEqual(Set(row.scopes.names), ["sub0", "sub1", "sub2"]) + XCTAssertEqual(row.scopes.count, 3) + for (name, scopedRow) in row.scopes { + if name == "sub0" { + XCTAssertEqual(scopedRow, ["id": 0, "val": "foo0"]) + } else if name == "sub1" { + XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) + } else if name == "sub2" { + XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) + } else { + XCTFail() + } } - // sub1 is defined in the the first scoped adapter, and then - // redefined in the second - if let scope = row.scoped(on: "sub1") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 1) - XCTAssertEqual(scope["val"] as String, "foo1") - } else { - XCTFail() - } + XCTAssertEqual(row.scopesTree.names, ["sub0", "sub1", "sub2"]) - // sub2 is defined in the the second scoped adapter - if let scope = row.scoped(on: "sub2") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 2) - XCTAssertEqual(scope["val"] as String, "foo2") - } else { - XCTFail() - } + XCTAssertEqual(row.scopes["sub0"], ["id": 0, "val": "foo0"]) + XCTAssertTrue(row.scopes["sub0"]!.scopes.isEmpty) + XCTAssertEqual(row.scopesTree["sub0"], row.scopes["sub0"]) + + XCTAssertEqual(row.scopes["sub1"], ["id": 1, "val": "foo1"]) + XCTAssertTrue(row.scopes["sub1"]!.scopes.isEmpty) + XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) + + XCTAssertEqual(row.scopes["sub2"], ["id": 2, "val": "foo2"]) + XCTAssertTrue(row.scopes["sub2"]!.scopes.isEmpty) + XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub2"]) } } @@ -385,24 +407,38 @@ class AdapterRowTests : RowTestCase { XCTAssertEqual(row["id"] as Int, 0) XCTAssertEqual(row["val"] as String, "foo0") - if let scope = row.scoped(on: "sub1") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 1) - XCTAssertEqual(scope["val"] as String, "foo1") - - if let scope = scope.scoped(on: "sub2") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 2) - XCTAssertEqual(scope["val"] as String, "foo2") + XCTAssertEqual(Set(row.scopes.names), ["sub1"]) + XCTAssertEqual(row.scopes.count, 1) + for (name, scopedRow) in row.scopes { + if name == "sub1" { + XCTAssertEqual(scopedRow.unscoped, ["id": 1, "val": "foo1"]) } else { XCTFail() } - } else { - XCTFail() } + let scopedRow = row.scopes["sub1"]! + XCTAssertEqual(scopedRow.unscoped, ["id": 1, "val": "foo1"]) + + XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) + XCTAssertEqual(scopedRow.scopes.count, 1) + for (name, subScopedRow) in scopedRow.scopes { + if name == "sub2" { + XCTAssertEqual(subScopedRow, ["id": 2, "val": "foo2"]) + } else { + XCTFail() + } + } + + XCTAssertEqual(scopedRow.scopes["sub2"]!, ["id": 2, "val": "foo2"]) + XCTAssertTrue(scopedRow.scopes["sub2"]!.scopes.isEmpty) + // sub2 is only defined in sub1 - XCTAssertTrue(row.scoped(on: "sub2") == nil) + XCTAssertTrue(row.scopes["sub2"] == nil) + + XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) + XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) + XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub1"]!.scopes["sub2"]) } } @@ -442,22 +478,39 @@ class AdapterRowTests : RowTestCase { "sub2": SuffixRowAdapter(fromIndex: 1)])]) let row = try Row.fetchOne(db, "SELECT 0 AS a0, 1 AS a1, 2 AS a2, 3 AS a3", adapter: adapter)! - if let scope = row.scoped(on: "sub1") { - XCTAssertEqual(Array(scope.columnNames), ["a1", "a2", "a3"]) - XCTAssertEqual(Array(scope.databaseValues), [1.databaseValue, 2.databaseValue, 3.databaseValue]) - - if let scope = scope.scoped(on: "sub2") { - XCTAssertEqual(Array(scope.columnNames), ["a1", "a2", "a3"]) - XCTAssertEqual(Array(scope.databaseValues), [1.databaseValue, 2.databaseValue, 3.databaseValue]) + XCTAssertEqual(Set(row.scopes.names), ["sub1"]) + XCTAssertEqual(row.scopes.count, 1) + for (name, scopedRow) in row.scopes { + if name == "sub1" { + XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2, "a3": 3]) } else { XCTFail() } - } else { - XCTFail() } + let scopedRow = row.scopes["sub1"]! + XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2, "a3": 3]) + + XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) + XCTAssertEqual(scopedRow.scopes.count, 1) + for (name, subScopedRow) in scopedRow.scopes { + if name == "sub2" { + XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2, "a3": 3]) + } else { + XCTFail() + } + } + + let subScopedRow = scopedRow.scopes["sub2"]! + XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2, "a3": 3]) + XCTAssertTrue(subScopedRow.scopes.isEmpty) + // sub2 is only defined in sub1 - XCTAssertTrue(row.scoped(on: "sub2") == nil) + XCTAssertTrue(row.scopes["sub2"] == nil) + + XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) + XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) + XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub1"]!.scopes["sub2"]) } } @@ -534,22 +587,39 @@ class AdapterRowTests : RowTestCase { "sub2": RangeRowAdapter(1..<3)])]) let row = try Row.fetchOne(db, "SELECT 0 AS a0, 1 AS a1, 2 AS a2, 3 AS a3", adapter: adapter)! - if let scope = row.scoped(on: "sub1") { - XCTAssertEqual(Array(scope.columnNames), ["a1", "a2"]) - XCTAssertEqual(Array(scope.databaseValues), [1.databaseValue, 2.databaseValue]) - - if let scope = scope.scoped(on: "sub2") { - XCTAssertEqual(Array(scope.columnNames), ["a1", "a2"]) - XCTAssertEqual(Array(scope.databaseValues), [1.databaseValue, 2.databaseValue]) + XCTAssertEqual(Set(row.scopes.names), ["sub1"]) + XCTAssertEqual(row.scopes.count, 1) + for (name, scopedRow) in row.scopes { + if name == "sub1" { + XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2]) } else { XCTFail() } - } else { - XCTFail() } + let scopedRow = row.scopes["sub1"]! + XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2]) + + XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) + XCTAssertEqual(scopedRow.scopes.count, 1) + for (name, subScopedRow) in scopedRow.scopes { + if name == "sub2" { + XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2]) + } else { + XCTFail() + } + } + + let subScopedRow = scopedRow.scopes["sub2"]! + XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2]) + XCTAssertTrue(subScopedRow.scopes.isEmpty) + // sub2 is only defined in sub1 - XCTAssertTrue(row.scoped(on: "sub2") == nil) + XCTAssertTrue(row.scopes["sub2"] == nil) + + XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) + XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) + XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub1"]!.scopes["sub2"]) } } @@ -569,10 +639,22 @@ class AdapterRowTests : RowTestCase { XCTAssertEqual(copiedRow["a"] as Int, 0) XCTAssertEqual(copiedRow["b"] as Int, 1) XCTAssertEqual(copiedRow["c"] as Int, 2) - if let scope = copiedRow.scoped(on: "sub") { - XCTAssertEqual(scope.count, 1) - XCTAssertEqual(scope["a"] as Int, 1) + + XCTAssertEqual(Set(copiedRow.scopes.names), ["sub"]) + XCTAssertEqual(copiedRow.scopes.count, 1) + for (name, scopedRow) in copiedRow.scopes { + if name == "sub" { + XCTAssertEqual(scopedRow, ["a": 1]) + } else { + XCTFail() + } } + + XCTAssertEqual(Set(copiedRow.scopes.names), ["sub"]) + XCTAssertEqual(copiedRow.scopes["sub"]!, ["a": 1]) + XCTAssertTrue(copiedRow.scopes["sub"]!.scopes.isEmpty) + XCTAssertEqual(copiedRow.scopesTree.names, ["sub"]) + XCTAssertEqual(copiedRow.scopesTree["sub"]!, ["a": 1]) } else { XCTFail() } @@ -621,9 +703,9 @@ class AdapterRowTests : RowTestCase { (row1, row3, true), (row1, row4, false), (row1, row5, false), - (row1.scoped(on: "sub"), row3.scoped(on: "sub"), true), - (row1.scoped(on: "sub"), row4.scoped(on: "sub"), true), - (row1.scoped(on: "sub"), row5.scoped(on: "sub"), false)] + (row1.scopes["sub"], row3.scopes["sub"], true), + (row1.scopes["sub"], row4.scopes["sub"], true), + (row1.scopes["sub"], row5.scopes["sub"], false)] for (lrow, rrow, equal) in tests { if equal { XCTAssertEqual(lrow, rrow) @@ -676,73 +758,78 @@ class AdapterRowTests : RowTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) - .asRequest(of: Row.self) + let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) .fetchOne(db)! XCTAssertEqual(Array(row.columnNames), ["a1", "a2"]) XCTAssertEqual(Array(row.databaseValues), [1.databaseValue, 2.databaseValue]) } do { - let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2") + let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2") .adapted { _ in SuffixRowAdapter(fromIndex: 1) } - .asRequest(of: Row.self) .fetchOne(db)! XCTAssertEqual(Array(row.columnNames), ["a1", "a2"]) XCTAssertEqual(Array(row.databaseValues), [1.databaseValue, 2.databaseValue]) } do { - let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) + let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) .adapted { _ in SuffixRowAdapter(fromIndex: 1) } - .asRequest(of: Row.self) .fetchOne(db)! XCTAssertEqual(Array(row.columnNames), ["a2"]) XCTAssertEqual(Array(row.databaseValues), [2.databaseValue]) } do { - let row = try SQLRequest("SELECT 0 AS a0", adapter: ColumnMapping(["a1": "a0"])) + let row = try SQLRequest("SELECT 0 AS a0", adapter: ColumnMapping(["a1": "a0"])) .adapted { _ in ColumnMapping(["a2": "a1"]) } - .asRequest(of: Row.self) .fetchOne(db)! XCTAssertEqual(Array(row.columnNames), ["a2"]) XCTAssertEqual(Array(row.databaseValues), [0.databaseValue]) } + do { + let row = try SQLRequest("SELECT 0 AS a0", adapter: ColumnMapping(["a1": "a0"])) + .adapted { _ in ColumnMapping(["a2": "a1"]) } + .adapted { _ in ColumnMapping(["a3": "a2"]) } + .fetchOne(db)! + XCTAssertEqual(Array(row.columnNames), ["a3"]) + XCTAssertEqual(Array(row.databaseValues), [0.databaseValue]) + } } } - - func testTypedRequestAdapter() throws { + + func testDescription() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - do { - let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) - .asRequest(of: Row.self) - .fetchOne(db)! - XCTAssertEqual(Array(row.columnNames), ["a1", "a2"]) - XCTAssertEqual(Array(row.databaseValues), [1.databaseValue, 2.databaseValue]) - } - do { - let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2") - .asRequest(of: Row.self) - .adapted { _ in SuffixRowAdapter(fromIndex: 1) } - .fetchOne(db)! - XCTAssertEqual(Array(row.columnNames), ["a1", "a2"]) - XCTAssertEqual(Array(row.databaseValues), [1.databaseValue, 2.databaseValue]) - } - do { - let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) - .asRequest(of: Row.self) - .adapted { _ in SuffixRowAdapter(fromIndex: 1) } - .fetchOne(db)! - XCTAssertEqual(Array(row.columnNames), ["a2"]) - XCTAssertEqual(Array(row.databaseValues), [2.databaseValue]) - } - do { - let row = try SQLRequest("SELECT 0 AS a0", adapter: ColumnMapping(["a1": "a0"])) - .asRequest(of: Row.self) - .adapted { _ in ColumnMapping(["a2": "a1"]) } - .fetchOne(db)! - XCTAssertEqual(Array(row.columnNames), ["a2"]) - XCTAssertEqual(Array(row.databaseValues), [0.databaseValue]) - } + let adapter = ColumnMapping(["id": "id0", "val": "val0"]) + .addingScopes([ + "a": ColumnMapping(["id": "id1", "val": "val1"]) + .addingScopes([ + "b": ColumnMapping(["id": "id2", "val": "val2"]) + .addingScopes([ + "c": SuffixRowAdapter(fromIndex:4)]), + "a": SuffixRowAdapter(fromIndex:0)]), + "b": ColumnMapping(["id": "id1", "val": "val1"]) + .addingScopes([ + "ba": ColumnMapping(["id": "id2", "val": "val2"])])]) + let row = try Row.fetchOne(db, "SELECT 0 AS id0, 'foo0' AS val0, 1 AS id1, 'foo1' AS val1, 2 as id2, 'foo2' AS val2", adapter: adapter)! + + XCTAssertEqual(row.description, "[id:0 val:\"foo0\"]") + XCTAssertEqual(row.debugDescription, """ + ▿ [id:0 val:"foo0"] + unadapted: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] + - a: [id:1 val:"foo1"] + - a: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] + - b: [id:2 val:"foo2"] + - c: [id2:2 val2:"foo2"] + - b: [id:1 val:"foo1"] + - ba: [id:2 val:"foo2"] + """) + XCTAssertEqual(row.scopes["a"]!.description, "[id:1 val:\"foo1\"]") + XCTAssertEqual(row.scopes["a"]!.debugDescription, """ + ▿ [id:1 val:"foo1"] + unadapted: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] + - a: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] + - b: [id:2 val:"foo2"] + - c: [id2:2 val2:"foo2"] + """) } } } diff --git a/Tests/GRDBTests/RowCopiedFromStatementTests.swift b/Tests/GRDBTests/RowCopiedFromStatementTests.swift index 10dff1794..10bd99e55 100644 --- a/Tests/GRDBTests/RowCopiedFromStatementTests.swift +++ b/Tests/GRDBTests/RowCopiedFromStatementTests.swift @@ -245,11 +245,13 @@ class RowCopiedFromStatementTests: RowTestCase { } } - func testVariants() throws { + func testScopes() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let row = try Row.fetchOne(db, "SELECT 'foo' AS nAmE, 1 AS foo")! - XCTAssertTrue(row.scoped(on: "missing") == nil) + XCTAssertTrue(row.scopes.isEmpty) + XCTAssertTrue(row.scopes["missing"] == nil) + XCTAssertTrue(row.scopesTree["missing"] == nil) } } @@ -279,4 +281,13 @@ class RowCopiedFromStatementTests: RowTestCase { XCTAssertEqual(row, copiedRow) } } + + func testDescription() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let row = try Row.fetchOne(db, "SELECT NULL AS \"null\", 1 AS \"int\", 1.1 AS \"double\", 'foo' AS \"string\", x'53514C697465' AS \"data\"")! + XCTAssertEqual(row.description, "[null:NULL int:1 double:1.1 string:\"foo\" data:Data(6 bytes)]") + XCTAssertEqual(row.debugDescription, "[null:NULL int:1 double:1.1 string:\"foo\" data:Data(6 bytes)]") + } + } } diff --git a/Tests/GRDBTests/RowFetchTests.swift b/Tests/GRDBTests/RowFetchTests.swift index 45446a830..617aba94d 100644 --- a/Tests/GRDBTests/RowFetchTests.swift +++ b/Tests/GRDBTests/RowFetchTests.swift @@ -34,8 +34,8 @@ class RowFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Row.fetchCursor(db, sql)) try test(Row.fetchCursor(statement)) - try test(Row.fetchCursor(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchCursor(db)) + try test(Row.fetchCursor(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchCursor(db)) } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" @@ -43,8 +43,8 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchCursor(db, sql, adapter: adapter)) try test(Row.fetchCursor(statement, adapter: adapter)) - try test(Row.fetchCursor(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchCursor(db)) + try test(Row.fetchCursor(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } } @@ -78,16 +78,16 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT throw(), NULL" try test(Row.fetchCursor(db, sql), sql: sql) try test(Row.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Row.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchCursor(db), sql: sql) + try test(Row.fetchCursor(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT 0, throw(), NULL" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Row.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Row.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchCursor(db), sql: sql) + try test(Row.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -110,16 +110,16 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Row.fetchCursor(db, sql), sql: sql) try test(Row.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Row.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchCursor(db), sql: sql) + try test(Row.fetchCursor(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Row.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Row.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchCursor(db), sql: sql) + try test(Row.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -136,8 +136,8 @@ class RowFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Row.fetchAll(db, sql)) try test(Row.fetchAll(statement)) - try test(Row.fetchAll(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchAll(db)) + try test(Row.fetchAll(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchAll(db)) } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" @@ -145,8 +145,8 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchAll(db, sql, adapter: adapter)) try test(Row.fetchAll(statement, adapter: adapter)) - try test(Row.fetchAll(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchAll(db)) + try test(Row.fetchAll(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } } @@ -171,16 +171,16 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Row.fetchAll(db, sql), sql: sql) try test(Row.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Row.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchAll(db), sql: sql) + try test(Row.fetchAll(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Row.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Row.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchAll(db), sql: sql) + try test(Row.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -203,16 +203,16 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Row.fetchAll(db, sql), sql: sql) try test(Row.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Row.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchAll(db), sql: sql) + try test(Row.fetchAll(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Row.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Row.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchAll(db), sql: sql) + try test(Row.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -229,8 +229,8 @@ class RowFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Row.fetchOne(db, sql)) try test(Row.fetchOne(statement)) - try test(Row.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchOne(db)) + try test(Row.fetchOne(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, 1 WHERE 0" @@ -238,8 +238,8 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql, adapter: adapter)) try test(Row.fetchOne(statement, adapter: adapter)) - try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchOne(db)) + try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } do { @@ -252,8 +252,8 @@ class RowFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Row.fetchOne(db, sql)) try test(Row.fetchOne(statement)) - try test(Row.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchOne(db)) + try test(Row.fetchOne(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName" @@ -261,8 +261,8 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql, adapter: adapter)) try test(Row.fetchOne(statement, adapter: adapter)) - try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchOne(db)) + try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } } @@ -288,16 +288,16 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Row.fetchOne(db, sql), sql: sql) try test(Row.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Row.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchOne(db), sql: sql) + try test(Row.fetchOne(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Row.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchOne(db), sql: sql) + try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } @@ -320,16 +320,16 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Row.fetchOne(db, sql), sql: sql) try test(Row.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Row.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchOne(db), sql: sql) + try test(Row.fetchOne(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Row.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchOne(db), sql: sql) + try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } diff --git a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift index a542768e8..33d959670 100644 --- a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift @@ -206,9 +206,11 @@ class RowFromDictionaryLiteralTests : RowTestCase { XCTAssertTrue(row.hasColumn("FOO")) } - func testSubRows() { + func testScopes() { let row: Row = ["a": 0, "b": 1, "c": 2] - XCTAssertTrue(row.scoped(on: "missing") == nil) + XCTAssertTrue(row.scopes.isEmpty) + XCTAssertTrue(row.scopes["missing"] == nil) + XCTAssertTrue(row.scopesTree["missing"] == nil) } func testCopy() { @@ -227,4 +229,10 @@ class RowFromDictionaryLiteralTests : RowTestCase { let copiedRow = row.copy() XCTAssertEqual(row, copiedRow) } + + func testDescription() throws { + let row: Row = ["a": 0, "b": 1, "c": 2] + XCTAssertEqual(row.description, "[a:0 b:1 c:2]") + XCTAssertEqual(row.debugDescription, "[a:0 b:1 c:2]") + } } diff --git a/Tests/GRDBTests/RowFromDictionaryTests.swift b/Tests/GRDBTests/RowFromDictionaryTests.swift index 79e457852..2fe4e414b 100644 --- a/Tests/GRDBTests/RowFromDictionaryTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryTests.swift @@ -196,9 +196,11 @@ class RowFromDictionaryTests : RowTestCase { XCTAssertTrue(row.hasColumn("FOO")) } - func testSubRows() { + func testScopes() { let row = Row(["a": 0, "b": 1, "c": 2]) - XCTAssertTrue(row.scoped(on: "missing") == nil) + XCTAssertTrue(row.scopes.isEmpty) + XCTAssertTrue(row.scopes["missing"] == nil) + XCTAssertTrue(row.scopesTree["missing"] == nil) } func testCopy() { @@ -217,4 +219,12 @@ class RowFromDictionaryTests : RowTestCase { let copiedRow = row.copy() XCTAssertEqual(row, copiedRow) } + + func testDescription() throws { + let row = Row(["a": 0, "b": "foo"]) + let variants: Set = ["[a:0 b:\"foo\"]", "[b:\"foo\" a:0]"] + XCTAssert(variants.contains(row.description)) + let debugVariants: Set = ["[a:0 b:\"foo\"]", "[b:\"foo\" a:0]"] + XCTAssert(debugVariants.contains(row.debugDescription)) + } } diff --git a/Tests/GRDBTests/RowFromStatementTests.swift b/Tests/GRDBTests/RowFromStatementTests.swift index 69ca661e5..79a281c94 100644 --- a/Tests/GRDBTests/RowFromStatementTests.swift +++ b/Tests/GRDBTests/RowFromStatementTests.swift @@ -308,14 +308,16 @@ class RowFromStatementTests : RowTestCase { } } - func testVariants() throws { + func testScopes() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var rowFetched = false let rows = try Row.fetchCursor(db, "SELECT 'foo' AS nAmE, 1 AS foo") while let row = try rows.next() { rowFetched = true - XCTAssertTrue(row.scoped(on: "missing") == nil) + XCTAssertTrue(row.scopes.isEmpty) + XCTAssertTrue(row.scopes["missing"] == nil) + XCTAssertTrue(row.scopesTree["missing"] == nil) } XCTAssertTrue(rowFetched) } @@ -367,4 +369,18 @@ class RowFromStatementTests : RowTestCase { XCTAssertTrue(try values.next() == nil) } } + + func testDescription() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let rows = try Row.fetchCursor(db, "SELECT NULL AS \"null\", 1 AS \"int\", 1.1 AS \"double\", 'foo' AS \"string\", x'53514C697465' AS \"data\"") + var rowFetched = false + while let row = try rows.next() { + rowFetched = true + XCTAssertEqual(row.description, "[null:NULL int:1 double:1.1 string:\"foo\" data:Data(6 bytes)]") + XCTAssertEqual(row.debugDescription, "[null:NULL int:1 double:1.1 string:\"foo\" data:Data(6 bytes)]") + } + XCTAssertTrue(rowFetched) + } + } } 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))") } } diff --git a/Tests/GRDBTests/SQLRequestTests.swift b/Tests/GRDBTests/SQLRequestTests.swift index 207f1f913..d54e3d1ab 100644 --- a/Tests/GRDBTests/SQLRequestTests.swift +++ b/Tests/GRDBTests/SQLRequestTests.swift @@ -12,21 +12,23 @@ class SQLRequestTests: GRDBTestCase { func testSQLRequest() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let request = SQLRequest("SELECT 1") + let request = SQLRequest("SELECT 1") let (statement, adapter) = try request.prepare(db) XCTAssertEqual(statement.sql, "SELECT 1") XCTAssertNil(adapter) + let row = try request.fetchOne(db) + XCTAssertEqual(row, ["1": 1]) } } func testSQLRequestWithArgumentsAndAdapter() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let request = SQLRequest("SELECT ?, ?", arguments: [1, 2], adapter: SuffixRowAdapter(fromIndex: 1)) + let request = SQLRequest("SELECT ?, ?", arguments: [1, 2], adapter: SuffixRowAdapter(fromIndex: 1)) let (statement, adapter) = try request.prepare(db) XCTAssertEqual(statement.sql, "SELECT ?, ?") XCTAssertNotNil(adapter) - let int = try Int.fetchOne(db, request)! + let int = try request.fetchOne(db)! XCTAssertEqual(int, 2) } } @@ -34,7 +36,7 @@ class SQLRequestTests: GRDBTestCase { func testNotCachedSQLRequest() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let request = SQLRequest("SELECT 1") + let request = SQLRequest("SELECT 1") let (statement1, _) = try request.prepare(db) let (statement2, _) = try request.prepare(db) XCTAssertTrue(statement1 !== statement2) @@ -44,25 +46,29 @@ class SQLRequestTests: GRDBTestCase { func testCachedSQLRequest() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let request = SQLRequest("SELECT 1", cached: true) + let request = SQLRequest("SELECT 1", cached: true) let (statement1, _) = try request.prepare(db) let (statement2, _) = try request.prepare(db) XCTAssertTrue(statement1 === statement2) } } - func testAsSQLRequest() throws { - struct CustomRequest: Request { + func testRequestInitializer() throws { + struct CustomRequest: FetchRequest { + typealias RowDecoder = Row func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try SQLRequest("SELECT ?, ?", arguments: [1, "foo"]).prepare(db) + let statement = try db.makeSelectStatement("SELECT ? AS a, ? AS b") + statement.arguments = [1, "foo"] + return (statement, nil) } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let request = CustomRequest() - let sqlRequest = try request.asSQLRequest(db) - XCTAssertEqual(sqlRequest.sql, "SELECT ?, ?") + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT ? AS a, ? AS b") XCTAssertEqual(sqlRequest.arguments, [1, "foo"]) + XCTAssertEqual(try sqlRequest.fetchOne(db)!, ["a": 1, "b": "foo"]) } } } diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index 52dcf4429..66b6cc1ba 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -130,7 +130,7 @@ class SelectStatementTests : GRDBTestCase { func testRegion() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in class Observer: TransactionObserver { private var didChange = false var triggered = false @@ -196,7 +196,7 @@ class SelectStatementTests : GRDBTestCase { let doubtfulCountFunction = (sqlite3_libversion_number() < 3019000) - let observers = statements.map { Observer(region: $0.fetchedRegion) } + let observers = statements.map { Observer(region: $0.databaseRegion) } if doubtfulCountFunction { XCTAssertEqual(observers.map { $0.region.description }, ["table1(a,b,id,id3,id4)","table1(a,id,id3)", "table1(a,id),table2(a,id)", "full database"]) } else { diff --git a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift index 5b3cdcb9d..97121e429 100644 --- a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift +++ b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift @@ -100,8 +100,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchCursor(db, sql)) try test(Fetched.fetchCursor(statement)) - try test(Fetched.fetchCursor(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db)) + try test(Fetched.fetchCursor(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchCursor(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" @@ -109,8 +109,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter)) try test(Fetched.fetchCursor(statement, adapter: adapter)) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db)) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } } @@ -144,16 +144,16 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -176,16 +176,16 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -202,8 +202,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchAll(db, sql)) try test(Fetched.fetchAll(statement)) - try test(Fetched.fetchAll(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db)) + try test(Fetched.fetchAll(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchAll(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" @@ -211,8 +211,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter)) try test(Fetched.fetchAll(statement, adapter: adapter)) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db)) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } } @@ -237,16 +237,16 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -269,16 +269,16 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -295,8 +295,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, 1 WHERE 0" @@ -304,8 +304,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } do { @@ -317,8 +317,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, NULL" @@ -326,8 +326,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } do { @@ -339,8 +339,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, 1" @@ -348,8 +348,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } } @@ -375,16 +375,16 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } @@ -407,16 +407,16 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } @@ -438,8 +438,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Optional.fetchCursor(db, sql)) try test(Optional.fetchCursor(statement)) - try test(Optional.fetchCursor(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchCursor(db)) + try test(Optional.fetchCursor(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchCursor(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" @@ -447,8 +447,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter)) try test(Optional.fetchCursor(statement, adapter: adapter)) - try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchCursor(db)) + try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } } @@ -471,16 +471,16 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchCursor(db, sql), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchCursor(db), sql: sql) + try test(Optional.fetchCursor(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchCursor(db), sql: sql) + try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -499,8 +499,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Optional.fetchAll(db, sql)) try test(Optional.fetchAll(statement)) - try test(Optional.fetchAll(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchAll(db)) + try test(Optional.fetchAll(db, SQLRequest(sql))) + try test(SQLRequest(sql).fetchAll(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" @@ -508,8 +508,8 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter)) try test(Optional.fetchAll(statement, adapter: adapter)) - try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchAll(db)) + try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter))) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } } @@ -534,16 +534,16 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Optional.fetchAll(db, sql), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -566,16 +566,16 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchAll(db, sql), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index f70fa0c16..b25ec0aa2 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -65,6 +65,32 @@ class TableDefinitionTests: GRDBTestCase { } } + func testAutoIncrementedPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inTransaction { db in + try db.create(table: "test") { t in + t.autoIncrementedPrimaryKey("id") + } + assertEqualSQL(lastSQLQuery, """ + CREATE TABLE "test" (\ + "id" INTEGER PRIMARY KEY AUTOINCREMENT\ + ) + """) + return .rollback + } + try dbQueue.inTransaction { db in + try db.create(table: "test") { t in + t.autoIncrementedPrimaryKey("id", onConflict: .fail) + } + assertEqualSQL(lastSQLQuery, """ + CREATE TABLE "test" (\ + "id" INTEGER PRIMARY KEY ON CONFLICT FAIL AUTOINCREMENT\ + ) + """) + return .rollback + } + } + func testColumnPrimaryKeyOptions() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in diff --git a/Tests/GRDBTests/TableMappingTests.swift b/Tests/GRDBTests/TableMappingTests.swift deleted file mode 100644 index c310cf690..000000000 --- a/Tests/GRDBTests/TableMappingTests.swift +++ /dev/null @@ -1,49 +0,0 @@ -import XCTest -#if GRDBCIPHER - import GRDBCipher -#elseif GRDBCUSTOMSQLITE - import GRDBCustomSQLite -#else - import GRDB -#endif - -class TableMappingTests: GRDBTestCase { - - func testDefaultDatabaseSelection() throws { - struct Record: TableMapping { - static let databaseTableName = "t1" - } - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE t1(a,b,c)") - _ = try Record.all().asRequest(of: Row.self).fetchAll(db) - XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"t1\"") - } - } - - func testExtendedDatabaseSelection() throws { - struct Record: TableMapping { - static let databaseTableName = "t1" - static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] - } - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE t1(a,b,c)") - _ = try Record.all().asRequest(of: Row.self).fetchAll(db) - XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"t1\"") - } - } - - func testRestrictedDatabaseSelection() throws { - struct Record: TableMapping { - static let databaseTableName = "t1" - static let databaseSelection: [SQLSelectable] = [Column("a"), Column("b")] - } - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE t1(a,b,c)") - _ = try Record.all().asRequest(of: Row.self).fetchAll(db) - XCTAssertEqual(lastSQLQuery, "SELECT \"a\", \"b\" FROM \"t1\"") - } - } -} diff --git a/Tests/GRDBTests/TableMapping+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift similarity index 97% rename from Tests/GRDBTests/TableMapping+QueryInterfaceRequestTests.swift rename to Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index a3ac07434..52bee069f 100644 --- a/Tests/GRDBTests/TableMapping+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -14,12 +14,12 @@ private struct Col { static let readerId = Column("readerId") } -private struct Reader : TableMapping { +private struct Reader : TableRecord { static let databaseTableName = "readers" } -class TableMappingQueryInterfaceRequestTests: GRDBTestCase { +class TableRecordQueryInterfaceRequestTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { var migrator = DatabaseMigrator() @@ -166,21 +166,21 @@ class TableMappingQueryInterfaceRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, Reader.filter(sql: "id <> 1")), - "SELECT * FROM \"readers\" WHERE id <> 1") + "SELECT * FROM \"readers\" WHERE (id <> 1)") } func testFilterLiteralWithPositionalArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, Reader.filter(sql: "id <> ?", arguments: [1])), - "SELECT * FROM \"readers\" WHERE id <> 1") + "SELECT * FROM \"readers\" WHERE (id <> 1)") } func testFilterLiteralWithNamedArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, Reader.filter(sql: "id <> :id", arguments: ["id": 1])), - "SELECT * FROM \"readers\" WHERE id <> 1") + "SELECT * FROM \"readers\" WHERE (id <> 1)") } func testFilter() throws { diff --git a/Tests/GRDBTests/TableRecordTests.swift b/Tests/GRDBTests/TableRecordTests.swift new file mode 100644 index 000000000..e33b18046 --- /dev/null +++ b/Tests/GRDBTests/TableRecordTests.swift @@ -0,0 +1,136 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct RecordStruct: TableRecord { } +private struct CustomizedRecordStruct: TableRecord { static let databaseTableName = "CustomizedRecordStruct" } +private class RecordClass: TableRecord { } +private class RecordSubClass: RecordClass { } +private class CustomizedRecordClass: TableRecord { class var databaseTableName: String { return "CustomizedRecordClass" } } +private class CustomizedRecordSubClass: CustomizedRecordClass { override class var databaseTableName: String { return "CustomizedRecordSubClass" } } +private class CustomizedPlainRecord: Record { override class var databaseTableName: String { return "CustomizedPlainRecord" } } +private enum Namespace { + struct RecordStruct: TableRecord { } + struct CustomizedRecordStruct: TableRecord { static let databaseTableName = "CustomizedRecordStruct" } + class RecordClass: TableRecord { } + class RecordSubClass: RecordClass { } + class CustomizedRecordClass: TableRecord { class var databaseTableName: String { return "CustomizedRecordClass" } } + class CustomizedRecordSubClass: CustomizedRecordClass { override class var databaseTableName: String { return "CustomizedRecordSubClass" } } + class CustomizedPlainRecord: Record { override class var databaseTableName: String { return "CustomizedPlainRecord" } } +} +struct HTTPRequest: TableRecord { } +struct TOEFL: TableRecord { } + +class TableRecordTests: GRDBTestCase { + + func testDefaultDatabaseTableName() { + struct InnerRecordStruct: TableRecord { } + struct InnerCustomizedRecordStruct: TableRecord { static let databaseTableName = "InnerCustomizedRecordStruct" } + class InnerRecordClass: TableRecord { } + class InnerRecordSubClass: InnerRecordClass { } + class InnerCustomizedRecordClass: TableRecord { class var databaseTableName: String { return "InnerCustomizedRecordClass" } } + class InnerCustomizedRecordSubClass: InnerCustomizedRecordClass { override class var databaseTableName: String { return "InnerCustomizedRecordSubClass" } } + class InnerCustomizedPlainRecord: Record { override class var databaseTableName: String { return "InnerCustomizedPlainRecord" } } + + XCTAssertEqual(RecordStruct.databaseTableName, "recordStruct") + XCTAssertEqual(CustomizedRecordStruct.databaseTableName, "CustomizedRecordStruct") + XCTAssertEqual(RecordClass.databaseTableName, "recordClass") + XCTAssertEqual(RecordSubClass.databaseTableName, "recordSubClass") + XCTAssertEqual(CustomizedRecordClass.databaseTableName, "CustomizedRecordClass") + XCTAssertEqual(CustomizedRecordSubClass.databaseTableName, "CustomizedRecordSubClass") + XCTAssertEqual(CustomizedPlainRecord.databaseTableName, "CustomizedPlainRecord") + + XCTAssertEqual(Namespace.RecordStruct.databaseTableName, "recordStruct") + XCTAssertEqual(Namespace.CustomizedRecordStruct.databaseTableName, "CustomizedRecordStruct") + XCTAssertEqual(Namespace.RecordClass.databaseTableName, "recordClass") + XCTAssertEqual(Namespace.RecordSubClass.databaseTableName, "recordSubClass") + XCTAssertEqual(Namespace.CustomizedRecordClass.databaseTableName, "CustomizedRecordClass") + XCTAssertEqual(Namespace.CustomizedRecordSubClass.databaseTableName, "CustomizedRecordSubClass") + XCTAssertEqual(Namespace.CustomizedPlainRecord.databaseTableName, "CustomizedPlainRecord") + + XCTAssertEqual(InnerRecordStruct.databaseTableName, "innerRecordStruct") + XCTAssertEqual(InnerCustomizedRecordStruct.databaseTableName, "InnerCustomizedRecordStruct") + XCTAssertEqual(InnerRecordClass.databaseTableName, "innerRecordClass") + XCTAssertEqual(InnerRecordSubClass.databaseTableName, "innerRecordSubClass") + XCTAssertEqual(InnerCustomizedRecordClass.databaseTableName, "InnerCustomizedRecordClass") + XCTAssertEqual(InnerCustomizedRecordSubClass.databaseTableName, "InnerCustomizedRecordSubClass") + XCTAssertEqual(InnerCustomizedPlainRecord.databaseTableName, "InnerCustomizedPlainRecord") + + XCTAssertEqual(HTTPRequest.databaseTableName, "httpRequest") + XCTAssertEqual(TOEFL.databaseTableName, "toefl") + + func tableName(_ type: T.Type) -> String { + return T.databaseTableName + } + + XCTAssertEqual(tableName(RecordStruct.self), "recordStruct") + XCTAssertEqual(tableName(CustomizedRecordStruct.self), "CustomizedRecordStruct") + XCTAssertEqual(tableName(RecordClass.self), "recordClass") + XCTAssertEqual(tableName(RecordSubClass.self), "recordSubClass") + XCTAssertEqual(tableName(CustomizedRecordClass.self), "CustomizedRecordClass") + XCTAssertEqual(tableName(CustomizedRecordSubClass.self), "CustomizedRecordSubClass") + XCTAssertEqual(tableName(CustomizedPlainRecord.self), "CustomizedPlainRecord") + + XCTAssertEqual(tableName(Namespace.RecordStruct.self), "recordStruct") + XCTAssertEqual(tableName(Namespace.CustomizedRecordStruct.self), "CustomizedRecordStruct") + XCTAssertEqual(tableName(Namespace.RecordClass.self), "recordClass") + XCTAssertEqual(tableName(Namespace.RecordSubClass.self), "recordSubClass") + XCTAssertEqual(tableName(Namespace.CustomizedRecordClass.self), "CustomizedRecordClass") + XCTAssertEqual(tableName(Namespace.CustomizedRecordSubClass.self), "CustomizedRecordSubClass") + XCTAssertEqual(tableName(Namespace.CustomizedPlainRecord.self), "CustomizedPlainRecord") + + XCTAssertEqual(tableName(InnerRecordStruct.self), "innerRecordStruct") + XCTAssertEqual(tableName(InnerCustomizedRecordStruct.self), "InnerCustomizedRecordStruct") + XCTAssertEqual(tableName(InnerRecordClass.self), "innerRecordClass") + XCTAssertEqual(tableName(InnerRecordSubClass.self), "innerRecordSubClass") + XCTAssertEqual(tableName(InnerCustomizedRecordClass.self), "InnerCustomizedRecordClass") + XCTAssertEqual(tableName(InnerCustomizedRecordSubClass.self), "InnerCustomizedRecordSubClass") + XCTAssertEqual(tableName(InnerCustomizedPlainRecord.self), "InnerCustomizedPlainRecord") + + XCTAssertEqual(tableName(HTTPRequest.self), "httpRequest") + XCTAssertEqual(tableName(TOEFL.self), "toefl") + } + + func testDefaultDatabaseSelection() throws { + struct Record: TableRecord { + static let databaseTableName = "t1" + } + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE t1(a,b,c)") + _ = try Row.fetchAll(db, Record.all()) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"t1\"") + } + } + + func testExtendedDatabaseSelection() throws { + struct Record: TableRecord { + static let databaseTableName = "t1" + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + } + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE t1(a,b,c)") + _ = try Row.fetchAll(db, Record.all()) + XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"t1\"") + } + } + + func testRestrictedDatabaseSelection() throws { + struct Record: TableRecord { + static let databaseTableName = "t1" + static let databaseSelection: [SQLSelectable] = [Column("a"), Column("b")] + } + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE t1(a,b,c)") + _ = try Row.fetchAll(db, Record.all()) + XCTAssertEqual(lastSQLQuery, "SELECT \"a\", \"b\" FROM \"t1\"") + } + } +} diff --git a/Tests/GRDBTests/TransactionObserverSavepointsTests.swift b/Tests/GRDBTests/TransactionObserverSavepointsTests.swift index f57a847b3..66cfdd935 100644 --- a/Tests/GRDBTests/TransactionObserverSavepointsTests.swift +++ b/Tests/GRDBTests/TransactionObserverSavepointsTests.swift @@ -80,7 +80,7 @@ class TransactionObserverSavepointsTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)") try db.execute("SAVEPOINT sp1") @@ -112,7 +112,7 @@ class TransactionObserverSavepointsTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)") try db.execute("BEGIN TRANSACTION") @@ -143,7 +143,7 @@ class TransactionObserverSavepointsTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items3 (id INTEGER PRIMARY KEY)") @@ -191,7 +191,7 @@ class TransactionObserverSavepointsTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items3 (id INTEGER PRIMARY KEY)") @@ -234,7 +234,7 @@ class TransactionObserverSavepointsTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items3 (id INTEGER PRIMARY KEY)") @@ -278,7 +278,7 @@ class TransactionObserverSavepointsTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items3 (id INTEGER PRIMARY KEY)") diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index a5a586429..2631b1bc4 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -100,7 +100,7 @@ private final class Artist: Codable { } } -extension Artist : RowConvertible, Persistable { +extension Artist : FetchableRecord, PersistableRecord { static let databaseTableName = "artists" func didInsert(with rowID: Int64, for column: String?) { self.id = rowID @@ -119,7 +119,7 @@ private final class Artwork : Codable { } } -extension Artwork : RowConvertible, Persistable { +extension Artwork : FetchableRecord, PersistableRecord { static let databaseTableName = "artworks" func didInsert(with rowID: Int64, for column: String?) { self.id = rowID @@ -224,7 +224,7 @@ class TransactionObserverTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() let observer = Observer() dbQueue.add(transactionObserver: observer, extent: extent) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -246,7 +246,7 @@ class TransactionObserverTests: GRDBTestCase { for extent in extents { let dbQueue = try makeDatabaseQueue() let observer = Observer() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) db.add(transactionObserver: observer, extent: extent) try db.execute(endSQL) @@ -271,7 +271,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() weakObserver = observer dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -310,7 +310,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() weakObserver = observer dbQueue.add(transactionObserver: observer, extent: .observerLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -351,7 +351,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer, extent: .nextTransaction) } if let observer = weakObserver { - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -376,7 +376,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer, extent: .nextTransaction) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -418,7 +418,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: witness) dbQueue.add(transactionObserver: observer, extent: .nextTransaction) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -484,7 +484,7 @@ class TransactionObserverTests: GRDBTestCase { } if let observer = weakObserver { - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -546,7 +546,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer3, extent: extent) do { - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -595,7 +595,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let artist = Artist(id: nil, name: "Gerhard Richter") // @@ -626,7 +626,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let artist = Artist(id: nil, name: "Gerhard Richter") try artist.save(db) artist.name = "Vincent Fournier" @@ -662,7 +662,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let artist = Artist(id: nil, name: "Gerhard Richter") try artist.save(db) @@ -694,7 +694,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let artist = Artist(id: nil, name: "Gerhard Richter") try artist.save(db) let artwork1 = Artwork(id: nil, artistId: artist.id, title: "Cloud") @@ -761,7 +761,7 @@ class TransactionObserverTests: GRDBTestCase { let artist = Artist(id: nil, name: "Gerhard Richter") - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in observer.resetCounts() try artist.save(db) #if SQLITE_ENABLE_PREUPDATE_HOOK @@ -784,7 +784,7 @@ class TransactionObserverTests: GRDBTestCase { let artwork1 = Artwork(id: nil, artistId: nil, title: "Cloud") let artwork2 = Artwork(id: nil, artistId: nil, title: "Ema (Nude on a Staircase)") - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try artist.save(db) artwork1.artistId = artist.id artwork2.artistId = artist.id @@ -1116,7 +1116,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer) do { - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in do { try Artwork(id: nil, artistId: nil, title: "meh").save(db) XCTFail("Expected Error") @@ -1190,7 +1190,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer) observer.commitError = NSError(domain: "foo", code: 0, userInfo: nil) - dbQueue.inDatabase { db in + dbQueue.writeWithoutTransaction { db in do { try Artist(id: nil, name: "Gerhard Richter").save(db) XCTFail("Expected Error") @@ -1246,7 +1246,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer) do { - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in do { try Artwork(id: nil, artistId: nil, title: "meh").save(db) XCTFail("Expected Error") @@ -1329,7 +1329,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try MinimalRowID.setup(inDatabase: db) let record = MinimalRowID() @@ -1357,7 +1357,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer1) dbQueue.add(transactionObserver: observer2) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let artist = Artist(id: nil, name: "Gerhard Richter") // @@ -1410,7 +1410,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let artist = Artist(id: nil, name: "Gerhard Richter") // @@ -1690,7 +1690,7 @@ class TransactionObserverTests: GRDBTestCase { } } - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in // Don't ignore anything do { observer.resetCounts() diff --git a/Tests/GRDBTests/TruncateOptimizationTests.swift b/Tests/GRDBTests/TruncateOptimizationTests.swift index 6334d3044..7617539f0 100644 --- a/Tests/GRDBTests/TruncateOptimizationTests.swift +++ b/Tests/GRDBTests/TruncateOptimizationTests.swift @@ -75,7 +75,7 @@ class TruncateOptimizationTests: GRDBTestCase { let observer = DeletionObserver { deletionEvents.append($0) } dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") @@ -100,7 +100,7 @@ class TruncateOptimizationTests: GRDBTestCase { let observer = DeletionObserver { deletionEvents.append($0) } dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") let deleteStatement = try db.makeUpdateStatement("DELETE FROM t") @@ -121,7 +121,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTable() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -133,7 +133,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTable() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -144,7 +144,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -157,7 +157,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -169,7 +169,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryTable() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -181,7 +181,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryTable() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -192,7 +192,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -205,7 +205,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -217,7 +217,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropVirtualTable() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -229,7 +229,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropVirtualTable() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -240,7 +240,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropVirtualTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -253,7 +253,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropVirtualTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -265,7 +265,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropView() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -278,7 +278,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropView() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -290,7 +290,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -304,7 +304,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -317,7 +317,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryView() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -330,7 +330,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryView() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -342,7 +342,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -356,7 +356,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -369,7 +369,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropIndex() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) @@ -381,7 +381,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropIndex() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) @@ -392,7 +392,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropIndexViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try db.execute("INSERT INTO t VALUES (1)") @@ -406,7 +406,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropIndexViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try db.execute("INSERT INTO t VALUES (1)") @@ -419,7 +419,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryIndex() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) @@ -431,7 +431,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryIndex() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) @@ -442,7 +442,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryIndexViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try db.execute("INSERT INTO t VALUES (1)") @@ -456,7 +456,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryIndexViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try db.execute("INSERT INTO t VALUES (1)") @@ -469,7 +469,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTrigger() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -481,7 +481,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTrigger() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -492,7 +492,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTriggerWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -505,7 +505,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTriggerWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -517,7 +517,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryTrigger() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -529,7 +529,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryTrigger() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -540,7 +540,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryTriggerWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -553,7 +553,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryTriggerWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) diff --git a/Tests/Performance/PerformanceTests.swift b/Tests/Performance/PerformanceTests.swift index 8400778b9..a606b2f30 100644 --- a/Tests/Performance/PerformanceTests.swift +++ b/Tests/Performance/PerformanceTests.swift @@ -7,7 +7,7 @@ import RealmSwift // MARK:- GRDB -struct ItemStruct : RowConvertible, Persistable { +struct ItemStruct : FetchableRecord, PersistableRecord { var i0: Int var i1: Int var i2: Int diff --git a/Tests/generatePerformanceReport.rb b/Tests/generatePerformanceReport.rb index f57c96d94..ac5bc49eb 100755 --- a/Tests/generatePerformanceReport.rb +++ b/Tests/generatePerformanceReport.rb @@ -48,7 +48,7 @@ All tests use the default settings of each library. For each library, we: - Build and consume database rows with raw SQL and column indexes (aiming at the best performance) - Build and consume database rows with column names (sacrificing performance for maintainability) - Build and consume records values to and from database rows (aiming at the shortest code from database to records) -- Build and consume records values to and from database rows, with [change tracking](https://github.com/groue/GRDB.swift#changes-tracking) (records know if they have unsaved changes) +- Build and consume records values to and from database rows, with [change tracking](https://github.com/groue/GRDB.swift/blob/master/README.md#record-comparison) (records know if they have unsaved changes) As a bottom line, the raw SQLite C API is used as efficiently as possible, without any error checking. @@ -103,11 +103,11 @@ As a bottom line, the raw SQLite C API is used as efficiently as possible, witho This test fetches an array of 100000 record objects initiated from rows of 10 ints. - It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [RowConvertible](https://github.com/groue/GRDB.swift#rowconvertible-protocol) protocol, and the values returned by the high-level query builder of SQLite.swift. + It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [FetchableRecord](https://github.com/groue/GRDB.swift/blob/master/README.md#fetchablerecord-protocol) protocol, and the values returned by the high-level query builder of SQLite.swift. - **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/InsertRecordStructTests.swift)) - This tests inserts 20000 records with the persistence method provided by GRDB's [Persistable](https://github.com/groue/GRDB.swift#persistable-protocol) protocol. + This tests inserts 20000 records with the persistence method provided by GRDB's [PersistableRecord](https://github.com/groue/GRDB.swift/blob/master/README.md#persistablerecord-protocol) protocol. - **Records with change tracking**: @@ -115,9 +115,9 @@ As a bottom line, the raw SQLite C API is used as efficiently as possible, witho This test fetches an array of 100000 record objects initiated from rows of 10 ints. - It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [Record](https://github.com/groue/GRDB.swift#record-class) class. + It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [Record](https://github.com/groue/GRDB.swift/blob/master/README.md#record-class) class. - **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/InsertRecordClassTests.swift)) - This tests inserts 20000 records with the persistence method provided by GRDB's [Record](https://github.com/groue/GRDB.swift#record-class) class. + This tests inserts 20000 records with the persistence method provided by GRDB's [Record](https://github.com/groue/GRDB.swift/blob/master/README.md#record-class) class. REPORT