diff --git a/.swiftlint.yml b/.swiftlint.yml index 3afb2e518..3d7960402 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -61,4 +61,3 @@ opt_in_rules: vertical_whitespace: max_empty_lines: 2 - diff --git a/.travis.yml b/.travis.yml index 3cdb4666e..f81d5ff2b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -41,121 +41,121 @@ jobs: script: make test_framework_GRDBiOS_minTarget ########################################### - ## Test GRDB Xcode 12.2 + ## Test GRDB Xcode 12.5 - - name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.3" + - name: "Test GRDB Xcode 12.5 - GRDBOSX - Swift 5.3" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_framework_GRDBOSX_maxSwift - - name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.2" + - name: "Test GRDB Xcode 12.5 - GRDBOSX - Swift 5.2" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_framework_GRDBOSX_minSwift - - name: "Test GRDB Xcode 12.2 - GRDBWatchOS" + - name: "Test GRDB Xcode 12.5 - GRDBWatchOS" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_framework_GRDBWatchOS - - name: "Test GRDB Xcode 12.2 - GRDBiOS iOS maxTarget" + - name: "Test GRDB Xcode 12.5 - GRDBiOS iOS maxTarget" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_framework_GRDBiOS_maxTarget_maxSwift - - name: "Test GRDB Xcode 12.2 - GRDBiOS iOS minTarget" + - name: "Test GRDB Xcode 12.5 - GRDBiOS iOS minTarget" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_framework_GRDBiOS_minTarget - - name: "Test GRDB Xcode 12.2 - GRDBtvOS maxTarget" + - name: "Test GRDB Xcode 12.5 - GRDBtvOS maxTarget" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_framework_GRDBtvOS_maxTarget_maxSwift - - name: "Test GRDB Xcode 12 - GRDBtvOS minTarget" + - name: "Test GRDB Xcode 12.5 - GRDBtvOS minTarget" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_framework_GRDBtvOS_minTarget - - name: "Test GRDB Xcode 12.2 - SPM" + - name: "Test GRDB Xcode 12.5 - SPM" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_SPM ########################################### - ## Test GRDBCustom Xcode 12.2 + ## Test GRDBCustom Xcode 12.5 - - name: "Test GRDBCustom Xcode 12.2 - GRDBOSX" + - name: "Test GRDBCustom Xcode 12.5 - GRDBOSX" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_framework_GRDBCustomSQLiteOSX - - name: "Test GRDBCustom Xcode 12.2 - GRDBiOS maxTarget" + - name: "Test GRDBCustom Xcode 12.5 - GRDBiOS maxTarget" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift - - name: "Test GRDBCustom Xcode 12.2 - GRDBiOS minTarget" + - name: "Test GRDBCustom Xcode 12.5 - GRDBiOS minTarget" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_framework_GRDBCustomSQLiteiOS_minTarget ########################################### - ## Test SQLCipher Xcode 12.2 + ## Test SQLCipher Xcode 12.5 - - name: "Test SQLCipher Xcode 12.2 - SQLCipher 3" + - name: "Test SQLCipher Xcode 12.5 - SQLCipher 3" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_framework_SQLCipher3 - - name: "Test SQLCipher Xcode 12.2 - SQLCipher 4" + - name: "Test SQLCipher Xcode 12.5 - SQLCipher 4" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_framework_SQLCipher4 ########################################### - ## Test Installation Xcode 12.2 + ## Test Installation Xcode 12.5 # Manual Install - - name: "Test Installation Xcode 12.2 - Manual Install" + - name: "Test Installation Xcode 12.5 - Manual Install" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_install_manual # Travis is much too slow, and always fail this job # # CocoaPods Lint - # - name: "Test Installation Xcode 12.2 - CocoaPods Lint" + # - name: "Test Installation Xcode 12.5 - CocoaPods Lint" # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode12.2 + # osx_image: xcode12.5 # script: make test_CocoaPodsLint_GRDB # CocoaPods Install GRDB - - name: "Test Installation Xcode 12.2 - CocoaPods Framework" + - name: "Test Installation Xcode 12.5 - CocoaPods Framework" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_install_GRDB_CocoaPods_framework # CocoaPods Install GRDB - - name: "Test Installation Xcode 12.2 - CocoaPods Static" + - name: "Test Installation Xcode 12.5 - CocoaPods Static" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_install_GRDB_CocoaPods_static # SPM Install - - name: "Test Installation Xcode 12.2 - SPM Package" + - name: "Test Installation Xcode 12.5 - SPM Package" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_install_SPM_Package # SPM Install - - name: "Test Installation Xcode 12.2 - SPM Package in Xcode Project" + - name: "Test Installation Xcode 12.5 - SPM Package in Xcode Project" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_install_SPM_Project # Custom SQLite Install - - name: "Test Installation Xcode 12.2 - Custom SQLite" + - name: "Test Installation Xcode 12.5 - Custom SQLite" gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode12.2 + osx_image: xcode12.5 script: make test_install_customSQLite diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e5ecb1e3..12a9f51d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 5.x Releases -- [Development Branch](#development-branch) +- `5.9.x` Releases - [5.9.0](#590) - `5.8.x` Releases - [5.8.0](#580) - `5.7.x` Releases - [5.7.0](#570) | [5.7.1](#571) | [5.7.2](#572) | [5.7.3](#573) | [5.7.4](#574) - `5.6.x` Releases - [5.6.0](#560) @@ -76,9 +76,32 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- -## Development Branch +## 5.9.0 + +Released August 15, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.8.0...v5.9.0) - **Fixed**: [#980](https://github.com/groue/GRDB.swift/pull/980) by [@jroselightricks](https://github.com/jroselightricks): Fix spelling +- **Fixed**: [#989](https://github.com/groue/GRDB.swift/pull/989) by [@pp5x](https://github.com/pp5x): FTS: add support of ifNotExists in synchronize() +- **Fixed**: [#999](https://github.com/groue/GRDB.swift/issues/999): `request(for: association)` no longer crashes when the foreign key contains a NULL value. +- **Fixed**: [#1025](https://github.com/groue/GRDB.swift/issues/1025) by [@mattgallagher](https://github.com/mattgallagher): Fix ValueObservation crash +- **Fixed**: Fix thread unsafety in `ValueObservation.print()` +- **New**: The `selectID()` method is now available for [Identifiable Records](README.md#identifiable-records) +- **New**: Cached prepared statements can profit from [SQL Interpolation](Documentation/SQLInterpolation.md): + + ```swift + let updateStatement = try db.cachedStatement(literal: "INSERT ...") + // ~~~~~~~ + ``` + +- **New**: [#993](https://github.com/groue/GRDB.swift/pull/993) by [@groue](https://github.com/groue): QueryInterfaceRequest builder with dynamic table/view name +- **New**: Types that adopt both `DatabaseValueConvertible` and `Codable` now profit from automatic JSON encoding and decoding. +- **New**: [#1010](https://github.com/groue/GRDB.swift/pull/1010) by [@tternes](https://github.com/tternes): Add VACUUM INTO Support +- **New**: [#1012](https://github.com/groue/GRDB.swift/pull/1012) by [@ZevEisenberg](https://github.com/ZevEisenberg): Add brackets to urls in doc comments to make them clickable +- **New**: [#1019](https://github.com/groue/GRDB.swift/pull/1019) by [@groue](https://github.com/groue): Merge prepared statement types, and introduce statement cursor +- **Documentation Update**: The [Requests](README.md#requests) chapter was updated for the new `Table` type that can build requests without any record type. +- **Documentation Update**: The [Custom Value Types](README.md#custom-value-types) chapter was extended about the new support for codable value types encoded as JSON arrays or objects. +- **Documentation Update**: The [Fetching Methods](README.md#fetching-methods) and [Prepared Statements](README.md#prepared-statements) chapters have been updated for the unique `Statement` class, and the new `Database.allStatements()` method. + ## 5.8.0 diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift index 292168671..5392728fe 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift @@ -4,7 +4,7 @@ import GRDB /// AppDatabase lets the application access the database. /// /// It applies the pratices recommended at -/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md +/// struct AppDatabase { /// Creates an `AppDatabase`, and make sure the database schema is ready. init(_ dbWriter: DatabaseWriter) throws { @@ -17,12 +17,12 @@ struct AppDatabase { /// Application can use a `DatabasePool`, while SwiftUI previews and tests /// can use a fast in-memory `DatabaseQueue`. /// - /// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections + /// See private let dbWriter: DatabaseWriter /// The DatabaseMigrator that defines the database schema. /// - /// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md + /// See private var migrator: DatabaseMigrator { var migrator = DatabaseMigrator() diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift index 56282df2c..1d414bd68 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift @@ -51,7 +51,7 @@ extension Player { /// Make Player a Codable Record. /// -/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records +/// See extension Player: Codable, FetchableRecord, MutablePersistableRecord { // Define database columns from CodingKeys fileprivate enum Columns { @@ -69,8 +69,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { /// Define some player requests used by the application. /// -/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests -/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md +/// See +/// See extension DerivableRequest where RowDecoder == Player { /// A request of players ordered by name. /// diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index 7c2aa8a5d..f62ab6e0d 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -3,7 +3,7 @@ import GRDB /// AppDatabase lets the application access the database. /// /// It applies the pratices recommended at -/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md +/// final class AppDatabase { /// Creates an `AppDatabase`, and make sure the database schema is ready. init(_ dbWriter: DatabaseWriter) throws { @@ -16,12 +16,12 @@ final class AppDatabase { /// Application can use a `DatabasePool`, and tests can use a fast /// in-memory `DatabaseQueue`. /// - /// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections + /// See private let dbWriter: DatabaseWriter /// The DatabaseMigrator that defines the database schema. /// - /// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md + /// See private var migrator: DatabaseMigrator { var migrator = DatabaseMigrator() diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift index 8f60b7c31..dc6de77f2 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift @@ -50,7 +50,7 @@ extension Player { /// Make Player a Codable Record. /// -/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records +/// See extension Player: Codable, FetchableRecord, MutablePersistableRecord { // Define database columns from CodingKeys fileprivate enum Columns { @@ -68,8 +68,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { /// Define some player requests used by the application. /// -/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests -/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md +/// See +/// See extension DerivableRequest where RowDecoder == Player { /// A request of players ordered by name. /// diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 2203cf57c..963f31811 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.8/Structs/StatementArguments.html): +FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.8/Structs/StatementArguments.html): +FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index 0796579de..1dec073ad 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -68,7 +68,7 @@ try dbQueue.read { db in } ``` -See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.8/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.9/Structs/DatabaseMigrator.html) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option diff --git a/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift b/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift index bbc0856d6..ca53da88d 100644 --- a/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift +++ b/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift @@ -212,30 +212,30 @@ extension Base: MyDatabaseDecoder { //: **prepared statement**: //: //: try dbQueue.read { db in -//: let statement = try db.makeSelectStatement(sql: "SELECT ...") +//: let statement = try db.makeStatement(sql: "SELECT ...") //: try Base.fetchCursor(statement) // Cursor of Base //: try Base.fetchAll(statement) // [Base] //: try Base.fetchOne(statement) // Base? //: } extension MyDatabaseDecoder { - // MARK: - Fetch from SelectStatement + // MARK: - Fetch from Prepared Statement - // SelectStatement, StatementArguments, and RowAdapter are the fundamental + // Statement, 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 { + static func fetchCursor(_ statement: Statement, 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] { + static func fetchAll(_ statement: Statement, 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? { + static func fetchOne(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? { // Consume the first value of the cursor return try fetchCursor(statement, arguments: arguments, adapter: adapter).next() } @@ -243,7 +243,7 @@ extension MyDatabaseDecoder { try dbQueue.read { db in print("> Fetch from prepared statement") - let statement = try db.makeSelectStatement(sql: "SELECT * FROM base") + let statement = try db.makeStatement(sql: "SELECT * FROM base") let bases = try Base.fetchAll(statement) for base in bases { print(base.description) @@ -422,7 +422,7 @@ protocol ContextFetchableRecord { extension ContextFetchableRecord { static func fetchCursor( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, context: Context) @@ -454,7 +454,7 @@ protocol FailableFetchableRecord { extension FailableFetchableRecord { static func fetchCursor( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor diff --git a/Documentation/SharingADatabase.md b/Documentation/SharingADatabase.md index ad51fe7ab..429ead152 100644 --- a/Documentation/SharingADatabase.md +++ b/Documentation/SharingADatabase.md @@ -173,7 +173,7 @@ do { > The exception code 0xDEAD10CC indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension. -See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for more information about this exception. +See https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report for more information about this exception. 1. If you use SQLCipher, use SQLCipher 4+, and call the [`cipher_plaintext_header_size` pragma](https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_plaintext_header_size) from your database preparation function: diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index b49b9e694..abc173109 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '5.8.0' + s.version = '5.9.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 3fbb46a02..4f2018a56 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -99,9 +99,9 @@ 56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; }; 56176C7D1EACCD2D000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; 56176C7F1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; - 561CFA7823735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */; }; - 561CFA7923735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */; }; - 561CFA7A23735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */; }; + 561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; }; + 561CFA7923735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; }; + 561CFA7A23735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; }; 561CFA982376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; 561CFA992376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; 561CFA9A2376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; @@ -129,6 +129,10 @@ 5623936D1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */; }; 562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; }; 562393761DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; }; + 56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; }; + 56256ED125D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; }; + 56256ED225D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; }; + 56256ED325D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; }; 56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; }; 56256EDA25D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; }; 56256EDB25D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; }; @@ -179,6 +183,9 @@ 563B071621862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */; }; 563B071821862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; 563B071921862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; + 563B5336267E2F90009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5335267E2F90009549B5 /* TableTests.swift */; }; + 563B5337267E2F90009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5335267E2F90009549B5 /* TableTests.swift */; }; + 563B5338267E2F90009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5335267E2F90009549B5 /* TableTests.swift */; }; 563B8F92249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; }; 563B8F93249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; }; 563B8F94249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; }; @@ -471,6 +478,10 @@ 566BE7212342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; }; 56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; + 56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; }; + 56713FDE2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; }; + 56713FDF2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; }; + 56713FE02691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; }; 567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; }; 56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */; }; 56717272261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */; }; @@ -773,7 +784,7 @@ 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 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; - 56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + 56D4966B1D81309E008276D7 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.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 */; }; @@ -901,7 +912,7 @@ 56FEB8FA248403020081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.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 */; }; + 56FF45441D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.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 */; }; @@ -1019,7 +1030,7 @@ AAA4DD0D230F262000C74B15 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; AAA4DD0E230F262000C74B15 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; AAA4DD0F230F262000C74B15 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; - AAA4DD10230F262000C74B15 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + AAA4DD10230F262000C74B15 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; }; AAA4DD11230F262000C74B15 /* RecordPrimaryKeyNoneTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238291B9C74A90082EB20 /* RecordPrimaryKeyNoneTests.swift */; }; AAA4DD12230F262000C74B15 /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; AAA4DD13230F262000C74B15 /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; }; @@ -1279,7 +1290,7 @@ 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 = ""; }; 56172947223533F40006E219 /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = ""; }; - 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = ""; }; + 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = ""; }; 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; }; 561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; @@ -1290,6 +1301,7 @@ 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FlattenCursorTests.swift; sourceTree = ""; }; 562393711DEE104400A6B01F /* MapCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapCursorTests.swift; sourceTree = ""; }; 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = ""; }; + 56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = ""; }; 56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = ""; }; 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; @@ -1318,6 +1330,7 @@ 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = ""; }; 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; + 563B5335267E2F90009549B5 /* TableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableTests.swift; sourceTree = ""; }; 563B8F91249E6171007A48C9 /* Trace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = ""; }; 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = ""; }; 563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabasePublishers.swift; sourceTree = ""; }; @@ -1422,6 +1435,7 @@ 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = ""; }; 566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = ""; }; 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; + 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONRequiredEncoder.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = ""; }; 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CaseInsensitiveIdentifier.swift; sourceTree = ""; }; @@ -1605,7 +1619,7 @@ 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.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 = ""; }; + 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.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 = ""; }; AAA4DCFE230F1E0600C74B15 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -1725,6 +1739,7 @@ 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */, 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */, 5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */, + 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */, 5605F1581C672E4000235C62 /* StandardLibrary.swift */, ); path = StandardLibrary; @@ -1759,11 +1774,9 @@ 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */, 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */, 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */, - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, - 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */, 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, ); name = PersistableRecord; @@ -1803,7 +1816,9 @@ 56176C9C1EACEA8C000F3F2B /* TableRecord */ = { isa = PBXGroup; children = ( + 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */, 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */, + 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */, ); name = TableRecord; sourceTree = ""; @@ -1873,6 +1888,7 @@ 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, + 563B5335267E2F90009549B5 /* TableTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, 5653EABF20944B1300F46237 /* Association */, ); @@ -2060,6 +2076,7 @@ 56D91AA12205E03700770D8D /* SQLRelation.swift */, 568ECA8925D7013000B71526 /* SQLSelection.swift */, 568ECB1725D9161500B71526 /* SQLSubquery.swift */, + 56256ECF25D1ACD0008C2BDD /* Table.swift */, ); path = SQL; sourceTree = ""; @@ -2867,6 +2884,7 @@ buildActionMask = 2147483647; files = ( 5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */, + 56256ED225D1ACD0008C2BDD /* Table.swift in Sources */, 56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, @@ -2962,6 +2980,7 @@ 56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */, 56F5ABD91D814330001F60CB /* Data.swift in Sources */, 565490D41D5AE252005622CB /* (null) in Sources */, + 56713FDF2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */, 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 565490B61D5AE236005622CB /* Configuration.swift in Sources */, 565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */, @@ -3019,6 +3038,7 @@ buildActionMask = 2147483647; files = ( 568ECAA025D7E53E00B71526 /* SQLOrdering.swift in Sources */, + 56713FDE2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */, 5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */, 563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */, 56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, @@ -3030,6 +3050,7 @@ 566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, 56012BA8257404E000B4925B /* CommonTableExpression.swift in Sources */, + 56256ED125D1ACD0008C2BDD /* Table.swift in Sources */, 5653EB0A20944C7C00F46237 /* Association.swift in Sources */, 56A2387E1B9C75030082EB20 /* Database.swift in Sources */, 56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, @@ -3155,7 +3176,7 @@ 56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */, 56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */, 56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, - 56FF45441D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56FF45441D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */, 56A238561B9C74A90082EB20 /* RecordPrimaryKeyNoneTests.swift in Sources */, 562EA8331F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, 563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -3302,7 +3323,7 @@ 56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, 5698ACD21DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, - 561CFA7923735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, + 561CFA7923735016000C8BAA /* TableRecordUpdateTests.swift in Sources */, 56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */, 5653EAE120944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 5604484A25DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, @@ -3315,6 +3336,7 @@ 56677C0E241CD0D00050755D /* ValueObservationRecorder.swift in Sources */, 5698ACA21DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, 56A2385C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, + 563B5337267E2F90009549B5 /* TableTests.swift in Sources */, 56A238401B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */, @@ -3413,7 +3435,7 @@ 56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */, 56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */, - 56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56D4966B1D81309E008276D7 /* TableRecordDeleteTests.swift in Sources */, 563B06F721861D8400B38F35 /* ValueObservationCountTests.swift in Sources */, 56DF001B228DDBA300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */, 56D4965B1D81304E008276D7 /* FoundationNSDecimalNumberTests.swift in Sources */, @@ -3533,7 +3555,7 @@ 5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, - 561CFA7823735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, + 561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */, 56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, 56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */, @@ -3545,6 +3567,7 @@ 562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */, 56677C0D241CD0D00050755D /* ValueObservationRecorder.swift in Sources */, 5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */, + 563B5336267E2F90009549B5 /* TableTests.swift in Sources */, 56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */, 56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */, 56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */, @@ -3610,6 +3633,7 @@ buildActionMask = 2147483647; files = ( 568ECAA225D7E53E00B71526 /* SQLOrdering.swift in Sources */, + 56713FE02691F409006153C3 /* JSONRequiredEncoder.swift in Sources */, AAA4DC77230F1E0600C74B15 /* FetchRequest.swift in Sources */, AAA4DC78230F1E0600C74B15 /* AssociationAggregate.swift in Sources */, AAA4DC79230F1E0600C74B15 /* SchedulingWatchdog.swift in Sources */, @@ -3621,6 +3645,7 @@ AAA4DC7F230F1E0600C74B15 /* SQLOperators.swift in Sources */, AAA4DC80230F1E0600C74B15 /* FTS5CustomTokenizer.swift in Sources */, 56012BB2257404E200B4925B /* CommonTableExpression.swift in Sources */, + 56256ED325D1ACD0008C2BDD /* Table.swift in Sources */, AAA4DC81230F1E0600C74B15 /* Association.swift in Sources */, AAA4DC82230F1E0600C74B15 /* Database.swift in Sources */, AAA4DC83230F1E0600C74B15 /* FTS3.swift in Sources */, @@ -3746,7 +3771,7 @@ AAA4DD0D230F262000C74B15 /* Record+QueryInterfaceRequestTests.swift in Sources */, AAA4DD0E230F262000C74B15 /* RowAdapterTests.swift in Sources */, AAA4DD0F230F262000C74B15 /* DatabaseCursorTests.swift in Sources */, - AAA4DD10230F262000C74B15 /* MutablePersistableRecordDeleteTests.swift in Sources */, + AAA4DD10230F262000C74B15 /* TableRecordDeleteTests.swift in Sources */, AAA4DD11230F262000C74B15 /* RecordPrimaryKeyNoneTests.swift in Sources */, AAA4DD12230F262000C74B15 /* CompilationSubClassTests.swift in Sources */, AAA4DD13230F262000C74B15 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -3893,7 +3918,7 @@ AAA4DD8B230F262000C74B15 /* ForeignKeyInfoTests.swift in Sources */, AAA4DD8C230F262000C74B15 /* AssociationChainSQLTests.swift in Sources */, AAA4DD8D230F262000C74B15 /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, - 561CFA7A23735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, + 561CFA7A23735016000C8BAA /* TableRecordUpdateTests.swift in Sources */, AAA4DD8E230F262000C74B15 /* RecordEditedTests.swift in Sources */, AAA4DD8F230F262000C74B15 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 5604484B25DEEEF8002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, @@ -3906,6 +3931,7 @@ 56677C0F241CD0D00050755D /* ValueObservationRecorder.swift in Sources */, AAA4DD94230F262000C74B15 /* FTS4TableBuilderTests.swift in Sources */, AAA4DD95230F262000C74B15 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, + 563B5338267E2F90009549B5 /* TableTests.swift in Sources */, AAA4DD96230F262000C74B15 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, AAA4DD97230F262000C74B15 /* DatabaseAggregateTests.swift in Sources */, AAA4DD98230F262000C74B15 /* FoundationUUIDTests.swift in Sources */, @@ -3971,6 +3997,7 @@ buildActionMask = 2147483647; files = ( 568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */, + 56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */, 563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */, 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */, @@ -3982,6 +4009,7 @@ 566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */, 56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */, + 56256ED025D1ACD0008C2BDD /* Table.swift in Sources */, 563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */, 56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */, 5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */, diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index f0ae2fd82..d40748439 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -9,12 +9,12 @@ public struct Configuration { /// If true, foreign key constraints are checked. /// /// Default: true - public var foreignKeysEnabled: Bool = true + public var foreignKeysEnabled = true /// If true, database modifications are disallowed. /// /// Default: false - public var readonly: Bool = false + public var readonly = false /// The configuration label. /// @@ -91,7 +91,7 @@ public struct Configuration { /// When true, the `Database.suspendNotification` and /// `Database.resumeNotification` suspend and resume the database. Database /// suspension helps avoiding the [`0xdead10cc` - /// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html). + /// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report). /// /// During suspension, all database accesses but reads in WAL mode may throw /// a DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. You can @@ -175,11 +175,11 @@ public struct Configuration { /// never allow leaving a transaction opened at the end of a read access. /// /// Default: false - public var allowsUnsafeTransactions: Bool = false + public var allowsUnsafeTransactions = false // MARK: - Concurrency - /// The behavior in case of SQLITE_BUSY error. See https://www.sqlite.org/rescode.html#busy + /// The behavior in case of SQLITE_BUSY error. See /// /// Default: immediateError public var busyMode: Database.BusyMode = .immediateError diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index e923864e4..97dbaa94a 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -1,5 +1,5 @@ extension Database { - /// A SQLite schema. See https://sqlite.org/lang_naming.html + /// A SQLite schema. See enum SchemaIdentifier: Hashable { /// The main database case main @@ -7,7 +7,7 @@ extension Database { /// The temp database case temp - /// An attached database: https://sqlite.org/lang_attach.html + /// An attached database: case attached(String) /// The name of the schema in SQL queries @@ -57,8 +57,8 @@ extension Database { SchedulingWatchdog.preconditionValidQueue(self) schemaCache.clear() - // We also clear updateStatementCache and selectStatementCache despite - // the automatic statement recompilation (see https://www.sqlite.org/c3ref/prepare.html) + // We also clear statement cache despite the automatic statement + // recompilation (see https://www.sqlite.org/c3ref/prepare.html) // because the automatic statement recompilation only happens a // limited number of times. internalStatementCache.clear() @@ -68,7 +68,7 @@ extension Database { /// Clears the database schema cache if the database schema has changed /// since this method was last called. func clearSchemaCacheIfNeeded() throws { - let schemaVersion = try Int32.fetchOne(internalCachedSelectStatement(sql: "PRAGMA schema_version")) + let schemaVersion = try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version")) if _lastSchemaVersion != schemaVersion { _lastSchemaVersion = schemaVersion clearSchemaCache() @@ -116,7 +116,7 @@ extension Database { /// /// Those are tables whose name begins with `sqlite_` and `pragma_`. /// - /// For more information, see https://www.sqlite.org/fileformat2.html + /// For more information, see public static func isSQLiteInternalTable(_ tableName: String) -> Bool { // https://www.sqlite.org/fileformat2.html#internal_schema_objects // > The names of internal schema objects always begin with "sqlite_" @@ -131,7 +131,7 @@ extension Database { /// /// Those are tables whose name begins with `sqlite_` and `pragma_`. /// - /// For more information, see https://www.sqlite.org/fileformat2.html + /// For more information, see @available(*, deprecated, message: "Use Database.isSQLiteInternalTable(_:) static method instead.") public func isSQLiteInternalTable(_ tableName: String) -> Bool { Self.isSQLiteInternalTable(tableName) @@ -295,7 +295,7 @@ extension Database { // // TODO: find a way to know if a table is WITHOUT ROWID without // generating an error. - _ = try makeSelectStatement(sql: """ + _ = try makeStatement(sql: """ SELECT rowid AS checkWithoutRowidOptimization FROM \(table.quotedDatabaseIdentifier) """) return true @@ -641,7 +641,7 @@ extension Database { /// 1 firstName TEXT 0 0 0 /// 2 lastName TEXT 0 0 0 /// -/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info +/// See `Database.columns(in:)` and public struct ColumnInfo: FetchableRecord { let cid: Int let hidden: Int? @@ -689,8 +689,8 @@ public struct ColumnInfo: FetchableRecord { /// the primary key for columns that are part of the primary key. /// /// References: - /// - https://sqlite.org/releaselog/3_7_16.html - /// - http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html + /// - + /// - public let primaryKeyIndex: Int /// :nodoc: diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 67bdce52d..66d20dae9 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -4,6 +4,62 @@ extension Database { // MARK: - Statements + /// Returns a new prepared statement that can be reused. + /// + /// let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?") + /// let player1 = try Player.fetchOne(statement, arguments: [1])! + /// let player2 = try Player.fetchOne(statement, arguments: [2])! + /// + /// let statement = try db.makeStatement(sql: "INSERT INTO player (name) VALUES (?)") + /// try statement.execute(arguments: ["Arthur"]) + /// try statement.execute(arguments: ["Barbara"]) + /// + /// - parameter sql: An SQL query. + /// - returns: A Statement. + /// - throws: A DatabaseError whenever SQLite could not parse the sql query. + public func makeStatement(sql: String) throws -> Statement { + try makeStatement(sql: sql, prepFlags: 0) + } + + /// Returns a new prepared statement that can be reused. + /// + /// let statement = try db.makeStatement(literal: "SELECT * FROM player WHERE id = ?") + /// let player1 = try Player.fetchOne(statement, arguments: [1])! + /// let player2 = try Player.fetchOne(statement, arguments: [2])! + /// + /// let statement = try db.makeStatement(literal: "INSERT INTO player (name) VALUES (?)") + /// try statement.execute(arguments: ["Arthur"]) + /// try statement.execute(arguments: ["Barbara"]) + /// + /// - parameter sqlLiteral: An `SQL` literal. + /// - returns: A Statement. + /// - throws: A DatabaseError whenever SQLite could not parse the sql query. + /// - precondition: No argument must be set, or all arguments must be set. + /// An error is raised otherwise. + /// + /// // OK + /// try makeStatement(literal: """ + /// SELECT COUNT(*) FROM player WHERE score > ? + /// """) + /// try makeStatement(literal: """ + /// SELECT COUNT(*) FROM player WHERE score > \(1000) + /// """) + /// + /// // NOT OK + /// try makeStatement(literal: """ + /// SELECT COUNT(*) FROM player + /// WHERE color = ? AND score > \(1000) + /// """) + public func makeStatement(literal sqlLiteral: SQL) throws -> Statement { + let (sql, arguments) = try sqlLiteral.build(self) + let statement = try makeStatement(sql: sql) + if arguments.isEmpty == false { + // Throws if arguments do not match + try statement.setArguments(arguments) + } + return statement + } + /// Returns a new prepared statement that can be reused. /// /// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player WHERE id = ?") @@ -11,19 +67,20 @@ extension Database { /// let player2 = try Player.fetchOne(statement, arguments: [2])! /// /// - parameter sql: An SQL query. - /// - returns: A SelectStatement. + /// - returns: A Statement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. - public func makeSelectStatement(sql: String) throws -> SelectStatement { - try makeSelectStatement(sql: sql, prepFlags: 0) + @available(*, deprecated, renamed: "makeStatement(sql:)") + public func makeSelectStatement(sql: String) throws -> Statement { + try makeStatement(sql: sql) } /// Returns a new prepared statement that can be reused. /// /// - parameter sqlLiteral: An `SQL` literal. - /// - returns: An SelectStatement. + /// - returns: A Statement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. /// - precondition: No argument must be set, or all arguments must be set. - /// A fatal error is raised otherwise. + /// An error is raised otherwise. /// /// // OK /// try makeSelectStatement(literal: """ @@ -38,29 +95,111 @@ extension Database { /// SELECT COUNT(*) FROM player /// WHERE color = ? AND score > \(1000) /// """) - public func makeSelectStatement(literal sqlLiteral: SQL) throws -> SelectStatement { - let (sql, arguments) = try sqlLiteral.build(self) - let statement = try makeSelectStatement(sql: sql) - if arguments.isEmpty == false { - // Crash if arguments do not match - statement.arguments = arguments - } - return statement + @available(*, deprecated, renamed: "makeStatement(literal:)") + public func makeSelectStatement(literal sqlLiteral: SQL) throws -> Statement { + try makeStatement(literal: sqlLiteral) } /// Returns a new prepared statement that can be reused. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0) + /// let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0) /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! /// /// - parameter sql: An SQL query. /// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from - /// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html) - /// - returns: A SelectStatement. + /// SQLite 3.20.0, see ) + /// - returns: A Statement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. - func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement { - try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags) + func makeStatement(sql: String, prepFlags: Int32) throws -> Statement { + let statements = SQLStatementCursor(database: self, sql: sql, arguments: nil, prepFlags: prepFlags) + guard let statement = try statements.next() else { + throw DatabaseError( + resultCode: .SQLITE_ERROR, + message: "empty statement", + sql: sql) + } + do { + guard try statements.next() == nil else { + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: """ + Multiple statements found. To execute multiple statements, use \ + Database.execute(sql:) or Database.allStatements(sql:) instead. + """, + sql: sql) + } + } catch { + // Something while would not compile was found after the first statement. + // Complain about multiple statements anyway. + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: """ + Multiple statements found. To execute multiple statements, use \ + Database.execute(sql:) or Database.allStatements(sql:) instead. + """, + sql: sql) + } + return statement + } + + /// Returns a prepared statement that can be reused. + /// + /// let statement = try db.cachedStatement(sql: "SELECT * FROM player WHERE id = ?") + /// let player1 = try Player.fetchOne(statement, arguments: [1])! + /// let player2 = try Player.fetchOne(statement, arguments: [2])! + /// + /// let statement = try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)") + /// try statement.execute(arguments: ["Arthur"]) + /// try statement.execute(arguments: ["Barbara"]) + /// + /// The returned statement may have already been used: it may or may not + /// contain values for its eventual arguments. + /// + /// - parameter sql: An SQL query. + /// - returns: A Statement. + /// - throws: A DatabaseError whenever SQLite could not parse the sql query. + public func cachedStatement(sql: String) throws -> Statement { + try publicStatementCache.statement(sql) + } + + /// Returns a prepared statement that can be reused. + /// + /// let statement = try db.cachedStatement(literal: "SELECT * FROM player WHERE id = ?") + /// let player1 = try Player.fetchOne(statement, arguments: [1])! + /// let player2 = try Player.fetchOne(statement, arguments: [2])! + /// + /// let statement = try db.cachedStatement(literal: "INSERT INTO player (name) VALUES (?)") + /// try statement.execute(arguments: ["Arthur"]) + /// try statement.execute(arguments: ["Barbara"]) + /// + /// - parameter sqlLiteral: An `SQL` literal. + /// - returns: A Statement. + /// - throws: A DatabaseError whenever SQLite could not parse the sql query. + /// - precondition: No argument must be set, or all arguments must be set. + /// An error is raised otherwise. + /// + /// // OK + /// try cachedStatement(literal: """ + /// SELECT COUNT(*) FROM player WHERE score > ? + /// """) + /// try cachedStatement(literal: """ + /// SELECT COUNT(*) FROM player WHERE score > \(1000) + /// """) + /// + /// // NOT OK + /// try cachedStatement(literal: """ + /// SELECT COUNT(*) FROM player + /// WHERE color = ? AND score > \(1000) + /// """) + public func cachedStatement(literal sqlLiteral: SQL) throws -> Statement { + let (sql, arguments) = try sqlLiteral.build(self) + let statement = try cachedStatement(sql: sql) + if arguments.isEmpty == false { + // Throws if arguments do not match + try statement.setArguments(arguments) + } + return statement } /// Returns a prepared statement that can be reused. @@ -73,15 +212,45 @@ extension Database { /// contain values for its eventual arguments. /// /// - parameter sql: An SQL query. - /// - returns: An UpdateStatement. + /// - returns: A Statement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. - public func cachedSelectStatement(sql: String) throws -> SelectStatement { - try publicStatementCache.selectStatement(sql) + @available(*, deprecated, renamed: "cachedStatement(sql:)") + public func cachedSelectStatement(sql: String) throws -> Statement { + try cachedStatement(sql: sql) + } + + /// Returns a prepared statement that can be reused. + /// + /// let statement = try db.cachedSelectStatement(literal: "SELECT COUNT(*) FROM player WHERE score > \(20)") + /// let moreThanTwentyCount = try Int.fetchOne(statement)! + /// + /// - parameter sqlLiteral: An `SQL` literal. + /// - returns: A Statement. + /// - throws: A DatabaseError whenever SQLite could not parse the sql query. + /// - precondition: No argument must be set, or all arguments must be set. + /// An error is raised otherwise. + /// + /// // OK + /// try cachedSelectStatement(literal: """ + /// SELECT COUNT(*) FROM player WHERE score > ? + /// """) + /// try cachedSelectStatement(literal: """ + /// SELECT COUNT(*) FROM player WHERE score > \(1000) + /// """) + /// + /// // NOT OK + /// try cachedSelectStatement(literal: """ + /// SELECT COUNT(*) FROM player + /// WHERE color = ? AND score > \(1000) + /// """) + @available(*, deprecated, renamed: "cachedStatement(literal:)") + public func cachedSelectStatement(literal sqlLiteral: SQL) throws -> Statement { + try cachedStatement(literal: sqlLiteral) } /// Returns a cached statement that does not conflict with user's cached statements. - func internalCachedSelectStatement(sql: String) throws -> SelectStatement { - try internalStatementCache.selectStatement(sql) + func internalCachedStatement(sql: String) throws -> Statement { + try internalStatementCache.statement(sql) } /// Returns a new prepared statement that can be reused. @@ -93,17 +262,18 @@ extension Database { /// - parameter sql: An SQL query. /// - returns: An UpdateStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. - public func makeUpdateStatement(sql: String) throws -> UpdateStatement { - try makeUpdateStatement(sql: sql, prepFlags: 0) + @available(*, deprecated, renamed: "makeStatement(sql:)") + public func makeUpdateStatement(sql: String) throws -> Statement { + try makeStatement(sql: sql) } /// Returns a new prepared statement that can be reused. /// /// - parameter sqlLiteral: An `SQL` literal. - /// - returns: An UpdateStatement. + /// - returns: A Statement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. /// - precondition: No argument must be set, or all arguments must be set. - /// A fatal error is raised otherwise. + /// An error is raised otherwise. /// /// // OK /// try makeUpdateStatement(literal: """ @@ -117,29 +287,9 @@ extension Database { /// try makeUpdateStatement(literal: """ /// UPDATE player SET name = ?, score = \(10) /// """) - public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> UpdateStatement { - let (sql, arguments) = try sqlLiteral.build(self) - let statement = try makeUpdateStatement(sql: sql) - if arguments.isEmpty == false { - // Crash if arguments do not match - statement.arguments = arguments - } - return statement - } - - /// Returns a new prepared statement that can be reused. - /// - /// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)", prepFlags: 0) - /// try statement.execute(arguments: ["Arthur"]) - /// try statement.execute(arguments: ["Barbara"]) - /// - /// - parameter sql: An SQL query. - /// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from - /// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html) - /// - returns: An UpdateStatement. - /// - throws: A DatabaseError whenever SQLite could not parse the sql query. - func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement { - try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags) + @available(*, deprecated, renamed: "makeStatement(literal:)") + public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> Statement { + try makeStatement(literal: sqlLiteral) } /// Returns a prepared statement that can be reused. @@ -152,15 +302,120 @@ extension Database { /// contain values for its eventual arguments. /// /// - parameter sql: An SQL query. - /// - returns: An UpdateStatement. + /// - returns: A Statement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. - public func cachedUpdateStatement(sql: String) throws -> UpdateStatement { - try publicStatementCache.updateStatement(sql) + @available(*, deprecated, renamed: "cachedStatement(sql:)") + public func cachedUpdateStatement(sql: String) throws -> Statement { + try cachedStatement(sql: sql) } - /// Returns a cached statement that does not conflict with user's cached statements. - func internalCachedUpdateStatement(sql: String) throws -> UpdateStatement { - try internalStatementCache.updateStatement(sql) + /// Returns a new prepared statement that can be reused. + /// + /// - parameter sqlLiteral: An `SQL` literal. + /// - returns: A Statement. + /// - throws: A DatabaseError whenever SQLite could not parse the sql query. + /// - precondition: No argument must be set, or all arguments must be set. + /// An error is raised otherwise. + /// + /// // OK + /// try cachedUpdateStatement(literal: """ + /// UPDATE player SET name = ? + /// """) + /// try cachedUpdateStatement(literal: """ + /// UPDATE player SET name = \("O'Brien") + /// """) + /// + /// // NOT OK + /// try cachedUpdateStatement(literal: """ + /// UPDATE player SET name = ?, score = \(10) + /// """) + @available(*, deprecated, renamed: "cachedStatement(sql:)") + public func cachedUpdateStatement(literal sqlLiteral: SQL) throws -> Statement { + try cachedStatement(literal: sqlLiteral) + } + + /// Returns a cursor of all SQL statements separated by semi-colons. + /// + /// let statements = try db.allStatements(sql: """ + /// INSERT INTO player (name) VALUES (?); + /// INSERT INTO player (name) VALUES (?); + /// INSERT INTO player (name) VALUES (?); + /// """, arguments: ["Arthur", "Barbara", "O'Brien"]) + /// while let statement = try statements.next() { + /// try statement.execute() + /// } + /// + /// - parameters: + /// - sql: An SQL query. + /// - arguments: Statement arguments. + /// - returns: A cursor of `Statement` + /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - precondition: Arguments must be nil, or all arguments must be set. + /// The returned cursor will throw an error otherwise. + /// + /// // OK + /// try allStatements(sql: """ + /// SELECT COUNT(*) FROM player WHERE score < ?; + /// SELECT COUNT(*) FROM player WHERE score > ?; + /// """) + /// try allStatements(sql: """ + /// SELECT COUNT(*) FROM player WHERE score < ?; + /// SELECT COUNT(*) FROM player WHERE score > ?; + /// """, arguments: [1000, 1000]) + /// + /// // NOT OK + /// try allStatements(sql: """ + /// SELECT COUNT(*) FROM player WHERE score < ?; + /// SELECT COUNT(*) FROM player WHERE score > ?; + /// """, arguments: [1000]) + public func allStatements(sql: String, arguments: StatementArguments? = nil) + throws -> SQLStatementCursor + { + SQLStatementCursor(database: self, sql: sql, arguments: arguments) + } + + /// Returns a cursor of all SQL statements separated by semi-colons. + /// + /// Literals allow you to safely embed raw values in your SQL, without any + /// risk of syntax errors or SQL injection: + /// + /// let statements = try db.allStatements(literal: """ + /// INSERT INTO player (name) VALUES (\("Arthur")); + /// INSERT INTO player (name) VALUES (\("Barbara")); + /// INSERT INTO player (name) VALUES (\("O'Brien")); + /// """) + /// while let statement = try statements.next() { + /// try statement.execute() + /// } + /// + /// - parameter sqlLiteral: An `SQL` literal. + /// - returns: A cursor of `Statement` + /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - precondition: No argument must be set, or all arguments must be set. + /// The returned cursor will throw an error otherwise. + /// + /// // OK + /// try allStatements(literal: """ + /// SELECT COUNT(*) FROM player WHERE score < ?; + /// SELECT COUNT(*) FROM player WHERE score > ?; + /// """) + /// try allStatements(literal: """ + /// SELECT COUNT(*) FROM player WHERE score < \(1000); + /// SELECT COUNT(*) FROM player WHERE score > \(1000); + /// """) + /// + /// // NOT OK + /// try allStatements(literal: """ + /// SELECT COUNT(*) FROM player WHERE score < \(1000); + /// SELECT COUNT(*) FROM player WHERE score > ?; + /// """) + public func allStatements(literal sqlLiteral: SQL) throws -> SQLStatementCursor { + let context = SQLGenerationContext(self) + let sql = try sqlLiteral.sql(context) + let arguments = context.arguments.isEmpty + ? nil // builds statements without arguments + : context.arguments // force arguments to match + return SQLStatementCursor(database: self, sql: sql, arguments: arguments) } /// Executes one or several SQL statements, separated by semi-colons. @@ -205,83 +460,105 @@ extension Database { /// - parameter sqlLiteral: An `SQL` literal. /// - throws: A DatabaseError whenever an SQLite error occurs. public func execute(literal sqlLiteral: SQL) throws { - // This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html) - // It adds support for arguments, and the tricky part is to consume - // arguments as statements are executed. - // - // This job is performed by StatementArguments.extractBindings(forStatement:allowingRemainingValues:) - // - // And before we return, we'll check that all arguments were consumed. - - let context = SQLGenerationContext(self) - let sql = try sqlLiteral.sql(context) - var arguments = context.arguments - let initialValuesCount = arguments.values.count - - // Build a C string (SQLite wants that), and execute SQL statements one - // after the other. - try sql.utf8CString.withUnsafeBufferPointer { buffer in - guard let sqlStart = buffer.baseAddress else { return } - let sqlEnd = sqlStart + buffer.count // past \0 - var statementStart = sqlStart - while statementStart < sqlEnd { - var statementEnd: UnsafePointer? = nil - let nextStatement: UpdateStatement? - - // Compile - do { - let authorizer = StatementCompilationAuthorizer() - nextStatement = try withAuthorizer(authorizer) { - try UpdateStatement( - database: self, - statementStart: statementStart, - statementEnd: &statementEnd, - prepFlags: 0, - authorizer: authorizer) - } - } - - guard let statement = nextStatement else { - // End of SQL string - break - } - - // Extract statement arguments - let bindings = try arguments.extractBindings(forStatement: statement, allowingRemainingValues: true) - // unsafe is OK because we just extracted the correct number of arguments - statement.setUncheckedArguments(StatementArguments(bindings)) - - // Execute - try statement.execute() - - // Next - statementStart = statementEnd! - } + let statements = try allStatements(literal: sqlLiteral) + while let statement = try statements.next() { + try statement.execute() + } + } +} + +public class SQLStatementCursor: Cursor { + private let database: Database + /// C string + private let buffer: UnsafeBufferPointer + private let prepFlags: CInt + private let initialArgumentCount: Int? + private let sqlEnd: UnsafePointer? + private var statementStart: UnsafePointer? + /// Nil when arguments are set later + private var arguments: StatementArguments? + + init(database: Database, sql: String, arguments: StatementArguments?, prepFlags: CInt = 0) { + self.database = database + self.arguments = arguments + self.prepFlags = prepFlags + self.initialArgumentCount = arguments?.values.count + self.buffer = sql.utf8CString.withUnsafeBufferPointer { buffer in + let rawBuffer = UnsafeRawBufferPointer(buffer) + let copy = UnsafeMutableRawBufferPointer.allocate( + byteCount: rawBuffer.count, + alignment: MemoryLayout.alignment) + copy.copyMemory(from: rawBuffer) + return UnsafeBufferPointer(copy.bindMemory(to: CChar.self)) + } + if let sqlStart = buffer.baseAddress { + statementStart = sqlStart + sqlEnd = sqlStart + buffer.count // past \0 + } else { + statementStart = nil + sqlEnd = nil + } + } + + deinit { + buffer.deallocate() + } + + public func next() throws -> Statement? { + guard let statementStart = statementStart, + let sqlEnd = sqlEnd, + statementStart < sqlEnd + else { + try checkArgumentsAreEmpty() + return nil } - // Check that all arguments were consumed: it is a programmer error to - // provide arguments that do not match the statement. - if arguments.values.isEmpty == false { + var statementEnd: UnsafePointer? = nil + let authorizer = StatementCompilationAuthorizer() + let statement = try database.withAuthorizer(authorizer) { + try Statement( + database: database, + statementStart: statementStart, + statementEnd: &statementEnd, + prepFlags: prepFlags, + authorizer: authorizer) + } + + self.statementStart = statementEnd! + + if let statement = statement { + if arguments != nil { + // Extract statement arguments + let bindings = try arguments!.extractBindings(forStatement: statement, allowingRemainingValues: true) + // unsafe is OK because we just extracted the correct number of arguments + statement.setUncheckedArguments(StatementArguments(bindings)) + } + return statement + } else { + try checkArgumentsAreEmpty() + return nil + } + } + + /// Check that all arguments were consumed: it is a programmer error to + /// provide arguments that do not match the statements. + private func checkArgumentsAreEmpty() throws { + if let arguments = arguments, + let initialArgumentCount = initialArgumentCount, + arguments.values.isEmpty == false + { throw DatabaseError( resultCode: .SQLITE_MISUSE, - message: "wrong number of statement arguments: \(initialValuesCount)") + message: "wrong number of statement arguments: \(initialArgumentCount)") } } } extension Database { - func executeUpdateStatement(_ statement: UpdateStatement) throws { - // Two things must prevent the statement from executing: aborted - // transactions, and database suspension. - try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments) - try checkForSuspensionViolation(from: statement) - - if _isRecordingSelectedRegion { - _selectedRegion.formUnion(statement.databaseRegion) - } - - let authorizer = observationBroker.updateStatementWillExecute(statement) + func executeStatement(_ statement: Statement) throws { + let authorizer = try statementWillExecute(statement) let sqliteStatement = statement.sqliteStatement + var code: Int32 = SQLITE_OK withAuthorizer(authorizer) { while true { @@ -314,40 +591,18 @@ extension Database { // We can now move on further tasks. if code == SQLITE_DONE { - try updateStatementDidExecute(statement) + try statementDidExecute(statement) } else { assert(code != SQLITE_ROW) - try updateStatementDidFail(statement) - throw DatabaseError( - resultCode: code, - message: lastErrorMessage, - sql: statement.sql, - arguments: statement.arguments) + try statementDidFail(statement, withResultCode: code) } } - private func updateStatementDidExecute(_ statement: UpdateStatement) throws { - if statement.invalidatesDatabaseSchemaCache { - clearSchemaCache() - } - - try observationBroker.updateStatementDidExecute(statement) - } - - private func updateStatementDidFail(_ statement: UpdateStatement) throws { - // Failed statements can not be reused, because sqlite3_reset won't - // be able to restore the statement to its initial state: - // https://www.sqlite.org/c3ref/reset.html - // - // So make sure we clear this statement from the cache. - internalStatementCache.remove(statement) - publicStatementCache.remove(statement) - - try observationBroker.updateStatementDidFail(statement) - } - - @inline(__always) - func selectStatementWillExecute(_ statement: SelectStatement) throws { + /// Returns the authorizer that should be used during statement execution + /// (this allows preventing the truncate optimization when there exists a + /// transaction observer for row deletion). + @usableFromInline + func statementWillExecute(_ statement: Statement) throws -> StatementAuthorizer? { // Two things must prevent the statement from executing: aborted // transactions, and database suspension. try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments) @@ -356,9 +611,24 @@ extension Database { if _isRecordingSelectedRegion { _selectedRegion.formUnion(statement.databaseRegion) } + + return observationBroker.statementWillExecute(statement) } - func selectStatementDidFail(_ statement: SelectStatement) { + /// May throw a cancelled commit error, if a transaction observer cancels + /// an empty transaction. + @usableFromInline + func statementDidExecute(_ statement: Statement) throws { + if statement.invalidatesDatabaseSchemaCache { + clearSchemaCache() + } + + try observationBroker.statementDidExecute(statement) + } + + /// Always throws an error + @usableFromInline + func statementDidFail(_ statement: Statement, withResultCode resultCode: Int32) throws -> Never { // Failed statements can not be reused, because sqlite3_reset won't // be able to restore the statement to its initial state: // https://www.sqlite.org/c3ref/reset.html @@ -366,21 +636,30 @@ extension Database { // So make sure we clear this statement from the cache. internalStatementCache.remove(statement) publicStatementCache.remove(statement) + + /// Exposes the user-provided cancelled commit error, if a transaction + /// observer has cancelled a transaction. + try observationBroker.statementDidFail(statement) + + throw DatabaseError( + resultCode: resultCode, + message: lastErrorMessage, + sql: statement.sql, + arguments: statement.arguments) } } /// A thread-unsafe statement cache struct StatementCache { unowned let db: Database - private var selectStatements: [String: SelectStatement] = [:] - private var updateStatements: [String: UpdateStatement] = [:] + private var statements: [String: Statement] = [:] init(database: Database) { self.db = database } - mutating func selectStatement(_ sql: String) throws -> SelectStatement { - if let statement = selectStatements[sql] { + mutating func statement(_ sql: String) throws -> Statement { + if let statement = statements[sql] { return statement } @@ -394,61 +673,26 @@ struct StatementCache { // However SQLITE_PREPARE_PERSISTENT was only introduced in // SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20 #if GRDBCUSTOMSQLITE || GRDBCIPHER - let statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT) + let statement = try db.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT) #else - let statement: SelectStatement + let statement: Statement if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) { // SQLite 3.24.0 or more - statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT) + statement = try db.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT) } else { // SQLite 3.19.3 or less - statement = try db.makeSelectStatement(sql: sql) + statement = try db.makeStatement(sql: sql) } #endif - selectStatements[sql] = statement - return statement - } - - mutating func updateStatement(_ sql: String) throws -> UpdateStatement { - if let statement = updateStatements[sql] { - return statement - } - - // http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent - // > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query - // > planner that the prepared statement will be retained for a long - // > time and probably reused many times. - // - // This looks like a perfect match for cached statements. - // - // However SQLITE_PREPARE_PERSISTENT was only introduced in - // SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20 - #if GRDBCUSTOMSQLITE || GRDBCIPHER - let statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT) - #else - let statement: UpdateStatement - if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) { - // SQLite 3.24.0 or more - statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT) - } else { - // SQLite 3.19.3 or less - statement = try db.makeUpdateStatement(sql: sql) - } - #endif - updateStatements[sql] = statement + statements[sql] = statement return statement } mutating func clear() { - updateStatements = [:] - selectStatements = [:] + statements = [:] } - mutating func remove(_ statement: SelectStatement) { - selectStatements.removeFirst { $0.value === statement } - } - - mutating func remove(_ statement: UpdateStatement) { - updateStatements.removeFirst { $0.value === statement } + mutating func remove(_ statement: Statement) { + statements.removeFirst { $0.value === statement } } } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 31323b0e7..9a607d73d 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -33,7 +33,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// The error logging function. /// - /// Quoting https://www.sqlite.org/errlog.html: + /// Quoting : /// /// > SQLite can be configured to invoke a callback function containing an /// > error code and a terse error message whenever anomalies occur. This @@ -72,7 +72,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// If no row has ever been inserted using this database connection, /// returns zero. /// - /// For more detailed information, see https://www.sqlite.org/c3ref/last_insert_rowid.html + /// For more detailed information, see public var lastInsertedRowID: Int64 { SchedulingWatchdog.preconditionValidQueue(self) return sqlite3_last_insert_rowid(sqliteConnection) @@ -81,7 +81,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// The number of rows modified, inserted or deleted by the most recent /// successful INSERT, UPDATE or DELETE statement. /// - /// For more detailed information, see https://www.sqlite.org/c3ref/changes.html + /// For more detailed information, see public var changesCount: Int { SchedulingWatchdog.preconditionValidQueue(self) return Int(sqlite3_changes(sqliteConnection)) @@ -91,7 +91,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// INSERT, UPDATE or DELETE statements since the database connection was /// opened. /// - /// For more detailed information, see https://www.sqlite.org/c3ref/total_changes.html + /// For more detailed information, see public var totalChangesCount: Int { SchedulingWatchdog.preconditionValidQueue(self) return Int(sqlite3_total_changes(sqliteConnection)) @@ -162,8 +162,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } /// If true, select statement execution is recorded. - /// Use recordingSelectedRegion(_:), see `selectStatementWillExecute(_:)` - var _isRecordingSelectedRegion: Bool = false + /// Use recordingSelectedRegion(_:), see `statementWillExecute(_:)` + var _isRecordingSelectedRegion = false var _selectedRegion = DatabaseRegion() /// Support for checkForAbortedTransaction() @@ -183,7 +183,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib private var functions = Set() private var collations = Set() private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly - private var isClosed: Bool = false + private var isClosed = false // MARK: - Initializer @@ -204,7 +204,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Database Opening private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection { - // See https://www.sqlite.org/c3ref/open.html + // See var sqliteConnection: SQLiteConnection? = nil let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil) guard code == SQLITE_OK else { @@ -365,7 +365,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // // So let's fail early if file is not a database, or encrypted with // another passphrase. - try makeSelectStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next() + try makeStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next() } // MARK: - Database Closing @@ -415,7 +415,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// try Player.deleteAll(db, keys: ids) /// } /// - /// See https://www.sqlite.org/limits.html + /// See /// and `SQLITE_LIMIT_VARIABLE_NUMBER`. public var maximumStatementArgumentCount: Int { Int(sqlite3_limit(sqliteConnection, SQLITE_LIMIT_VARIABLE_NUMBER, -1)) @@ -486,7 +486,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib func beginReadOnly() throws { if configuration.readonly { return } if _readOnlyDepth == 0 { - try internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute() + try internalCachedStatement(sql: "PRAGMA query_only = 1").execute() } _readOnlyDepth += 1 } @@ -495,7 +495,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib if configuration.readonly { return } _readOnlyDepth -= 1 if _readOnlyDepth == 0 { - try internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute() + try internalCachedStatement(sql: "PRAGMA query_only = 0").execute() } } @@ -512,7 +512,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib #if SQLITE_ENABLE_SNAPSHOT /// Returns a snapshot that must be freed with `sqlite3_snapshot_free`. /// - /// See https://www.sqlite.org/c3ref/snapshot.html + /// See func takeVersionSnapshot() throws -> UnsafeMutablePointer { var snapshot: UnsafeMutablePointer? let code = withUnsafeMutablePointer(to: &snapshot) { @@ -592,7 +592,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// // Stop tracing /// db.trace(options: []) /// - /// See https://www.sqlite.org/c3ref/trace_v2.html for more information. + /// See for more information. /// /// - parameter options: The set of desired event kinds. Defaults to /// `.statement`, which notifies all executed database statements. @@ -700,8 +700,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Runs a WAL checkpoint. /// - /// See https://www.sqlite.org/wal.html and - /// https://www.sqlite.org/c3ref/wal_checkpoint_v2.html for + /// See and + /// for /// more information. /// /// - parameter kind: The checkpoint mode (default passive) @@ -731,7 +731,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Interrupt - // See https://www.sqlite.org/c3ref/interrupt.html + // See func interrupt() { sqlite3_interrupt(sqliteConnection) } @@ -752,7 +752,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Suspends the database. A suspended database prevents database locks in /// order to avoid the [`0xdead10cc` - /// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html). + /// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report). /// /// This method can be called from any thread. /// @@ -773,7 +773,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // Interrupt the database because this may trigger an // SQLITE_INTERRUPT error which may itself abort a transaction and - // release a lock. See https://www.sqlite.org/c3ref/interrupt.html + // release a lock. See interrupt() // Now what about the eventual remaining lock? We'll issue a @@ -784,7 +784,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Resumes the database. A resumed database stops preventing database locks /// in order to avoid the [`0xdead10cc` - /// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html). + /// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report). /// /// This method can be called from any thread. /// @@ -816,7 +816,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Throws SQLITE_ABORT for suspended databases, if statement would lock /// the database, in order to avoid the [`0xdead10cc` - /// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html). + /// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report). func checkForSuspensionViolation(from statement: Statement) throws { try $isSuspended.read { isSuspended in guard isSuspended else { @@ -834,9 +834,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib return } - if let updateStatement = statement as? UpdateStatement, - updateStatement.releasesDatabaseLock - { + if statement.releasesDatabaseLock { // Accept statements that release locks: // - COMMIT // - ROLLBACK @@ -910,7 +908,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// - 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 + /// defaults to .deferred. See /// for more information. /// - block: A block that executes SQL statements and return either /// .commit or .rollback. @@ -1077,7 +1075,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// /// - parameter 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 + /// defaults to .deferred. See /// for more information. /// - throws: The error thrown by the block. public func beginTransaction(_ kind: TransactionKind? = nil) throws { @@ -1255,7 +1253,7 @@ extension Database { } try usePassphrase(data) } - + /// Sets the passphrase used to crypt and decrypt an SQLCipher database. /// /// Call this method from `Configuration.prepareDatabase`, @@ -1284,7 +1282,7 @@ extension Database { } try changePassphrase(data) } - + /// Changes the passphrase used by an SQLCipher encrypted database. public func changePassphrase(_ passphrase: Data) throws { // FIXME: sqlite3_rekey is discouraged. @@ -1311,7 +1309,7 @@ extension Database { // MARK: - Database-Related Types - /// See BusyMode and https://www.sqlite.org/c3ref/busy_handler.html + /// See BusyMode and public typealias BusyCallback = (_ numberOfTries: Int) -> Bool /// When there are several connections to a database, a connection may try @@ -1336,10 +1334,10 @@ extension Database { /// /// Relevant SQLite documentation: /// - /// - https://www.sqlite.org/c3ref/busy_timeout.html - /// - https://www.sqlite.org/c3ref/busy_handler.html - /// - https://www.sqlite.org/lang_transaction.html - /// - https://www.sqlite.org/wal.html + /// - + /// - + /// - + /// - public enum BusyMode { /// The SQLITE_BUSY error is immediately returned to the connection that /// tries to access the locked database. @@ -1350,7 +1348,7 @@ extension Database { case timeout(TimeInterval) /// A custom callback that is called when a database is locked. - /// See https://www.sqlite.org/c3ref/busy_handler.html + /// See case callback(BusyCallback) } @@ -1371,7 +1369,7 @@ extension Database { /// A built-in SQLite collation. /// - /// See https://www.sqlite.org/datatype3.html#collation + /// See public struct CollationName: RawRepresentable, Hashable { /// :nodoc: public let rawValue: String @@ -1398,7 +1396,7 @@ extension Database { /// t.column("title", .text) /// } /// - /// See https://www.sqlite.org/datatype3.html + /// See public struct ColumnType: RawRepresentable, Hashable { /// :nodoc: public let rawValue: String @@ -1435,7 +1433,7 @@ extension Database { /// An SQLite conflict resolution. /// - /// See https://www.sqlite.org/lang_conflict.html. + /// See public enum ConflictResolution: String { /// The `ROLLBACK` conflict resolution case rollback = "ROLLBACK" @@ -1455,7 +1453,7 @@ extension Database { /// A foreign key action. /// - /// See https://www.sqlite.org/foreignkeys.html + /// See public enum ForeignKeyAction: String { /// The `CASCADE` foreign key action case cascade = "CASCADE" @@ -1477,13 +1475,13 @@ extension Database { public struct TracingOptions: OptionSet { /// The raw "Trace Event Code". /// - /// See https://www.sqlite.org/c3ref/c_trace.html + /// See public let rawValue: CInt /// Creates a `TracingOptions` from a raw "Trace Event Code". /// /// See: - /// - https://www.sqlite.org/c3ref/c_trace.html + /// - /// - `Database.trace(options:_:)` public init(rawValue: CInt) { self.rawValue = rawValue @@ -1584,15 +1582,8 @@ extension Database { /// An event reported by `TracingOptions.statement`. case statement(Statement) - #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) /// An event reported by `TracingOptions.profile`. case profile(statement: Statement, duration: TimeInterval) - #elseif os(Linux) - #else - /// An event reported by `TracingOptions.profile`. - @available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) - case profile(statement: Statement, duration: TimeInterval) - #endif public var description: String { switch self { @@ -1614,7 +1605,7 @@ extension Database { case rollback } - /// An SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html + /// An SQLite transaction kind. See public enum TransactionKind: String { /// The `DEFERRED` transaction kind case deferred = "DEFERRED" @@ -1626,7 +1617,7 @@ extension Database { case exclusive = "EXCLUSIVE" } - /// An SQLite threading mode. See https://www.sqlite.org/threadsafe.html. + /// An SQLite threading mode. See . enum ThreadingMode { case `default` case multiThread diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index c5eb6b439..6feed3285 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -51,7 +51,7 @@ extension DatabaseCollation: Hashable { /// Two collations are equal if they share the same name (case insensitive) /// :nodoc: public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool { - // See https://www.sqlite.org/c3ref/create_collation.html + // See return sqlite3_stricmp(lhs.name, rhs.name) == 0 } } diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index ab10baaf0..9fda1eb42 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -2,7 +2,7 @@ import Foundation /// An SQLite result code. /// -/// See https://www.sqlite.org/rescode.html +/// See public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { /// The raw SQLite result code public let rawValue: CInt @@ -13,7 +13,7 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { } /// A result code limited to the least significant 8 bits of the receiver. - /// See https://www.sqlite.org/rescode.html for more information. + /// See for more information. /// /// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY /// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true @@ -193,7 +193,7 @@ extension ResultCode { public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { /// The SQLite error code (see - /// https://www.sqlite.org/rescode.html#primary_result_code_list). + /// ). /// /// do { /// ... @@ -203,7 +203,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { /// /// This property returns a "primary result code", that is to say the least /// significant 8 bits of any SQLite result code. See - /// https://www.sqlite.org/rescode.html for more information. + /// for more information. /// /// See also `extendedResultCode`. public var resultCode: ResultCode { @@ -211,7 +211,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { } /// The SQLite extended error code (see - /// https://www.sqlite.org/rescode.html#extended_result_code_list). + /// ). /// /// do { /// ... diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index fb137e7c4..b71b70ca5 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -109,7 +109,7 @@ public final class DatabaseFunction: Hashable { /// Returns an SQL expression that applies the function. /// - /// See https://github.com/groue/GRDB.swift/#sql-functions + /// See public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression { switch kind { case .aggregate: @@ -120,7 +120,7 @@ public final class DatabaseFunction: Hashable { } /// Calls sqlite3_create_function_v2 - /// See https://sqlite.org/c3ref/create_function.html + /// See func install(in db: Database) { // Retain the function definition let definition = kind.definition @@ -147,7 +147,7 @@ public final class DatabaseFunction: Hashable { } /// Calls sqlite3_create_function_v2 - /// See https://sqlite.org/c3ref/create_function.html + /// See func uninstall(in db: Database) { let code = sqlite3_create_function_v2( db.sqliteConnection, @@ -164,7 +164,7 @@ public final class DatabaseFunction: Hashable { /// The way to compute the result of a function. /// Feeds the `pApp` parameter of sqlite3_create_function_v2 - /// http://sqlite.org/capi3ref.html#sqlite3_create_function + /// private class FunctionDefinition { let compute: (Int32, UnsafeMutablePointer?) throws -> DatabaseValueConvertible? init(compute: @escaping (Int32, UnsafeMutablePointer?) throws -> DatabaseValueConvertible?) { @@ -174,7 +174,7 @@ public final class DatabaseFunction: Hashable { /// The way to start an aggregate. /// Feeds the `pApp` parameter of sqlite3_create_function_v2 - /// http://sqlite.org/capi3ref.html#sqlite3_create_function + /// private class AggregateDefinition { let makeAggregate: () -> DatabaseAggregate init(makeAggregate: @escaping () -> DatabaseAggregate) { @@ -192,7 +192,7 @@ public final class DatabaseFunction: Hashable { } /// A function kind: an "SQL function" or an "aggregate". - /// See http://sqlite.org/capi3ref.html#sqlite3_create_function + /// See private enum Kind { /// A regular function: SELECT f(1) case function((Int32, UnsafeMutablePointer?) throws -> DatabaseValueConvertible?) @@ -201,7 +201,7 @@ public final class DatabaseFunction: Hashable { case aggregate(() -> DatabaseAggregate) /// Feeds the `pApp` parameter of sqlite3_create_function_v2 - /// http://sqlite.org/capi3ref.html#sqlite3_create_function + /// var definition: AnyObject { switch self { case .function(let compute): @@ -212,7 +212,7 @@ public final class DatabaseFunction: Hashable { } /// Feeds the `xFunc` parameter of sqlite3_create_function_v2 - /// http://sqlite.org/capi3ref.html#sqlite3_create_function + /// var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer?) -> Void)? { guard case .function = self else { return nil } return { (sqliteContext, argc, argv) in @@ -230,7 +230,7 @@ public final class DatabaseFunction: Hashable { } /// Feeds the `xStep` parameter of sqlite3_create_function_v2 - /// http://sqlite.org/capi3ref.html#sqlite3_create_function + /// var xStep: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer?) -> Void)? { guard case .aggregate = self else { return nil } return { (sqliteContext, argc, argv) in @@ -250,7 +250,7 @@ public final class DatabaseFunction: Hashable { } /// Feeds the `xFinal` parameter of sqlite3_create_function_v2 - /// http://sqlite.org/capi3ref.html#sqlite3_create_function + /// var xFinal: (@convention(c) (OpaquePointer?) -> Void)? { guard case .aggregate = self else { return nil } return { (sqliteContext) in @@ -278,8 +278,8 @@ public final class DatabaseFunction: Hashable { /// /// The result must be released when the aggregate concludes. /// - /// See https://sqlite.org/c3ref/context.html - /// See https://sqlite.org/c3ref/aggregate_context.html + /// See + /// See private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged { // > The first time the sqlite3_aggregate_context(C,N) routine is called // > for a particular aggregate function, SQLite allocates N of memory, diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 6a51ae8bf..40f5d32a9 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -754,7 +754,7 @@ extension DatabasePool: DatabaseReader { /// - 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 + /// defaults to .deferred. See /// for more information. /// - updates: The updates to the database. /// - throws: The error thrown by the updates, or by the @@ -1072,7 +1072,7 @@ extension DatabasePool { /// 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 + /// For more information, read about "snapshot isolation" at public func makeSnapshot() throws -> DatabaseSnapshot { // Sanity check if writer.onValidQueue { diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index bc5df2833..7264c583e 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -361,7 +361,7 @@ extension DatabaseQueue { /// - 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 + /// defaults to .deferred. See /// for more information. /// - updates: The updates to the database. /// - throws: The error thrown by the updates, or by the diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 033349beb..18349a9dc 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -20,9 +20,9 @@ /// /// - `DatabaseRegion(table:)`: the region that covers one database table. /// -/// - `SelectStatement.databaseRegion`: +/// - `Statement.databaseRegion`: /// -/// let statement = try db.makeSelectStatement(sql: "SELECT name, score FROM player") +/// let statement = try db.makeStatement(sql: "SELECT name, score FROM player") /// let region = statement.databaseRegion /// /// - `FetchRequest.databaseRegion(_:)` diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 3c280b926..768ce697e 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -5,7 +5,7 @@ import Dispatch /// /// See DatabasePool.makeSnapshot() /// -/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html +/// For more information, read about "snapshot isolation" at public class DatabaseSnapshot: DatabaseReader { private var serializedDatabase: SerializedDatabase @@ -40,7 +40,7 @@ public class DatabaseSnapshot: DatabaseReader { try db.beginTransaction(.deferred) // Acquire snapshot isolation - try db.internalCachedSelectStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next() + try db.internalCachedStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next() #if SQLITE_ENABLE_SNAPSHOT // We must expect an error: https://www.sqlite.org/c3ref/snapshot_get.html diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index f5f1f9ffe..65397b29c 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -4,7 +4,7 @@ import Foundation /// DatabaseValue is the intermediate type between SQLite and your values. /// -/// See https://www.sqlite.org/datatype3.html +/// See public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLSpecificExpressible { /// The SQLite storage public let storage: Storage diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index b99ef5b15..2347e6e9e 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -8,7 +8,7 @@ /// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String] /// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String? /// -/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") +/// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// try String.fetchCursor(statement, arguments:...) // Cursor of String /// try String.fetchAll(statement, arguments:...) // [String] /// try String.fetchOne(statement, arguments:...) // String? @@ -58,7 +58,7 @@ extension DatabaseValueConvertible { let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) return try decode(fromDatabaseValue: dbValue, context: context()) } - + @usableFromInline static func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self { if let sqliteStatement = row.sqliteStatement { @@ -71,7 +71,7 @@ extension DatabaseValueConvertible { fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index), context: RowDecodingContext(row: row, key: .columnIndex(index))) } - + static func decodeIfPresent( fromDatabaseValue dbValue: DatabaseValue, context: @autoclosure () -> RowDecodingContext) @@ -86,7 +86,7 @@ extension DatabaseValueConvertible { throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) } } - + @usableFromInline static func decodeIfPresent( fromStatement sqliteStatement: SQLiteStatement, @@ -103,7 +103,7 @@ extension DatabaseValueConvertible { throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) } } - + @usableFromInline static func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self? { if let sqliteStatement = row.sqliteStatement { @@ -130,12 +130,16 @@ extension DatabaseValueConvertible { /// } /// } public final class DatabaseValueCursor: Cursor { - @usableFromInline let _statement: SelectStatement + @usableFromInline enum _State { + case idle, busy, done, failed + } + + @usableFromInline let _statement: Statement @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline let _columnIndex: Int32 - @usableFromInline var _done = false + @usableFromInline var _state = _State.idle - init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { _statement = statement _sqliteStatement = statement.sqliteStatement if let adapter = adapter { @@ -144,13 +148,16 @@ public final class DatabaseValueCursor: Cursor } else { _columnIndex = 0 } - _statement.reset(withArguments: arguments) - // Assume cursor is created for iteration - try statement.database.selectStatementWillExecute(statement) + // Assume cursor is created for immediate iteration: reset and set arguments + statement.reset(withArguments: arguments) } deinit { + if _state == .busy { + try? _statement.database.statementDidExecute(_statement) + } + // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. try? _statement.reset() @@ -158,14 +165,28 @@ public final class DatabaseValueCursor: Cursor @inlinable public func next() throws -> Value? { - if _done { + switch _state { + case .done: // make sure this instance never yields a value again, even if the // statement is reset by another cursor. return nil + case .idle: + guard try _statement.database.statementWillExecute(_statement) == nil else { + throw DatabaseError( + resultCode: SQLITE_MISUSE, + message: "Can't run statement that requires a customized authorizer from a cursor", + sql: _statement.sql, + arguments: _statement.arguments) + } + _state = .busy + default: + break } + switch sqlite3_step(_sqliteStatement) { case SQLITE_DONE: - _done = true + _state = .done + try _statement.database.statementDidExecute(_statement) return nil case SQLITE_ROW: // TODO GRDB6: don't crash on decoding errors @@ -174,7 +195,8 @@ public final class DatabaseValueCursor: Cursor atUncheckedIndex: _columnIndex, context: RowDecodingContext(statement: _statement, index: Int(_columnIndex))) case let code: - try _statement.didFail(withResultCode: code) + _state = .failed + try _statement.database.statementDidFail(_statement, withResultCode: code) } } } @@ -189,12 +211,16 @@ public final class DatabaseValueCursor: Cursor /// } /// } public final class NullableDatabaseValueCursor: Cursor { - @usableFromInline let _statement: SelectStatement + @usableFromInline enum _State { + case idle, busy, done, failed + } + + @usableFromInline let _statement: Statement @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline let _columnIndex: Int32 - @usableFromInline var _done = false + @usableFromInline var _state = _State.idle - init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { _statement = statement _sqliteStatement = statement.sqliteStatement if let adapter = adapter { @@ -203,13 +229,16 @@ public final class NullableDatabaseValueCursor: } else { _columnIndex = 0 } - _statement.reset(withArguments: arguments) - // Assume cursor is created for iteration - try statement.database.selectStatementWillExecute(statement) + // Assume cursor is created for immediate iteration: reset and set arguments + statement.reset(withArguments: arguments) } deinit { + if _state == .busy { + try? _statement.database.statementDidExecute(_statement) + } + // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. try? _statement.reset() @@ -217,14 +246,28 @@ public final class NullableDatabaseValueCursor: @inlinable public func next() throws -> Value?? { - if _done { + switch _state { + case .done: // make sure this instance never yields a value again, even if the // statement is reset by another cursor. return nil + case .idle: + guard try _statement.database.statementWillExecute(_statement) == nil else { + throw DatabaseError( + resultCode: SQLITE_MISUSE, + message: "Can't run statement that requires a customized authorizer from a cursor", + sql: _statement.sql, + arguments: _statement.arguments) + } + _state = .busy + default: + break } + switch sqlite3_step(_sqliteStatement) { case SQLITE_DONE: - _done = true + _state = .done + try _statement.database.statementDidExecute(_statement) return nil case SQLITE_ROW: // TODO GRDB6: don't crash on decoding errors @@ -233,7 +276,8 @@ public final class NullableDatabaseValueCursor: atUncheckedIndex: _columnIndex, context: RowDecodingContext(statement: _statement, index: Int(_columnIndex))) case let code: - try _statement.didFail(withResultCode: code) + _state = .failed + try _statement.database.statementDidFail(_statement, withResultCode: code) } } } @@ -245,7 +289,7 @@ public final class NullableDatabaseValueCursor: /// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String] /// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String? /// -/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") +/// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// try String.fetchCursor(statement, arguments:...) // Cursor of String /// try String.fetchAll(statement, arguments:...) // [String] /// try String.fetchOne(statement, arguments:...) // String @@ -253,11 +297,11 @@ public final class NullableDatabaseValueCursor: /// DatabaseValueConvertible is adopted by Bool, Int, String, etc. extension DatabaseValueConvertible { - // MARK: Fetching From SelectStatement + // MARK: Fetching From Prepared Statement /// Returns a cursor over values fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let names = try String.fetchCursor(statement) // Cursor of String /// while let name = try names.next() { // String /// ... @@ -275,7 +319,7 @@ extension DatabaseValueConvertible { /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor @@ -285,7 +329,7 @@ extension DatabaseValueConvertible { /// Returns an array of values fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let names = try String.fetchAll(statement) // [String] /// /// - parameters: @@ -295,7 +339,7 @@ extension DatabaseValueConvertible { /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] @@ -308,7 +352,7 @@ extension DatabaseValueConvertible { /// The result is nil if the query returns no row, or if no value can be /// extracted from the first row. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let name = try String.fetchOne(statement) // String? /// /// - parameters: @@ -318,7 +362,7 @@ extension DatabaseValueConvertible { /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? @@ -332,7 +376,7 @@ extension DatabaseValueConvertible { extension DatabaseValueConvertible where Self: Hashable { /// Returns a set of values fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let names = try String.fetchSet(statement) // Set /// /// - parameters: @@ -342,7 +386,7 @@ extension DatabaseValueConvertible where Self: Hashable { /// - returns: A set. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchSet( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Set @@ -603,18 +647,18 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable { /// try Optional.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String? /// try Optional.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String?] /// -/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") +/// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// try Optional.fetchCursor(statement, arguments:...) // Cursor of String? /// try Optional.fetchAll(statement, arguments:...) // [String?] /// /// DatabaseValueConvertible is adopted by Bool, Int, String, etc. extension Optional where Wrapped: DatabaseValueConvertible { - // MARK: Fetching From SelectStatement + // MARK: Fetching From Prepared Statement /// Returns a cursor over optional values fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let names = try Optional.fetchCursor(statement) // Cursor of String? /// while let name = try names.next() { // String? /// ... @@ -632,7 +676,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( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor @@ -642,7 +686,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// Returns an array of optional values fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let names = try Optional.fetchAll(statement) // [String?] /// /// - parameters: @@ -652,7 +696,7 @@ 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( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] @@ -664,7 +708,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { extension Optional where Wrapped: DatabaseValueConvertible & Hashable { /// Returns a set of optional values fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let names = try Optional.fetchSet(statement) // Set /// /// - parameters: @@ -674,7 +718,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & Hashable { /// - returns: A set of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchSet( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Set diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index caf66bbf3..1f5fd8d46 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -315,11 +315,50 @@ extension DatabaseWriter { /// Rebuilds the database file, repacking it into a minimal amount of /// disk space. /// - /// See https://www.sqlite.org/lang_vacuum.html for more information. + /// See for more information. public func vacuum() throws { try writeWithoutTransaction { try $0.execute(sql: "VACUUM") } } + // VACUUM INTO was introduced in SQLite 3.27.0: + // https://www.sqlite.org/releaselog/3_27_0.html + // + // Old versions of SQLCipher won't have it, but I don't know how to perform + // availability checks that depend on the version of the SQLCipher CocoaPod + // chosen by the application. So let's just have the method fail at runtime. + // + // This method is declared on DatabaseWriter instead of DatabaseReader, + // so that it is not available on DatabaseSnaphot. VACUUM INTO is not + // available inside the transaction that is kept open by DatabaseSnaphot. + #if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Creates a new database file at the specified path with a minimum + /// amount of disk space. + /// + /// Databases encrypted with SQLCipher are copied with the same password + /// and configuration as the original database. + /// + /// See for more information. + /// + /// - Parameter filePath: file path for new database + public func vacuum(into filePath: String) throws { + try writeWithoutTransaction { + try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath]) + } + } + #else + /// Creates a new database file at the specified path with a minimum + /// amount of disk space. + /// See for more information. + /// + /// - Parameter filePath: file path for new database + @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) + public func vacuum(into filePath: String) throws { + try writeWithoutTransaction { + try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath]) + } + } + #endif + // MARK: - Database Observation /// A write-only observation only uses the serialized writer diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 1c4ae00b5..b474d1aef 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -49,7 +49,7 @@ extension FetchRequest { /// A PreparedRequest is a request that is ready to be executed. public struct PreparedRequest { /// A prepared statement - public var statement: SelectStatement + public var statement: Statement /// An eventual adapter for rows fetched by the select statement public var adapter: RowAdapter? @@ -58,7 +58,7 @@ public struct PreparedRequest { var supplementaryFetch: ((Database, [Row]) throws -> Void)? init( - statement: SelectStatement, + statement: Statement, adapter: RowAdapter?, supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil) { diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 8b098994e..01fcb86ad 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -14,7 +14,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, /// /// let rows = try Row.fetchCursor(db, sql: "SELECT ...") /// let players = try Player.fetchAll(db, sql: "SELECT ...") - @usableFromInline let statement: SelectStatement? + @usableFromInline let statement: Statement? @usableFromInline let sqliteStatement: SQLiteStatement? /// The number of columns in the row. @@ -96,7 +96,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, /// The row is implemented on top of StatementRowImpl, which grants *direct* /// access to the SQLite statement. Iteration of the statement does modify /// the row. - init(statement: SelectStatement) { + init(statement: Statement) { self.statement = statement self.sqliteStatement = statement.sqliteStatement self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement) @@ -120,7 +120,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, /// statement does not modify the row. convenience init( copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, - statement: SelectStatement) + statement: Statement) { self.init(impl: StatementCopyRowImpl( sqliteStatement: sqliteStatement, @@ -239,7 +239,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). + /// (see ). @inlinable public subscript(_ index: Int) -> Value? { try! decodeIfPresent(Value.self, atIndex: index) @@ -267,7 +267,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). + /// (see ). @inlinable public subscript(_ index: Int) -> Value { try! decode(Value.self, atIndex: index) @@ -318,7 +318,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). + /// (see ). @inlinable public subscript(_ columnName: String) -> Value? { try! decodeIfPresent(Value.self, forKey: columnName) @@ -350,7 +350,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). + /// (see ). @inlinable public subscript(_ columnName: String) -> Value { try! decode(Value.self, forKey: columnName) @@ -392,7 +392,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). + /// (see ). @inlinable public subscript(_ column: Column) -> Value? @@ -429,7 +429,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). + /// (see ). @inlinable public subscript(_ column: Column) -> Value @@ -531,7 +531,7 @@ extension Row { /// A fatal error is raised if the scope is not available, or contains only /// null values. /// - /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support + /// See /// for more information. public subscript(_ scope: String) -> Record { try! decode(Record.self, forKey: scope) @@ -566,7 +566,7 @@ extension Row { /// Nil is returned if the scope is not available, or contains only /// null values. /// - /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support + /// See /// for more information. public subscript(_ scope: String) -> Record? { try! decodeIfPresent(Record.self, forKey: scope) @@ -786,7 +786,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). + /// (see ). @inlinable func decodeIfPresent( _ type: Value.Type = Value.self, @@ -806,7 +806,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). + /// (see ). @inlinable func decode( _ type: Value.Type = Value.self, @@ -827,7 +827,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). + /// (see ). @inlinable func decodeIfPresent( _ type: Value.Type = Value.self, @@ -851,7 +851,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). + /// (see ). @inlinable func decode( _ type: Value.Type = Value.self, @@ -997,7 +997,7 @@ extension Row { /// Nil is returned if the scope is not available, or contains only /// null values. /// - /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support + /// See /// for more information. func decodeIfPresent( _ type: Record.Type = Record.self, @@ -1039,7 +1039,7 @@ extension Row { /// A fatal error is raised if the scope is not available, or contains only /// null values. /// - /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support + /// See /// for more information. func decode( _ type: Record.Type = Record.self, @@ -1189,23 +1189,30 @@ extension Row { /// let rows: RowCursor = try Row.fetchCursor(db, sql: "SELECT * FROM player") /// } public final class RowCursor: Cursor { + @usableFromInline enum _State { + case idle, busy, done, failed + } + /// The statement iterated by this cursor - public let statement: SelectStatement + public let statement: Statement @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline let _row: Row // Reused for performance - @usableFromInline var _done = false + @usableFromInline var _state = _State.idle - init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { self.statement = statement self._row = try Row(statement: statement).adapted(with: adapter, layout: statement) self._sqliteStatement = statement.sqliteStatement - statement.reset(withArguments: arguments) - // Assume cursor is created for iteration - try statement.database.selectStatementWillExecute(statement) + // Assume cursor is created for immediate iteration: reset and set arguments + statement.reset(withArguments: arguments) } deinit { + if _state == .busy { + try? statement.database.statementDidExecute(statement) + } + // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. try? statement.reset() @@ -1213,30 +1220,45 @@ public final class RowCursor: Cursor { @inlinable public func next() throws -> Row? { - if _done { + switch _state { + case .done: // make sure this instance never yields a value again, even if the // statement is reset by another cursor. return nil + case .idle: + guard try statement.database.statementWillExecute(statement) == nil else { + throw DatabaseError( + resultCode: SQLITE_MISUSE, + message: "Can't run statement that requires a customized authorizer from a cursor", + sql: statement.sql, + arguments: statement.arguments) + } + _state = .busy + default: + break } + switch sqlite3_step(_sqliteStatement) { case SQLITE_DONE: - _done = true + _state = .done + try statement.database.statementDidExecute(statement) return nil case SQLITE_ROW: return _row case let code: - try statement.didFail(withResultCode: code) + _state = .failed + try statement.database.statementDidFail(statement, withResultCode: code) } } } extension Row { - // MARK: - Fetching From SelectStatement + // MARK: - Fetching From Prepared Statement /// Returns a cursor over rows fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT ...") + /// let statement = try db.makeStatement(sql: "SELECT ...") /// let rows = try Row.fetchCursor(statement) // RowCursor /// while let row = try rows.next() { // Row /// let id: Int64 = row[0] @@ -1264,7 +1286,7 @@ extension Row { /// - returns: A cursor over fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor @@ -1274,7 +1296,7 @@ extension Row { /// Returns an array of rows fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT ...") + /// let statement = try db.makeStatement(sql: "SELECT ...") /// let rows = try Row.fetchAll(statement) /// /// - parameters: @@ -1284,7 +1306,7 @@ extension Row { /// - returns: An array of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] @@ -1295,7 +1317,7 @@ extension Row { /// Returns a set of rows fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT ...") + /// let statement = try db.makeStatement(sql: "SELECT ...") /// let rows = try Row.fetchSet(statement) /// /// - parameters: @@ -1305,7 +1327,7 @@ extension Row { /// - returns: A set of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchSet( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Set @@ -1316,7 +1338,7 @@ extension Row { /// Returns a single row fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT ...") + /// let statement = try db.makeStatement(sql: "SELECT ...") /// let row = try Row.fetchOne(statement) /// /// - parameters: @@ -1326,7 +1348,7 @@ extension Row { /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? @@ -2225,11 +2247,11 @@ private struct StatementCopyRowImpl: RowImpl { /// See Row.init(statement:) private struct StatementRowImpl: RowImpl { - let statement: SelectStatement + let statement: Statement let sqliteStatement: SQLiteStatement let lowercaseColumnIndexes: [String: Int] - init(sqliteStatement: SQLiteStatement, statement: SelectStatement) { + init(sqliteStatement: SQLiteStatement, statement: Statement) { self.statement = statement self.sqliteStatement = sqliteStatement // Optimize row[columnName] diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index a7c85d3de..5e0880f8c 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -141,7 +141,7 @@ public protocol _RowLayout { func _layoutIndex(ofColumn name: String) -> Int? } -extension SelectStatement: _RowLayout { +extension Statement: _RowLayout { /// :nodoc: public var _layoutColumns: [(Int, String)] { Array(columnNames.enumerated()) diff --git a/GRDB/Core/RowDecodingError.swift b/GRDB/Core/RowDecodingError.swift index 6392886ec..a0c0182f6 100644 --- a/GRDB/Core/RowDecodingError.swift +++ b/GRDB/Core/RowDecodingError.swift @@ -92,7 +92,7 @@ enum RowDecodingError: Error { @usableFromInline static func valueMismatch( _ type: Any.Type, - statement: SelectStatement, + statement: Statement, index: Int) -> Self { @@ -149,7 +149,7 @@ struct RowDecodingContext { /// Convenience initializer @usableFromInline - init(statement: SelectStatement, index: Int) { + init(statement: Statement, index: Int) { self.key = .columnIndex(index) self.row = Row(copiedFromSQLiteStatement: statement.sqliteStatement, statement: statement) self.sql = statement.sql @@ -171,7 +171,7 @@ extension RowDecodingError: CustomStringConvertible { let columnName = row.columnNames[rowIndex] chunks.append("column: \(String(reflecting: columnName))") chunks.append("column index: \(columnIndex)") - + case let .columnName(columnName): if let columnIndex = row.index(forColumn: columnName) { chunks.append("column: \(String(reflecting: columnName))") diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 50097b34f..04bca77e7 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -155,14 +155,14 @@ extension SQLRequest: FetchRequest { { let context = SQLGenerationContext(db) let sql = try sqlLiteral.sql(context) - let statement: SelectStatement + let statement: Statement switch cache { case .none: - statement = try db.makeSelectStatement(sql: sql) + statement = try db.makeStatement(sql: sql) case .public?: - statement = try db.cachedSelectStatement(sql: sql) + statement = try db.cachedStatement(sql: sql) case .internal?: - statement = try db.internalCachedSelectStatement(sql: sql) + statement = try db.internalCachedStatement(sql: sql) } try statement.setArguments(context.arguments) return PreparedRequest(statement: statement, adapter: adapter) diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index 3d857daf0..1f836b841 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -6,7 +6,7 @@ import Dispatch /// /// Generally speaking, each connection has its own dispatch queue. But it's not /// enough: users need to use two database connections at the same time: -/// https://github.com/groue/GRDB.swift/issues/55. To support this use case, a +/// . To support this use case, a /// single dispatch queue can be temporarily shared by two or more connections. /// /// - SchedulingWatchdog.makeSerializedQueue(allowingDatabase:) creates a diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 66083f1a8..19fc6e601 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -9,10 +9,15 @@ extension CharacterSet { } /// A statement represents an SQL query. -/// -/// It is the base class of UpdateStatement that executes *update statements*, -/// and SelectStatement that fetches rows. -public class Statement { +public final class Statement { + enum TransactionEffect { + case beginTransaction + case commitTransaction + case rollbackTransaction + case beginSavepoint(String) + case releaseSavepoint(String) + case rollbackSavepoint(String) + } /// The raw SQLite statement, suitable for the SQLite C API. public let sqliteStatement: SQLiteStatement @@ -26,20 +31,43 @@ public class Statement { .trimmingCharacters(in: .sqlStatementSeparators) } + /// The column names, ordered from left to right. + public lazy var columnNames: [String] = { + let sqliteStatement = self.sqliteStatement + return (0... + public var isReadonly: Bool { sqlite3_stmt_readonly(sqliteStatement) != 0 } @usableFromInline unowned let database: Database + /// Cache for index(ofColumn:). Keys are lowercase. + private lazy var columnIndexes: [String: Int] = { + Dictionary( + self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) }, + uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes + }() + /// Creates a prepared statement. Returns nil if the compiled string is /// blank or empty. /// @@ -49,7 +77,7 @@ public class Statement { /// - parameter statementEnd: Upon success, the pointer to the next /// statement in the C string. /// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from - /// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html) + /// SQLite 3.20.0, see ) /// - parameter authorizer: A StatementCompilationAuthorizer /// - throws: DatabaseError in case of compilation error. required init?( @@ -92,6 +120,9 @@ public class Statement { self.database = database self.sqliteStatement = statement self.databaseRegion = authorizer.selectedRegion + self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache + self.transactionEffect = authorizer.transactionEffect + self.databaseEventKinds = authorizer.databaseEventKinds } deinit { @@ -115,7 +146,7 @@ public class Statement { @usableFromInline var _arguments = StatementArguments() - + lazy var sqliteArgumentCount: Int = { Int(sqlite3_bind_parameter_count(self.sqliteStatement)) }() @@ -264,117 +295,26 @@ public class Statement { } } +@available(*, deprecated, renamed: "Statement") +public typealias SelectStatement = Statement + +@available(*, deprecated, renamed: "Statement") +public typealias UpdateStatement = Statement + extension Statement: CustomStringConvertible { public var description: String { "SQL: \(sql), Arguments: \(arguments)" } } -// MARK: - Statement Preparation +// MARK: - Select Statements extension Statement { - // Static method instead of an initializer because initializer can't run - // inside `sqlCodeUnits.withUnsafeBufferPointer`. - static func prepare(_ db: Database, sql: String, prepFlags: Int32) throws -> Self { - let authorizer = StatementCompilationAuthorizer() - return try db.withAuthorizer(authorizer) { - try sql.utf8CString.withUnsafeBufferPointer { buffer in - let statementStart = buffer.baseAddress! - var statementEnd: UnsafePointer? = nil - guard let statement = try self.init( - database: db, - statementStart: statementStart, - statementEnd: &statementEnd, - prepFlags: prepFlags, - authorizer: authorizer) else - { - throw DatabaseError( - resultCode: .SQLITE_ERROR, - message: "empty statement", - sql: sql) - } - - let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators) - guard remainingSQL.isEmpty else { - throw DatabaseError( - resultCode: .SQLITE_MISUSE, - message: """ - Multiple statements found. To execute multiple statements, \ - use Database.execute(sql:) instead. - """, - sql: sql) - } - - return statement - } - } - } -} - -// MARK: - SelectStatement - -/// A subclass of Statement that fetches database rows. -/// -/// You create SelectStatement with the Database.makeSelectStatement() method: -/// -/// try dbQueue.read { db in -/// let statement = try db.makeSelectStatement(sql: "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 { - /// Creates a prepared statement. Returns nil if the compiled string is - /// blank or empty. - /// - /// - parameter database: A database connection. - /// - parameter statementStart: A pointer to a UTF-8 encoded C string - /// containing SQL. - /// - parameter statementEnd: Upon success, the pointer to the next - /// statement in the C string. - /// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from - /// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html) - /// - parameter authorizer: A StatementCompilationAuthorizer - /// - throws: DatabaseError in case of compilation error. - required init?( - database: Database, - statementStart: UnsafePointer, - statementEnd: UnsafeMutablePointer?>, - prepFlags: Int32, - authorizer: StatementCompilationAuthorizer) throws - { - try super.init( - database: database, - statementStart: statementStart, - statementEnd: statementEnd, - prepFlags: prepFlags, - authorizer: authorizer) - - 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.") - } - /// The number of columns in the resulting rows. public var columnCount: Int { Int(sqlite3_column_count(self.sqliteStatement)) } - /// The column names, ordered from left to right. - public lazy var columnNames: [String] = { - let sqliteStatement = self.sqliteStatement - return (0.. Int? { @@ -387,17 +327,6 @@ public final class SelectStatement: Statement { func makeCursor(arguments: StatementArguments? = nil) throws -> StatementCursor { try StatementCursor(statement: self, arguments: arguments) } - - /// Utility function for cursors - @usableFromInline - func didFail(withResultCode resultCode: Int32) throws -> Never { - database.selectStatementDidFail(self) - throw DatabaseError( - resultCode: resultCode, - message: database.lastErrorMessage, - sql: sql, - arguments: arguments) - } } /// A cursor that iterates a database statement without producing any value. @@ -406,26 +335,33 @@ public final class SelectStatement: Statement { /// For example: /// /// try dbQueue.read { db in -/// let statement = db.makeSelectStatement(sql: "SELECT performSideEffect()") +/// let statement = db.makeStatement(sql: "SELECT performSideEffect()") /// let cursor = statement.makeCursor() /// try cursor.next() /// } final class StatementCursor: Cursor { - let _statement: SelectStatement - let _sqliteStatement: SQLiteStatement - var _done = false + @usableFromInline enum _State { + case idle, busy, done, failed + } - // Use SelectStatement.makeCursor() instead - init(statement: SelectStatement, arguments: StatementArguments? = nil) throws { + let _statement: Statement + let _sqliteStatement: SQLiteStatement + var _state = _State.idle + + // Use Statement.makeCursor() instead + init(statement: Statement, arguments: StatementArguments? = nil) throws { _statement = statement _sqliteStatement = statement.sqliteStatement - _statement.reset(withArguments: arguments) - // Assume cursor is created for iteration - try statement.database.selectStatementWillExecute(statement) + // Assume cursor is created for immediate iteration: reset and set arguments + statement.reset(withArguments: arguments) } deinit { + if _state == .busy { + try? _statement.database.statementDidExecute(_statement) + } + // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. try? _statement.reset() @@ -434,53 +370,41 @@ final class StatementCursor: Cursor { /// :nodoc: @inlinable func next() throws -> Void? { - if _done { + switch _state { + case .done: // make sure this instance never yields a value again, even if the // statement is reset by another cursor. return nil + case .idle: + guard try _statement.database.statementWillExecute(_statement) == nil else { + throw DatabaseError( + resultCode: SQLITE_MISUSE, + message: "Can't run statement that requires a customized authorizer from a cursor", + sql: _statement.sql, + arguments: _statement.arguments) + } + _state = .busy + default: + break } + switch sqlite3_step(_sqliteStatement) { case SQLITE_DONE: - _done = true + _state = .done + try _statement.database.statementDidExecute(_statement) return nil case SQLITE_ROW: return .some(()) case let code: - try _statement.didFail(withResultCode: code) + _state = .failed + try _statement.database.statementDidFail(_statement, withResultCode: code) } } } +// MARK: - Update Statements -// MARK: - UpdateStatement - -/// A subclass of Statement that executes SQL queries. -/// -/// You create UpdateStatement with the Database.makeUpdateStatement() method: -/// -/// try dbQueue.inTransaction { db in -/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)") -/// try statement.execute(arguments: ["Arthur"]) -/// try statement.execute(arguments: ["Barbara"]) -/// return .commit -/// } -public final class UpdateStatement: Statement { - enum TransactionEffect { - case beginTransaction - case commitTransaction - case rollbackTransaction - case beginSavepoint(String) - case releaseSavepoint(String) - case rollbackSavepoint(String) - } - - /// If true, the database schema cache gets invalidated after this statement - /// is executed. - private(set) var invalidatesDatabaseSchemaCache: Bool = false - - private(set) var transactionEffect: TransactionEffect? - private(set) var databaseEventKinds: [DatabaseEventKind] = [] - +extension Statement { var releasesDatabaseLock: Bool { guard let transactionEffect = transactionEffect else { return false @@ -500,37 +424,7 @@ public final class UpdateStatement: Statement { } } - /// Creates a prepared statement. Returns nil if the compiled string is - /// blank or empty. - /// - /// - parameter database: A database connection. - /// - parameter statementStart: A pointer to a UTF-8 encoded C string - /// containing SQL. - /// - parameter statementEnd: Upon success, the pointer to the next - /// statement in the C string. - /// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from - /// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html) - /// - parameter authorizer: A StatementCompilationAuthorizer - /// - throws: DatabaseError in case of compilation error. - required init?( - database: Database, - statementStart: UnsafePointer, - statementEnd: UnsafeMutablePointer?>, - prepFlags: Int32, - authorizer: StatementCompilationAuthorizer) throws - { - try super.init( - database: database, - statementStart: statementStart, - statementEnd: statementEnd, - prepFlags: prepFlags, - authorizer: authorizer) - self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache - self.transactionEffect = authorizer.transactionEffect - self.databaseEventKinds = authorizer.databaseEventKinds - } - - /// Executes the SQL query. + /// Executes the prepared statement. /// /// - parameter arguments: Optional statement arguments. /// - throws: A DatabaseError whenever an SQLite error occurs. @@ -541,7 +435,7 @@ public final class UpdateStatement: Statement { // Statement does not know how to execute itself, because it does not // know how to handle its errors, or if truncate optimisation should be // prevented or not. Database knows. - try database.executeUpdateStatement(self) + try database.executeStatement(self) } } @@ -561,7 +455,7 @@ public protocol StatementBinding { /// StatementArguments provide values to argument placeholders in raw /// SQL queries. /// -/// Placeholders can take several forms (see https://www.sqlite.org/lang_expr.html#varparam +/// Placeholders can take several forms (see /// for more information): /// /// - `?NNN` (e.g. `?2`): the NNN-th argument (starts at 1) diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index b07b22e46..44fea582c 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -3,6 +3,7 @@ import Glibc #endif /// A protocol around sqlite3_set_authorizer +@usableFromInline protocol StatementAuthorizer: AnyObject { func authorize( _ actionCode: Int32, @@ -28,7 +29,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer { /// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction or /// savepoint statement. - var transactionEffect: UpdateStatement.TransactionEffect? + var transactionEffect: Statement.TransactionEffect? private var isDropStatement = false diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 50a2d6835..e4bdb7709 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -1,6 +1,6 @@ /// The `StatementColumnConvertible` protocol grants access to the low-level C /// interface that extracts values from query results: -/// https://www.sqlite.org/c3ref/column_blob.html. It can bring performance +/// . It can bring performance /// improvements. /// /// To use it, have a value type adopt both `StatementColumnConvertible` and @@ -34,7 +34,7 @@ public protocol StatementColumnConvertible { /// `nil` for failed conversions: GRDB will interpret a nil result as a /// decoding failure. /// - /// See https://www.sqlite.org/c3ref/column_blob.html for more information. + /// See for more information. /// /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. @@ -63,7 +63,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { } return value } - + @inlinable static func fastDecode( fromRow row: Row, @@ -79,7 +79,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { // Support for fast decoding from adapted rows return try row.fastDecode(Self.self, atUncheckedIndex: index) } - + @inlinable static func fastDecodeIfPresent( fromStatement sqliteStatement: SQLiteStatement, @@ -99,7 +99,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { } return value } - + @inlinable static func fastDecodeIfPresent( fromRow row: Row, @@ -129,12 +129,16 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// } /// } public final class FastDatabaseValueCursor : Cursor { - @usableFromInline let _statement: SelectStatement + @usableFromInline enum _State { + case idle, busy, done, failed + } + + @usableFromInline let _statement: Statement @usableFromInline let _columnIndex: Int32 @usableFromInline let _sqliteStatement: SQLiteStatement - @usableFromInline var _done = false + @usableFromInline var _state = _State.idle - init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { _statement = statement _sqliteStatement = statement.sqliteStatement if let adapter = adapter { @@ -143,13 +147,16 @@ public final class FastDatabaseValueCursor Value? { - if _done { + switch _state { + case .done: // make sure this instance never yields a value again, even if the // statement is reset by another cursor. return nil + case .idle: + guard try _statement.database.statementWillExecute(_statement) == nil else { + throw DatabaseError( + resultCode: SQLITE_MISUSE, + message: "Can't run statement that requires a customized authorizer from a cursor", + sql: _statement.sql, + arguments: _statement.arguments) + } + _state = .busy + default: + break } + switch sqlite3_step(_sqliteStatement) { case SQLITE_DONE: - _done = true + _state = .done + try _statement.database.statementDidExecute(_statement) return nil case SQLITE_ROW: // TODO GRDB6: don't crash on decoding errors @@ -173,7 +194,8 @@ public final class FastDatabaseValueCursor: Cursor where Value: DatabaseValueConvertible & StatementColumnConvertible { - @usableFromInline let _statement: SelectStatement + @usableFromInline enum _State { + case idle, busy, done, failed + } + + @usableFromInline let _statement: Statement @usableFromInline let _columnIndex: Int32 @usableFromInline let _sqliteStatement: SQLiteStatement - @usableFromInline var _done = false + @usableFromInline var _state = _State.idle - init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { _statement = statement _sqliteStatement = statement.sqliteStatement if let adapter = adapter { @@ -205,13 +231,16 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible } else { _columnIndex = 0 } - _statement.reset(withArguments: arguments) - // Assume cursor is created for iteration - try statement.database.selectStatementWillExecute(statement) + // Assume cursor is created for immediate iteration: reset and set arguments + statement.reset(withArguments: arguments) } deinit { + if _state == .busy { + try? _statement.database.statementDidExecute(_statement) + } + // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. try? _statement.reset() @@ -219,14 +248,28 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible @inlinable public func next() throws -> Value?? { - if _done { + switch _state { + case .done: // make sure this instance never yields a value again, even if the // statement is reset by another cursor. return nil + case .idle: + guard try _statement.database.statementWillExecute(_statement) == nil else { + throw DatabaseError( + resultCode: SQLITE_MISUSE, + message: "Can't run statement that requires a customized authorizer from a cursor", + sql: _statement.sql, + arguments: _statement.arguments) + } + _state = .busy + default: + break } + switch sqlite3_step(_sqliteStatement) { case SQLITE_DONE: - _done = true + _state = .done + try _statement.database.statementDidExecute(_statement) return nil case SQLITE_ROW: // TODO GRDB6: don't crash on decoding errors @@ -235,7 +278,8 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible atUncheckedIndex: _columnIndex, context: RowDecodingContext(statement: _statement, index: Int(_columnIndex))) case let code: - try _statement.didFail(withResultCode: code) + _state = .failed + try _statement.database.statementDidFail(_statement, withResultCode: code) } } } @@ -247,11 +291,11 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible /// See DatabaseValueConvertible for more information. extension DatabaseValueConvertible where Self: StatementColumnConvertible { - // MARK: Fetching From SelectStatement + // MARK: Fetching From Prepared Statement /// Returns a cursor over values fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let names = try String.fetchCursor(statement) // Cursor of String /// while let name = try names.next() { // String /// ... @@ -269,7 +313,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( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor @@ -279,7 +323,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns an array of values fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let names = try String.fetchAll(statement) // [String] /// /// - parameters: @@ -289,7 +333,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( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] @@ -299,7 +343,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns a single value fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let name = try String.fetchOne(statement) // String? /// /// - parameters: @@ -309,7 +353,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? @@ -326,7 +370,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hashable { /// Returns a set of values fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let names = try String.fetchSet(statement) // Set /// /// - parameters: @@ -336,7 +380,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash /// - returns: A set of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchSet( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Set @@ -593,18 +637,18 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// try Optional.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String? /// try Optional.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String?] /// -/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") +/// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// try Optional.fetchCursor(statement, arguments:...) // Cursor of String? /// try Optional.fetchAll(statement, arguments:...) // [String?] /// /// DatabaseValueConvertible is adopted by Bool, Int, String, etc. extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible { - // MARK: Fetching From SelectStatement + // MARK: Fetching From Prepared Statement /// Returns a cursor over optional values fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let names = try Optional.fetchCursor(statement) // Cursor of String? /// while let name = try names.next() { // String? /// ... @@ -622,7 +666,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( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor @@ -632,7 +676,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// Returns an array of optional values fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let names = try Optional.fetchAll(statement) // [String?] /// /// - parameters: @@ -642,7 +686,7 @@ 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( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] @@ -654,7 +698,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable { /// Returns a set of optional values fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...") + /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") /// let names = try Optional.fetchSet(statement) // Set /// /// - parameters: @@ -664,7 +708,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - returns: A set of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchSet( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Set diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index 54fa319b2..eb37b2612 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -26,7 +26,7 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible { return data case .string(let string): // Implicit conversion from string to blob, just as SQLite does - // See https://www.sqlite.org/c3ref/column_blob.html + // See return string.data(using: .utf8) default: return nil diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift index e9ed49e80..b65e64a34 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift @@ -1,3 +1,5 @@ +import Foundation + private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { let dbValue: DatabaseValue let codingPath: [CodingKey] @@ -155,15 +157,13 @@ private struct DatabaseValueDecoder: Decoder { var userInfo: [CodingUserInfoKey: Any] { [:] } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { - throw DecodingError.typeMismatch( - type, - DecodingError.Context(codingPath: codingPath, debugDescription: "keyed decoding is not supported")) + // We need to switch to JSON decoding + throw JSONRequiredError() } func unkeyedContainer() throws -> UnkeyedDecodingContainer { - throw DecodingError.typeMismatch( - UnkeyedDecodingContainer.self, - DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported")) + // We need to switch to JSON decoding + throw JSONRequiredError() } func singleValueContainer() throws -> SingleValueDecodingContainer { @@ -173,7 +173,20 @@ private struct DatabaseValueDecoder: Decoder { extension DatabaseValueConvertible where Self: Decodable { public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? { - try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: [])) + do { + return try self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: [])) + } catch is JSONRequiredError { + guard let data = Data.fromDatabaseValue(databaseValue) else { + return nil + } + let decoder = JSONDecoder() + decoder.dataDecodingStrategy = .base64 + decoder.dateDecodingStrategy = .millisecondsSince1970 + decoder.nonConformingFloatDecodingStrategy = .throw + return try? decoder.decode(Self.self, from: data) + } catch { + return nil + } } } diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift index 42d73482c..5682ca7c9 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift @@ -1,3 +1,5 @@ +import Foundation + private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { let encode: (DatabaseValue) -> Void @@ -40,13 +42,18 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { // This allows us to encode Date as String, for example. encode(dbValueConvertible.databaseValue) } else { - try value.encode(to: DatabaseValueEncoder(encode: encode)) + try DatabaseValueEncoder(encode: encode).encode(value) } } } -private struct DatabaseValueEncoder: Encoder { +private class DatabaseValueEncoder: Encoder { let encode: (DatabaseValue) -> Void + var requiresJSON = false + + init(encode: @escaping (DatabaseValue) -> Void) { + self.encode = encode + } /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. @@ -63,7 +70,14 @@ private struct DatabaseValueEncoder: Encoder { /// - precondition: May not be called after a value has been encoded through /// a previous `self.singleValueContainer()` call. func container(keyedBy type: Key.Type) -> KeyedEncodingContainer { - fatalError("keyed encoding is not supported") + // We need to perform JSON encoding. Unfortunately we can't access the + // inner container of Foundation's JSONEncoder. At this point we must + // throw an error so that the caller can retry encoding from scratch. + // Unfortunately (bis), we can't throw right from here, so let's + // return a JSONRequiredEncoder that will throw as soon as possible. + requiresJSON = true + let container = JSONRequiredEncoder.KeyedContainer(codingPath: codingPath) + return KeyedEncodingContainer(container) } /// Returns an encoding container appropriate for holding multiple unkeyed values. @@ -73,7 +87,13 @@ private struct DatabaseValueEncoder: Encoder { /// - precondition: May not be called after a value has been encoded through /// a previous `self.singleValueContainer()` call. func unkeyedContainer() -> UnkeyedEncodingContainer { - fatalError("unkeyed encoding is not supported") + // We need to perform JSON encoding. Unfortunately we can't access the + // inner container of Foundation's JSONEncoder. At this point we must + // throw an error so that the caller can retry encoding from scratch. + // Unfortunately (bis), we can't throw right from here, so let's + // return a JSONRequiredEncoder that will throw as soon as possible. + requiresJSON = true + return JSONRequiredEncoder(codingPath: codingPath) } /// Returns an encoding container appropriate for holding a single primitive value. @@ -86,13 +106,41 @@ private struct DatabaseValueEncoder: Encoder { func singleValueContainer() -> SingleValueEncodingContainer { DatabaseValueEncodingContainer(encode: encode) } + + func encode(_ value: T) throws { + do { + try value.encode(to: self) + if requiresJSON { + // Here we handle empty arrays and dictionaries. + throw JSONRequiredError() + } + } catch is JSONRequiredError { + let encoder = JSONEncoder() + encoder.dataEncodingStrategy = .base64 + encoder.dateEncodingStrategy = .millisecondsSince1970 + encoder.nonConformingFloatEncodingStrategy = .throw + if #available(watchOS 4.0, OSX 10.13, iOS 11.0, tvOS 11.0, *) { + // guarantee some stability in order to ease value comparison + encoder.outputFormatting = .sortedKeys + } + let jsonData = try encoder.encode(value) + + // Store JSON String in the database for easier debugging and + // database inspection. Thanks to SQLite weak typing, we won't + // have any trouble decoding this string into data when we + // eventually perform JSON decoding. + // TODO: possible optimization: avoid this conversion to string, + // and store raw data bytes as an SQLite string + let jsonString = String(data: jsonData, encoding: .utf8)! + try jsonString.encode(to: self) + } + } } extension DatabaseValueConvertible where Self: Encodable { public var databaseValue: DatabaseValue { var dbValue: DatabaseValue! = nil - let encoder = DatabaseValueEncoder(encode: { dbValue = $0 }) - try! self.encode(to: encoder) + try! DatabaseValueEncoder(encode: { dbValue = $0 }).encode(self) return dbValue } } diff --git a/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift b/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift new file mode 100644 index 000000000..8ab622a19 --- /dev/null +++ b/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift @@ -0,0 +1,97 @@ +struct JSONRequiredError: Error { } + +/// The encoder that always ends up with a JSONRequiredError +struct JSONRequiredEncoder: Encoder { + var codingPath: [CodingKey] + var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } + + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { + let container = KeyedContainer(codingPath: codingPath) + return KeyedEncodingContainer(container) + } + + func unkeyedContainer() -> UnkeyedEncodingContainer { self } + + func singleValueContainer() -> SingleValueEncodingContainer { self } + + struct KeyedContainer: KeyedEncodingContainerProtocol { + var codingPath: [CodingKey] + var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } + + // swiftlint:disable comma + func encodeNil(forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: Bool, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: Int, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: Int8, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: Int16, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: Int32, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: Int64, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: UInt, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: UInt8, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: UInt16, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: UInt32, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: UInt64, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() } + func encode(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() } + // swiftlint:enable comma + + func nestedContainer( + keyedBy keyType: NestedKey.Type, + forKey key: KeyType) + -> KeyedEncodingContainer + where NestedKey: CodingKey + { + let container = KeyedContainer(codingPath: codingPath + [key]) + return KeyedEncodingContainer(container) + } + + func nestedUnkeyedContainer(forKey key: KeyType) -> UnkeyedEncodingContainer { + JSONRequiredEncoder(codingPath: codingPath) + } + + func superEncoder() -> Encoder { + JSONRequiredEncoder(codingPath: codingPath) + } + + func superEncoder(forKey key: KeyType) -> Encoder { + JSONRequiredEncoder(codingPath: codingPath) + } + } +} + +extension JSONRequiredEncoder: SingleValueEncodingContainer { + func encodeNil() throws { throw JSONRequiredError() } + func encode(_ value: Bool ) throws { throw JSONRequiredError() } + func encode(_ value: Int ) throws { throw JSONRequiredError() } + func encode(_ value: Int8 ) throws { throw JSONRequiredError() } + func encode(_ value: Int16 ) throws { throw JSONRequiredError() } + func encode(_ value: Int32 ) throws { throw JSONRequiredError() } + func encode(_ value: Int64 ) throws { throw JSONRequiredError() } + func encode(_ value: UInt ) throws { throw JSONRequiredError() } + func encode(_ value: UInt8 ) throws { throw JSONRequiredError() } + func encode(_ value: UInt16) throws { throw JSONRequiredError() } + func encode(_ value: UInt32) throws { throw JSONRequiredError() } + func encode(_ value: UInt64) throws { throw JSONRequiredError() } + func encode(_ value: Float ) throws { throw JSONRequiredError() } + func encode(_ value: Double) throws { throw JSONRequiredError() } + func encode(_ value: String) throws { throw JSONRequiredError() } + func encode(_ value: T) throws where T: Encodable { throw JSONRequiredError() } +} + +extension JSONRequiredEncoder: UnkeyedEncodingContainer { + var count: Int { 0 } + + mutating func nestedContainer(keyedBy keyType: NestedKey.Type) + -> KeyedEncodingContainer + where NestedKey: CodingKey + { + let container = KeyedContainer(codingPath: codingPath) + return KeyedEncodingContainer(container) + } + + mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self } + + mutating func superEncoder() -> Encoder { self } +} diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index e0faf23ac..3a0aab73f 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -518,7 +518,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible { switch dbValue.storage { case .blob(let data): // Implicit conversion from blob to string, just as SQLite does - // See https://www.sqlite.org/c3ref/column_blob.html + // See return String(data: data, encoding: .utf8) case .string(let string): return string diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 1529f7b3e..129c55153 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -164,7 +164,7 @@ class DatabaseObservationBroker { private var statementObservations: [StatementObservation] = [] { didSet { observesDatabaseChanges = !statementObservations.isEmpty } } - private var observesDatabaseChanges: Bool = false { + private var observesDatabaseChanges = false { didSet { if observesDatabaseChanges == oldValue { return } if observesDatabaseChanges { @@ -200,8 +200,9 @@ class DatabaseObservationBroker { /// Setups observation of changes that are about to be performed by the /// statement, and returns the authorizer that should be used during - /// statement execution. - func updateStatementWillExecute(_ statement: UpdateStatement) -> StatementAuthorizer? { + /// statement execution (this allows preventing the truncate optimization + /// when there exists a transaction observer for row deletion). + func statementWillExecute(_ statement: Statement) -> StatementAuthorizer? { // If any observer observes row deletions, we'll have to disable // [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt) // so that observers are notified. @@ -285,16 +286,7 @@ class DatabaseObservationBroker { } } - switch transactionState { - case .none: - break - default: - // May happen after "PRAGMA journal_mode = WAL" executed with a - // SelectStatement. - // TODO: Maybe this state machine should be run for *all* statements, - // not ony update statements. - transactionState = .none - } + transactionState = .none if observesRowDeletion { return TruncateOptimizationBlocker() @@ -303,8 +295,10 @@ class DatabaseObservationBroker { } } - func updateStatementDidFail(_ statement: UpdateStatement) throws { - // Undo updateStatementWillExecute + /// May throw a cancelled commit error, if a transaction observer cancels + /// a transaction. + func statementDidFail(_ statement: Statement) throws { + // Undo statementWillExecute statementObservations = [] SchedulingWatchdog.current!.databaseObservationBroker = nil @@ -327,8 +321,10 @@ class DatabaseObservationBroker { } } - func updateStatementDidExecute(_ statement: UpdateStatement) throws { - // Undo updateStatementWillExecute + /// May throw a cancelled commit error, if a transaction observer cancels + /// an empty transaction. + func statementDidExecute(_ statement: Statement) throws { + // Undo statementWillExecute if transactionObservations.isEmpty == false { statementObservations = [] SchedulingWatchdog.current!.databaseObservationBroker = nil @@ -443,7 +439,7 @@ class DatabaseObservationBroker { } } - // Called from updateStatementDidExecute + // Called from statementDidExecute private func databaseDidCommit() { savepointStack.clear() @@ -453,7 +449,9 @@ class DatabaseObservationBroker { databaseDidEndTransaction() } - // Called from updateStatementDidExecute + // Called from statementDidExecute + /// May throw a cancelled commit error, if a transaction observer cancels + /// the empty transaction. private func databaseDidCommitEmptyDeferredTransaction() throws { // A statement that ends a transaction has been executed. But for // SQLite, no transaction at all has started, and sqlite3_commit_hook @@ -496,7 +494,7 @@ class DatabaseObservationBroker { } } - // Called from updateStatementDidExecute or updateStatementDidFails + // Called from statementDidExecute or statementDidFail private func databaseDidRollback(notifyTransactionObservers: Bool) { savepointStack.clear() @@ -531,7 +529,7 @@ class DatabaseObservationBroker { // // Normally, notifyBufferedEvents() is called as part of statement // execution, and the current broker has been set in - // updateStatementWillExecute(). An assertion should be enough: + // statementWillExecute(). An assertion should be enough: // // assert(SchedulingWatchdog.current?.databaseObservationBroker != nil) // @@ -539,10 +537,8 @@ class DatabaseObservationBroker { // // let journalMode = String.fetchOne(db, sql: "PRAGMA journal_mode = wal") // - // It runs a SelectStatement, not an UpdateStatement. But this not why - // this case is particular. What is unexpected is that it triggers - // the commit hook when the "PRAGMA journal_mode = wal" statement is - // finalized, long after it has executed: + // It triggers the commit hook when the "PRAGMA journal_mode = wal" + // statement is finalized, long after it has executed: // // 1. Statement.deinit() // 2. sqlite3_finalize() @@ -555,7 +551,7 @@ class DatabaseObservationBroker { // journal mode would trigger the commit hook in sqlite3_step(), // not in sqlite3_finalize(). // - // Anyway: in this scenario, updateStatementWillExecute() has not been + // Anyway: in this scenario, statementWillExecute() has not been // called, and the current broker is nil. // // Let's not try to outsmart SQLite, and build a complex state machine. @@ -590,7 +586,7 @@ class DatabaseObservationBroker { do { try broker.databaseWillCommit() broker.transactionState = .commit - // Next step: updateStatementDidExecute() + // Next step: statementDidExecute() return 0 } catch { broker.transactionState = .cancelledCommit(error) @@ -603,11 +599,11 @@ class DatabaseObservationBroker { let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() switch broker.transactionState { case .cancelledCommit: - // Next step: updateStatementDidFail() + // Next step: statementDidFail() break default: broker.transactionState = .rollback - // Next step: updateStatementDidExecute() + // Next step: statementDidExecute() } }, brokerPointer) } @@ -741,7 +737,7 @@ public protocol TransactionObserver: AnyObject { /// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library /// does not have this enabled, so you'll need to compile your own /// version of SQLite: - /// See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md + /// See /// /// The databaseDidChangeWithEvent callback is always available, /// and may provide most/all of what you need. @@ -800,7 +796,7 @@ final class TransactionObservation { // A disabled observation is not interested in individual database changes. // It is still interested in transactions commits & rollbacks. - var isDisabled: Bool = false + var isDisabled = false private weak var weakObserver: TransactionObserver? private var strongObserver: TransactionObserver? @@ -1350,7 +1346,7 @@ enum DatabaseEventPredicate { // MARK: - SavepointStack /// The SQLite savepoint stack is described at -/// https://www.sqlite.org/lang_savepoint.html +/// /// /// This class reimplements the SQLite stack, so that we can: /// diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index 536e2c9b5..66bdc12cf 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -8,7 +8,7 @@ public struct FTS3: VirtualTableModule { /// Options for Latin script characters. Matches the raw "remove_diacritics" /// tokenizer argument. /// - /// See https://www.sqlite.org/fts3.html + /// See public enum Diacritics { /// Do not remove diacritics from Latin script characters. This /// option matches the raw "remove_diacritics=0" tokenizer argument. @@ -45,10 +45,18 @@ public struct FTS3: VirtualTableModule { /// The virtual table module name public let moduleName = "fts3" + // TODO: remove when `makeTableDefinition()` is no longer a requirement /// Reserved; part of the VirtualTableModule protocol. /// /// See Database.create(virtualTable:using:) public func makeTableDefinition() -> FTS3TableDefinition { + preconditionFailure() + } + + /// Reserved; part of the VirtualTableModule protocol. + /// + /// See Database.create(virtualTable:using:) + public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS3TableDefinition { FTS3TableDefinition() } @@ -93,7 +101,7 @@ public final class FTS3TableDefinition { /// try db.create(virtualTable: "document", using: FTS3()) { t in /// t.tokenizer = .porter /// } - /// See https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables + /// See public var tokenizer: FTS3TokenizerDescriptor? /// Appends a table column. diff --git a/GRDB/FTS/FTS3Pattern.swift b/GRDB/FTS/FTS3Pattern.swift index 8fffdbf2e..f07bf0626 100644 --- a/GRDB/FTS/FTS3Pattern.swift +++ b/GRDB/FTS/FTS3Pattern.swift @@ -7,7 +7,7 @@ public struct FTS3Pattern { /// Creates a pattern from a raw pattern string; throws DatabaseError on /// invalid syntax. /// - /// The pattern syntax is documented at https://www.sqlite.org/fts3.html#full_text_index_queries + /// The pattern syntax is documented at /// /// try FTS3Pattern(rawPattern: "and") // OK /// try FTS3Pattern(rawPattern: "AND") // malformed MATCH expression: [AND] diff --git a/GRDB/FTS/FTS3TokenizerDescriptor.swift b/GRDB/FTS/FTS3TokenizerDescriptor.swift index d647654f6..5c2363fee 100644 --- a/GRDB/FTS/FTS3TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS3TokenizerDescriptor.swift @@ -4,7 +4,7 @@ /// t.tokenizer = .simple // FTS3TokenizerDescriptor /// } /// -/// See https://www.sqlite.org/fts3.html#tokenizer +/// See public struct FTS3TokenizerDescriptor { let name: String let arguments: [String] @@ -20,7 +20,7 @@ public struct FTS3TokenizerDescriptor { /// t.tokenizer = .simple /// } /// - /// See https://www.sqlite.org/fts3.html#tokenizer + /// See public static let simple = FTS3TokenizerDescriptor("simple") /// The "porter" tokenizer. @@ -29,7 +29,7 @@ public struct FTS3TokenizerDescriptor { /// t.tokenizer = .porter /// } /// - /// See https://www.sqlite.org/fts3.html#tokenizer + /// See public static let porter = FTS3TokenizerDescriptor("porter") /// The "unicode61" tokenizer. @@ -46,7 +46,7 @@ public struct FTS3TokenizerDescriptor { /// - tokenCharacters: Unless empty (the default), SQLite will consider /// these characters as token characters. /// - /// See https://www.sqlite.org/fts3.html#tokenizer + /// See public static func unicode61( diacritics: FTS3.Diacritics = .removeLegacy, separators: Set = [], diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index 71b45c50f..6166bfad5 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -5,7 +5,7 @@ /// t.column("content") /// } /// -/// See https://www.sqlite.org/fts3.html +/// See public struct FTS4: VirtualTableModule { /// Creates a FTS4 module suitable for the Database @@ -16,7 +16,7 @@ public struct FTS4: VirtualTableModule { /// t.column("content") /// } /// - /// See https://www.sqlite.org/fts3.html + /// See public init() { } @@ -25,11 +25,19 @@ public struct FTS4: VirtualTableModule { /// The virtual table module name public let moduleName = "fts4" + // TODO: remove when `makeTableDefinition()` is no longer a requirement /// Reserved; part of the VirtualTableModule protocol. /// /// See Database.create(virtualTable:using:) public func makeTableDefinition() -> FTS4TableDefinition { - FTS4TableDefinition() + preconditionFailure() + } + + /// Reserved; part of the VirtualTableModule protocol. + /// + /// See Database.create(virtualTable:using:) + public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS4TableDefinition { + FTS4TableDefinition(configuration: configuration) } /// Reserved; part of the VirtualTableModule protocol. @@ -113,20 +121,26 @@ public struct FTS4: VirtualTableModule { let oldRowID = "old.\(rowIDColumn.quotedDatabaseIdentifier)" + let ifNotExists = definition.configuration.ifNotExists + ? "IF NOT EXISTS " + : "" + + // swiftlint:disable line_length try db.execute(sql: """ - CREATE TRIGGER \("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN + CREATE TRIGGER \(ifNotExists)\("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); END; - CREATE TRIGGER \("__\(tableName)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN + CREATE TRIGGER \(ifNotExists)\("__\(tableName)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); END; - CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN + CREATE TRIGGER \(ifNotExists)\("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); END; - CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN + CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); END; """) + // swiftlint:enable line_length // https://www.sqlite.org/fts3.html#*fts4rebuidcmd @@ -144,13 +158,14 @@ public struct FTS4: VirtualTableModule { /// t.column("content") /// } /// -/// See https://www.sqlite.org/fts3.html +/// See public final class FTS4TableDefinition { enum ContentMode { case raw(content: String?) case synchronized(contentTable: String) } + fileprivate let configuration: VirtualTableConfiguration fileprivate var columns: [FTS4ColumnDefinition] = [] fileprivate var contentMode: ContentMode = .raw(content: nil) @@ -160,7 +175,7 @@ public final class FTS4TableDefinition { /// t.tokenizer = .porter /// } /// - /// See https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables + /// See public var tokenizer: FTS3TokenizerDescriptor? /// The FTS4 `content` option @@ -172,7 +187,7 @@ public final class FTS4TableDefinition { /// Setting this property invalidates any synchronization previously /// established with the `synchronize(withTable:)` method. /// - /// See https://www.sqlite.org/fts3.html#the_content_option_ + /// See public var content: String? { get { switch contentMode { @@ -189,17 +204,17 @@ public final class FTS4TableDefinition { /// The FTS4 `compress` option /// - /// See https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options + /// See public var compress: String? /// The FTS4 `uncompress` option /// - /// See https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options + /// See public var uncompress: String? /// The FTS4 `matchinfo` option /// - /// See https://www.sqlite.org/fts3.html#the_matchinfo_option + /// See public var matchinfo: String? /// Support for the FTS5 `prefix` option @@ -210,9 +225,13 @@ public final class FTS4TableDefinition { /// t.column("content") /// } /// - /// See https://www.sqlite.org/fts3.html#the_prefix_option + /// See public var prefixes: Set? + init(configuration: VirtualTableConfiguration) { + self.configuration = configuration + } + /// Appends a table column. /// /// try db.create(virtualTable: "document", using: FTS4()) { t in @@ -234,7 +253,7 @@ public final class FTS4TableDefinition { /// content in the external table. SQL triggers make sure that the /// full-text table is kept up to date with the external table. /// - /// See https://sqlite.org/fts5.html#external_content_tables + /// See public func synchronize(withTable tableName: String) { contentMode = .synchronized(contentTable: tableName) } @@ -249,7 +268,7 @@ public final class FTS4TableDefinition { /// t.column("content") // FTS4ColumnDefinition /// } /// -/// See https://www.sqlite.org/fts3.html +/// See public final class FTS4ColumnDefinition { fileprivate let name: String fileprivate var isIndexed: Bool @@ -268,7 +287,7 @@ public final class FTS4ColumnDefinition { /// t.column("b").notIndexed() /// } /// - /// See https://www.sqlite.org/fts3.html#the_notindexed_option + /// See /// /// - returns: Self so that you can further refine the column definition. @discardableResult @@ -284,7 +303,7 @@ public final class FTS4ColumnDefinition { /// t.column("lid").asLanguageId() /// } /// - /// See https://www.sqlite.org/fts3.html#the_languageid_option + /// See /// /// - returns: Self so that you can further refine the column definition. @discardableResult diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 9abef7a2f..b707c66cf 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -8,12 +8,12 @@ import Foundation /// t.column("content") /// } /// -/// See https://www.sqlite.org/fts5.html +/// See public struct FTS5: VirtualTableModule { /// Options for Latin script characters. Matches the raw "remove_diacritics" /// tokenizer argument. /// - /// See https://www.sqlite.org/fts5.html + /// See public enum Diacritics { /// Do not remove diacritics from Latin script characters. This /// option matches the raw "remove_diacritics=0" tokenizer argument. @@ -43,7 +43,7 @@ public struct FTS5: VirtualTableModule { /// t.column("content") /// } /// - /// See https://www.sqlite.org/fts5.html + /// See public init() { } @@ -52,9 +52,19 @@ public struct FTS5: VirtualTableModule { /// The virtual table module name public let moduleName = "fts5" - /// Don't use this method. + // TODO: remove when `makeTableDefinition()` is no longer a requirement + /// Reserved; part of the VirtualTableModule protocol. + /// + /// See Database.create(virtualTable:using:) public func makeTableDefinition() -> FTS5TableDefinition { - FTS5TableDefinition() + preconditionFailure() + } + + /// Reserved; part of the VirtualTableModule protocol. + /// + /// See Database.create(virtualTable:using:) + public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS5TableDefinition { + FTS5TableDefinition(configuration: configuration) } /// Don't use this method. @@ -150,18 +160,24 @@ public struct FTS5: VirtualTableModule { .map { "old.\($0.quotedDatabaseIdentifier)" } .joined(separator: ", ") + let ifNotExists = definition.configuration.ifNotExists + ? "IF NOT EXISTS " + : "" + + // swiftlint:disable line_length try db.execute(sql: """ - CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN + CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); END; - CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN + CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); END; - CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN + CREATE TRIGGER \(ifNotExists)\("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); END; """) + // swiftlint:enable line_length // https://sqlite.org/fts5.html#the_rebuild_command @@ -243,13 +259,14 @@ public struct FTS5: VirtualTableModule { /// t.column("content") /// } /// -/// See https://www.sqlite.org/fts5.html +/// See public final class FTS5TableDefinition { enum ContentMode { case raw(content: String?, contentRowID: String?) case synchronized(contentTable: String) } + fileprivate let configuration: VirtualTableConfiguration fileprivate var columns: [FTS5ColumnDefinition] = [] fileprivate var contentMode: ContentMode = .raw(content: nil, contentRowID: nil) @@ -259,7 +276,7 @@ public final class FTS5TableDefinition { /// t.tokenizer = .porter() /// } /// - /// See https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization + /// See public var tokenizer: FTS5TokenizerDescriptor? /// The FTS5 `content` option @@ -271,7 +288,7 @@ public final class FTS5TableDefinition { /// Setting this property invalidates any synchronization previously /// established with the `synchronize(withTable:)` method. /// - /// See https://www.sqlite.org/fts5.html#external_content_and_contentless_tables + /// See public var content: String? { get { switch contentMode { @@ -300,7 +317,7 @@ public final class FTS5TableDefinition { /// Setting this property invalidates any synchronization previously /// established with the `synchronize(withTable:)` method. /// - /// See https://sqlite.org/fts5.html#external_content_tables + /// See public var contentRowID: String? { get { switch contentMode { @@ -322,19 +339,23 @@ public final class FTS5TableDefinition { /// Support for the FTS5 `prefix` option /// - /// See https://www.sqlite.org/fts5.html#prefix_indexes + /// See public var prefixes: Set? /// Support for the FTS5 `columnsize` option /// - /// https://www.sqlite.org/fts5.html#the_columnsize_option + /// public var columnSize: Int? /// Support for the FTS5 `detail` option /// - /// https://www.sqlite.org/fts5.html#the_detail_option + /// public var detail: String? + init(configuration: VirtualTableConfiguration) { + self.configuration = configuration + } + /// Appends a table column. /// /// try db.create(virtualTable: "document", using: FTS5()) { t in @@ -356,7 +377,7 @@ public final class FTS5TableDefinition { /// content in the external table. SQL triggers make sure that the /// full-text table is kept up to date with the external table. /// - /// See https://sqlite.org/fts5.html#external_content_tables + /// See public func synchronize(withTable tableName: String) { contentMode = .synchronized(contentTable: tableName) } @@ -371,7 +392,7 @@ public final class FTS5TableDefinition { /// t.column("content") // FTS5ColumnDefinition /// } /// -/// See https://www.sqlite.org/fts5.html +/// See public final class FTS5ColumnDefinition { fileprivate let name: String fileprivate var isIndexed: Bool @@ -388,7 +409,7 @@ public final class FTS5ColumnDefinition { /// t.column("b").notIndexed() /// } /// - /// See https://www.sqlite.org/fts5.html#the_unindexed_column_option + /// See /// /// - returns: Self so that you can further refine the column definition. @discardableResult diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index 86f90b7f7..6b0a9becd 100644 --- a/GRDB/FTS/FTS5Pattern.swift +++ b/GRDB/FTS/FTS5Pattern.swift @@ -93,7 +93,7 @@ public struct FTS5Pattern { } } } - try db.makeSelectStatement(sql: "SELECT * FROM document WHERE document MATCH ?") + try db.makeStatement(sql: "SELECT * FROM document WHERE document MATCH ?") .makeCursor(arguments: [rawPattern]) .next() // error on next() for invalid patterns } @@ -114,7 +114,7 @@ extension Database { /// Creates a pattern from a raw pattern string; throws DatabaseError on /// invalid syntax. /// - /// The pattern syntax is documented at https://www.sqlite.org/fts5.html#full_text_query_syntax + /// The pattern syntax is documented at /// /// try db.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK /// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND] diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index dbb279bd7..fd94116fe 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -15,7 +15,7 @@ public typealias FTS5TokenCallback = @convention(c) ( /// The reason why FTS5 is requesting tokenization. /// -/// See https://www.sqlite.org/fts5.html#custom_tokenizers +/// See public struct FTS5Tokenization: OptionSet { public let rawValue: Int32 @@ -41,7 +41,7 @@ public protocol FTS5Tokenizer: AnyObject { /// Tokenizes the text described by `pText` and `nText`, and /// notifies found tokens to the `tokenCallback` function. /// - /// It matches the `xTokenize` function documented at https://www.sqlite.org/fts5.html#custom_tokenizers + /// It matches the `xTokenize` function documented at /// /// - parameters: /// - context: An opaque pointer that is the first argument to @@ -51,7 +51,7 @@ public protocol FTS5Tokenizer: AnyObject { /// nul-terminated. /// - nText: The number of bytes in the tokenized text. /// - tokenCallback: The function to call for each found token. - /// It matches the `xToken` callback at https://www.sqlite.org/fts5.html#custom_tokenizers + /// It matches the `xToken` callback at func tokenize( context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, diff --git a/GRDB/FTS/FTS5TokenizerDescriptor.swift b/GRDB/FTS/FTS5TokenizerDescriptor.swift index 3f30c88d2..996c9fdfa 100644 --- a/GRDB/FTS/FTS5TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS5TokenizerDescriptor.swift @@ -5,7 +5,7 @@ /// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor /// } /// -/// See https://www.sqlite.org/fts5.html#tokenizers +/// See public struct FTS5TokenizerDescriptor { /// The tokenizer components /// @@ -55,7 +55,7 @@ public struct FTS5TokenizerDescriptor { /// - tokenCharacters: Unless empty (the default), SQLite will /// consider these characters as token characters. /// - /// See https://www.sqlite.org/fts5.html#ascii_tokenizer + /// See public static func ascii( separators: Set = [], tokenCharacters: Set = []) @@ -108,7 +108,7 @@ public struct FTS5TokenizerDescriptor { /// - base: An eventual wrapping tokenizer which replaces the // default unicode61() base tokenizer. /// - /// See https://www.sqlite.org/fts5.html#porter_tokenizer + /// See public static func porter(wrapping base: FTS5TokenizerDescriptor? = nil) -> FTS5TokenizerDescriptor { if let base = base { return FTS5TokenizerDescriptor(components: ["porter"] + base.components) @@ -131,7 +131,7 @@ public struct FTS5TokenizerDescriptor { /// - tokenCharacters: Unless empty (the default), SQLite will /// consider these characters as token characters. /// - /// See https://www.sqlite.org/fts5.html#unicode61_tokenizer + /// See public static func unicode61( diacritics: FTS5.Diacritics = .removeLegacy, separators: Set = [], diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index d3d73392c..9c9093de6 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -3,7 +3,7 @@ import Foundation /// Flags that tell SQLite how to register a token. /// -/// See https://www.sqlite.org/fts5.html#custom_tokenizers +/// See public struct FTS5TokenFlags: OptionSet { public let rawValue: Int32 @@ -76,7 +76,7 @@ public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer { /// 2. The input `flags` should be given unmodified to the tokenCallback /// function, unless you union it with the .colocated flag when the /// tokenizer produces synonyms (see - /// https://www.sqlite.org/fts5.html#synonym_support). + /// ). /// /// - parameters: /// - token: A token produced by the wrapped tokenizer diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index 8dd012d77..3e51a7177 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -15,7 +15,7 @@ extension AnyFetchRequest { { preconditionFailure() } @available(*, unavailable, message: "Define your own FetchRequest type instead.") - public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?)) + public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (Statement, RowAdapter?)) { preconditionFailure() } } @@ -129,7 +129,7 @@ extension DatabaseReader { extension FetchRequest { @available(*, unavailable, message: "Use makePreparedRequest(_:forSingleResult:) instead.") - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) + func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (Statement, RowAdapter?) { preconditionFailure() } @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchCount) instead") diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index c4cdccfe4..7550cf407 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -39,7 +39,7 @@ struct Migration { // > schema change did not break any foreign // > key constraints. if try db - .makeSelectStatement(sql: "PRAGMA foreign_key_check") + .makeStatement(sql: "PRAGMA foreign_key_check") .makeCursor() .isEmpty() == false { diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index c82824bab..c6714f9c9 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -4,8 +4,7 @@ import Foundation /// /// :nodoc: public protocol _Association { - init(sqlAssociation: _SQLAssociation) - var _sqlAssociation: _SQLAssociation { get } + var _sqlAssociation: _SQLAssociation { get set } } /// The base protocol for all associations that define a connection between two @@ -45,35 +44,57 @@ public protocol Association: _Association, DerivableRequest { } extension Association { - /// :nodoc: - public func _including(all association: _SQLAssociation) -> Self { - mapDestinationRelation { $0._including(all: association) } + /// Returns self modified with the *update* function. + @inline(__always) + func with(_ update: (inout Self) throws -> Void) rethrows -> Self { + var result = self + try update(&result) + return result } - /// :nodoc: - public func _including(optional association: _SQLAssociation) -> Self { - mapDestinationRelation { $0._including(optional: association) } - } - - /// :nodoc: - public func _including(required association: _SQLAssociation) -> Self { - mapDestinationRelation { $0._including(required: association) } - } - - /// :nodoc: - public func _joining(optional association: _SQLAssociation) -> Self { - mapDestinationRelation { $0._joining(optional: association) } - } - - /// :nodoc: - public func _joining(required association: _SQLAssociation) -> Self { - mapDestinationRelation { $0._joining(required: association) } + /// Returns self with destination relation modified with the *update* function. + @inline(__always) + fileprivate func withDestinationRelation(_ update: (inout SQLRelation) throws -> Void) rethrows -> Self { + var result = self + try update(&result._sqlAssociation.destination.relation) + return result } } extension Association { - fileprivate func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { - .init(sqlAssociation: _sqlAssociation.map(\.destination.relation, transform)) + /// :nodoc: + public func _including(all association: _SQLAssociation) -> Self { + withDestinationRelation { relation in + relation = relation._including(all: association) + } + } + + /// :nodoc: + public func _including(optional association: _SQLAssociation) -> Self { + withDestinationRelation { relation in + relation = relation._including(optional: association) + } + } + + /// :nodoc: + public func _including(required association: _SQLAssociation) -> Self { + withDestinationRelation { relation in + relation = relation._including(required: association) + } + } + + /// :nodoc: + public func _joining(optional association: _SQLAssociation) -> Self { + withDestinationRelation { relation in + relation = relation._joining(optional: association) + } + } + + /// :nodoc: + public func _joining(required association: _SQLAssociation) -> Self { + withDestinationRelation { relation in + relation = relation._joining(required: association) + } } } @@ -159,11 +180,14 @@ extension Association { /// .including(required: Player.team.aliased(teamAlias)) /// .filter(sql: "custom.color = ?", arguments: ["red"]) public func aliased(_ alias: TableAlias) -> Self { - mapDestinationRelation { $0.aliased(alias) } + withDestinationRelation { relation in + relation = relation.aliased(alias) + } } } -extension Association where Self: SelectionRequest { +// SelectionRequest conformance +extension Association { /// Creates an association which selects *selection*. /// @@ -187,7 +211,11 @@ extension Association where Self: SelectionRequest { /// .select { db in [Column("color") } /// var request = Player.including(required: association) public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { - mapDestinationRelation { $0.select { try selection($0).map(\.sqlSelection) } } + withDestinationRelation { relation in + relation = relation.select { db in + try selection(db).map(\.sqlSelection) + } + } } /// Creates an association which appends *selection*. @@ -204,11 +232,16 @@ extension Association where Self: SelectionRequest { /// .annotated(with: { db in [Column("name")] }) /// var request = Player.including(required: association) public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { - mapDestinationRelation { $0.annotated { try selection($0).map(\.sqlSelection) } } + withDestinationRelation { relation in + relation = relation.annotated { db in + try selection(db).map(\.sqlSelection) + } + } } } -extension Association where Self: FilteredRequest { +// FilteredRequest conformance +extension Association { /// Creates an association with the provided *predicate promise* added to /// the eventual set of already applied predicates. /// @@ -222,11 +255,16 @@ extension Association where Self: FilteredRequest { /// let association = Player.team.filter { db in true } /// var request = Player.including(required: association) public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - mapDestinationRelation { $0.filter { try predicate($0).sqlExpression } } + withDestinationRelation { relation in + relation = relation.filter { db in + try predicate(db).sqlExpression + } + } } } -extension Association where Self: OrderedRequest { +// OrderedRequest conformance +extension Association { /// Creates an association with the provided *orderings promise*. /// /// struct Player: TableRecord { @@ -252,7 +290,11 @@ extension Association where Self: OrderedRequest { /// .order{ _ in [Column("name")] } /// var request = Player.including(required: association) public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self { - mapDestinationRelation { $0.order { try orderings($0).map(\.sqlOrdering) } } + withDestinationRelation { relation in + relation = relation.order { db in + try orderings(db).map(\.sqlOrdering) + } + } } /// Creates an association that reverses applied orderings. @@ -276,7 +318,9 @@ extension Association where Self: OrderedRequest { /// let association = Player.team.reversed() /// var request = Player.including(required: association) public func reversed() -> Self { - mapDestinationRelation { $0.reversed() } + withDestinationRelation { relation in + relation = relation.reversed() + } } /// Creates an association without any ordering. @@ -291,33 +335,48 @@ extension Association where Self: OrderedRequest { /// let association = Player.team.order(Column("name")).unordered() /// var request = Player.including(required: association) public func unordered() -> Self { - mapDestinationRelation { $0.unordered() } + withDestinationRelation { relation in + relation = relation.unordered() + } } } -extension Association where Self: TableRequest { +// TableRequest conformance +extension Association { public var databaseTableName: String { _sqlAssociation.destination.relation.source.tableName } } -extension Association where Self: AggregatingRequest { +// AggregatingRequest conformance +extension Association { /// Creates an association grouped according to *expressions promise*. public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self { - mapDestinationRelation { $0.group { try expressions($0).map(\.sqlExpression) } } + withDestinationRelation { relation in + relation = relation.group { db in + try expressions(db).map(\.sqlExpression) + } + } } /// Creates an association with the provided *predicate promise* added to /// the eventual set of already applied predicates. public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - mapDestinationRelation { $0.having { try predicate($0).sqlExpression } } + withDestinationRelation { relation in + relation = relation.having { db in + try predicate(db).sqlExpression + } + } } } -extension Association where Self: DerivableRequest { +// DerivableRequest conformance +extension Association { /// Creates an association for returns distinct rows. public func distinct() -> Self { - mapDestinationRelation { $0.with(\.isDistinct, true) } + withDestinationRelation { relation in + relation.isDistinct = true + } } /// Creates an association that fetches *limit* rows, starting at *offset*. @@ -329,14 +388,18 @@ extension Association where Self: DerivableRequest { /// /// :nodoc: public func limit(_ limit: Int, offset: Int? = nil) -> Self { - mapDestinationRelation { $0.with(\.limit, SQLLimit(limit: limit, offset: offset)) } + withDestinationRelation { relation in + relation.limit = SQLLimit(limit: limit, offset: offset) + } } /// Returns an association that embeds the common table expression. /// /// See `QueryInterfaceRequest.with(_:)` for more information. public func with(_ cte: CommonTableExpression) -> Self { - mapDestinationRelation { $0.with(\.ctes[cte.tableName], cte.cte) } + withDestinationRelation { relation in + relation.ctes[cte.tableName] = cte.cte + } } } @@ -348,7 +411,9 @@ public protocol AssociationToOne: Association { } extension AssociationToOne { public func forKey(_ key: String) -> Self { let associationKey = SQLAssociationKey.fixedSingular(key) - return .init(sqlAssociation: _sqlAssociation.forDestinationKey(associationKey)) + return with { + $0._sqlAssociation = $0._sqlAssociation.forDestinationKey(associationKey) + } } } @@ -360,6 +425,8 @@ public protocol AssociationToMany: Association { } extension AssociationToMany { public func forKey(_ key: String) -> Self { let associationKey = SQLAssociationKey.fixedPlural(key) - return .init(sqlAssociation: _sqlAssociation.forDestinationKey(associationKey)) + return with { + $0._sqlAssociation = $0._sqlAssociation.forDestinationKey(associationKey) + } } } diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 97820b2f8..1813bb570 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -62,6 +62,7 @@ extension AssociationToMany { /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// /// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db) + @available(*, deprecated, message: "Did you mean average(Column(...))? If not, prefer average(value.databaseValue) instead.") // swiftlint:disable:this line_length public func average(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression])) if let column = expression as? ColumnExpression { @@ -72,6 +73,33 @@ extension AssociationToMany { } } + /// Creates an aggregate which evaluate to the average value of the given + /// expression in associated records. + /// + /// When the averaged expression is a column, the aggregate has a default + /// name which is "average[Key][Column]", where key is the key of the + /// association. For example: + /// + /// For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var averagePlayerScore: Double + /// } + /// let request = Team.annotated(with: Team.players.average(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db) + public func average(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression])) + if let column = expression as? ColumnExpression { + let name = key.singularizedName + return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + } else { + return aggregate + } + } + /// Creates an aggregate which evaluate to the maximum value of the given /// expression in associated records. /// @@ -89,6 +117,7 @@ extension AssociationToMany { /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// /// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db) + @available(*, deprecated, message: "Did you mean max(Column(...))? If not, prefer max(value.databaseValue) instead.") // swiftlint:disable:this line_length public func max(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression])) if let column = expression as? ColumnExpression { @@ -99,6 +128,33 @@ extension AssociationToMany { } } + /// Creates an aggregate which evaluate to the maximum value of the given + /// expression in associated records. + /// + /// When the maximized expression is a column, the aggregate has a default + /// name which is "maximum[Key][Column]", where key is the key of the + /// association. For example: + /// + /// For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var maxPlayerScore: Double + /// } + /// let request = Team.annotated(with: Team.players.max(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db) + public func max(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression])) + if let column = expression as? ColumnExpression { + let name = key.singularizedName + return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + } else { + return aggregate + } + } + /// Creates an aggregate which evaluate to the minimum value of the given /// expression in associated records. /// @@ -116,6 +172,7 @@ extension AssociationToMany { /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// /// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db) + @available(*, deprecated, message: "Did you mean min(Column(...))? If not, prefer min(value.databaseValue) instead.") // swiftlint:disable:this line_length public func min(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression])) if let column = expression as? ColumnExpression { @@ -126,6 +183,33 @@ extension AssociationToMany { } } + /// Creates an aggregate which evaluate to the minimum value of the given + /// expression in associated records. + /// + /// When the minimized expression is a column, the aggregate has a default + /// name which is "minimum[Key][Column]", where key is the key of the + /// association. For example: + /// + /// For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var minPlayerScore: Double + /// } + /// let request = Team.annotated(with: Team.players.min(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db) + public func min(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression])) + if let column = expression as? ColumnExpression { + let name = key.singularizedName + return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + } else { + return aggregate + } + } + /// Creates an aggregate which evaluate to the sum of the given expression /// in associated records. /// @@ -143,6 +227,7 @@ extension AssociationToMany { /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// /// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db) + @available(*, deprecated, message: "Did you mean sum(Column(...))? If not, prefer sum(value.databaseValue) instead.") // swiftlint:disable:this line_length public func sum(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression])) if let column = expression as? ColumnExpression { @@ -152,6 +237,33 @@ extension AssociationToMany { return aggregate } } + + /// Creates an aggregate which evaluate to the sum of the given expression + /// in associated records. + /// + /// When the summed expression is a column, the aggregate has a default + /// name which is "[key][Column]Sum", where key is the key of the + /// association. For example: + /// + /// For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var playerScoreSum: Double + /// } + /// let request = Team.annotated(with: Team.players.sum(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db) + public func sum(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression])) + if let column = expression as? ColumnExpression { + let name = key.singularizedName + return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") + } else { + return aggregate + } + } } /// An AssociationAggregate is able to compute aggregated values from a @@ -232,7 +344,9 @@ extension AssociationAggregate: Refinable { /// let numberOfBooks: Int = row["numberOfBooks"] /// } public func forKey(_ key: String) -> Self { - with(\.key, key) + with { + $0.key = key + } } /// Returns an aggregate that is selected in a column named like the given @@ -976,8 +1090,9 @@ public func ?? ( rhs: SQLExpressible) -> AssociationAggregate { - // Preserve key - lhs.map { $0 ?? rhs }.with(\.key, lhs.key) + lhs + .map { $0 ?? rhs } + .with { $0.key = lhs.key } // Preserve key } // TODO: add support for ABS(aggregate) diff --git a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift index 435d76725..7ce78d7e1 100644 --- a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift @@ -44,7 +44,7 @@ /// 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. +/// See for more information. /// /// The example above uses auto-incremented primary keys. But generally /// speaking, all primary keys are supported. @@ -68,11 +68,6 @@ public struct BelongsToAssociation: AssociationToOne { /// :nodoc: public var _sqlAssociation: _SQLAssociation - /// :nodoc: - public init(sqlAssociation: _SQLAssociation) { - self._sqlAssociation = sqlAssociation - } - init( to destinationRelation: SQLRelation, key: String?, diff --git a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift index ad74dfbda..9e00ab85e 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift @@ -44,7 +44,7 @@ /// 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. +/// See for more information. /// /// The example above uses auto-incremented primary keys. But generally /// speaking, all primary keys are supported. @@ -68,11 +68,6 @@ public struct HasManyAssociation: AssociationToMany { /// :nodoc: public var _sqlAssociation: _SQLAssociation - /// :nodoc: - public init(sqlAssociation: _SQLAssociation) { - self._sqlAssociation = sqlAssociation - } - init( to destinationRelation: SQLRelation, key: String?, diff --git a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift index e2d3eeb91..51eda18de 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift @@ -50,9 +50,4 @@ public struct HasManyThroughAssociation: AssociationToMany /// :nodoc: public var _sqlAssociation: _SQLAssociation - - /// :nodoc: - public init(sqlAssociation: _SQLAssociation) { - self._sqlAssociation = sqlAssociation - } } diff --git a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift index 020b34b9f..f701ff9dd 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift @@ -46,7 +46,7 @@ /// 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. +/// See for more information. /// /// The example above uses a string primary for the country table. But generally /// speaking, all primary keys are supported. @@ -70,11 +70,6 @@ public struct HasOneAssociation: AssociationToOne { /// :nodoc: public var _sqlAssociation: _SQLAssociation - /// :nodoc: - public init(sqlAssociation: _SQLAssociation) { - self._sqlAssociation = sqlAssociation - } - init( to destinationRelation: SQLRelation, key: String?, diff --git a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift index 7d7027496..b77569198 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift @@ -30,9 +30,4 @@ public struct HasOneThroughAssociation: AssociationToOne { /// :nodoc: public var _sqlAssociation: _SQLAssociation - - /// :nodoc: - public init(sqlAssociation: _SQLAssociation) { - self._sqlAssociation = sqlAssociation - } } diff --git a/GRDB/QueryInterface/Request/Association/JoinAssociation.swift b/GRDB/QueryInterface/Request/Association/JoinAssociation.swift index 8578d2705..3e142448b 100644 --- a/GRDB/QueryInterface/Request/Association/JoinAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/JoinAssociation.swift @@ -10,11 +10,6 @@ public struct JoinAssociation: AssociationToOne { /// :nodoc: public var _sqlAssociation: _SQLAssociation - /// :nodoc: - public init(sqlAssociation: _SQLAssociation) { - self._sqlAssociation = sqlAssociation - } - /// Creates a `JoinAssociation` whose key is the table name of the relation. init( to relation: SQLRelation, diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index ebbdd54e1..5e5389e0c 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -378,7 +378,8 @@ extension CommonTableExpression { /// /// The key of the returned association is the table name of `Destination`. /// - /// - parameter cte: A common table expression. + /// - parameter destination: The record type at the other side of + /// the association. /// - parameter condition: A function that returns the joining clause. /// - parameter left: A `TableAlias` for the left table. /// - parameter right: A `TableAlias` for the right table. @@ -399,7 +400,8 @@ extension CommonTableExpression { /// /// The key of the returned association is the table name of `Destination`. /// - /// - parameter cte: A common table expression. + /// - parameter destination: The record type at the other side of + /// the association. /// - returns: An association to the common table expression. public func association( to destination: Destination.Type) @@ -408,4 +410,38 @@ extension CommonTableExpression { { JoinAssociation(to: Destination.relationForAll, condition: .none) } + + /// Creates an association to a table that you can join + /// or include in another request. + /// + /// The key of the returned association is the table name of `Destination`. + /// + /// - parameter destination: The table at the other side of the association. + /// - parameter condition: A function that returns the joining clause. + /// - parameter left: A `TableAlias` for the left table. + /// - parameter right: A `TableAlias` for the right table. + /// - returns: An association to the common table expression. + public func association( + to destination: Table, + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + -> JoinAssociation + { + JoinAssociation( + to: destination.relationForAll, + condition: .expression { condition($0, $1).sqlExpression }) + } + + /// Creates an association to a table that you can join + /// or include in another request. + /// + /// The key of the returned association is the table name of `Destination`. + /// + /// - parameter destination: The table at the other side of the association. + /// - returns: An association to the common table expression. + public func association( + to destination: Table) + -> JoinAssociation + { + JoinAssociation(to: destination.relationForAll, condition: .none) + } } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index dab927780..490ff67d9 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -27,7 +27,7 @@ /// let players = try request.fetchAll(db) // [Player] /// } /// -/// See https://github.com/groue/GRDB.swift#the-query-interface +/// See public struct QueryInterfaceRequest { var relation: SQLRelation } @@ -77,7 +77,11 @@ extension QueryInterfaceRequest: SelectionRequest { /// .select { db in [Column("id")] } /// .select { db in [Column("email")] } public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { - map(\.relation) { $0.select { try selection($0).map(\.sqlSelection) } } + with { + $0.relation = $0.relation.select { db in + try selection(db).map(\.sqlSelection) + } + } } /// Creates a request which selects *selection*, and fetches values of @@ -153,7 +157,52 @@ extension QueryInterfaceRequest: SelectionRequest { /// .select([Column("id"), Column("email")]) /// .annotated(with: { db in [Column("name")] }) public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { - map(\.relation) { $0.annotated { try selection($0).map(\.sqlSelection) } } + with { + $0.relation = $0.relation.annotated { db in + try selection(db).map(\.sqlSelection) + } + } + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension QueryInterfaceRequest +where RowDecoder: Identifiable, + RowDecoder.ID: DatabaseValueConvertible +{ + /// Creates a request which selects the primary key. + /// + /// // SELECT id FROM player WHERE ... + /// let request = try Player.filter(...).selectID() + public func selectID() -> QueryInterfaceRequest { + select { db in + let primaryKey = try db.primaryKey(self.databaseTableName) + GRDBPrecondition( + primaryKey.columns.count == 1, + "selectID requires a single-column primary key in the table \(self.databaseTableName)") + return [Column(primaryKey.columns[0])] + }.asRequest(of: RowDecoder.ID.self) + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension QueryInterfaceRequest +where RowDecoder: Identifiable, + RowDecoder.ID: _OptionalProtocol, + RowDecoder.ID.Wrapped: DatabaseValueConvertible +{ + /// Creates a request which selects the primary key. + /// + /// // SELECT id FROM player WHERE ... + /// let request = try Player.filter(...).selectID() + public func selectID() -> QueryInterfaceRequest { + select { db in + let primaryKey = try db.primaryKey(self.databaseTableName) + GRDBPrecondition( + primaryKey.columns.count == 1, + "selectID requires a single-column primary key in the table \(self.databaseTableName)") + return [Column(primaryKey.columns[0])] + }.asRequest(of: RowDecoder.ID.Wrapped.self) } } @@ -165,7 +214,11 @@ extension QueryInterfaceRequest: FilteredRequest { /// var request = Player.all() /// request = request.filter { db in true } public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { - map(\.relation) { $0.filter { try predicate($0).sqlExpression } } + with { + $0.relation = $0.relation.filter { db in + try predicate(db).sqlExpression + } + } } } @@ -184,7 +237,11 @@ extension QueryInterfaceRequest: OrderedRequest { /// .reversed() /// .order{ _ in [Column("name")] } public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest { - map(\.relation) { $0.order { try orderings($0).map(\.sqlOrdering) } } + with { + $0.relation = $0.relation.order { db in + try orderings(db).map(\.sqlOrdering) + } + } } /// Creates a request that reverses applied orderings. @@ -199,7 +256,9 @@ extension QueryInterfaceRequest: OrderedRequest { /// var request = Player.all() /// request = request.reversed() public func reversed() -> QueryInterfaceRequest { - map(\.relation) { $0.reversed() } + with { + $0.relation = $0.relation.reversed() + } } /// Creates a request without any ordering. @@ -208,20 +267,30 @@ extension QueryInterfaceRequest: OrderedRequest { /// var request = Player.all().order(Column("name")) /// request = request.unordered() public func unordered() -> QueryInterfaceRequest { - map(\.relation) { $0.unordered() } + with { + $0.relation = $0.relation.unordered() + } } } extension QueryInterfaceRequest: AggregatingRequest { /// Creates a request grouped according to *expressions promise*. public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest { - map(\.relation) { $0.group { try expressions($0).map(\.sqlExpression) } } + with { + $0.relation = $0.relation.group { db in + try expressions(db).map(\.sqlExpression) + } + } } /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { - map(\.relation) { $0.having { try predicate($0).sqlExpression } } + with { + $0.relation = $0.relation.having { db in + try predicate(db).sqlExpression + } + } } } @@ -229,27 +298,37 @@ extension QueryInterfaceRequest: AggregatingRequest { extension QueryInterfaceRequest: _JoinableRequest { /// :nodoc: public func _including(all association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.relation) { $0._including(all: association) } + with { + $0.relation = $0.relation._including(all: association) + } } /// :nodoc: public func _including(optional association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.relation) { $0._including(optional: association) } + with { + $0.relation = $0.relation._including(optional: association) + } } /// :nodoc: public func _including(required association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.relation) { $0._including(required: association) } + with { + $0.relation = $0.relation._including(required: association) + } } /// :nodoc: public func _joining(optional association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.relation) { $0._joining(optional: association) } + with { + $0.relation = $0.relation._joining(optional: association) + } } /// :nodoc: public func _joining(required association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.relation) { $0._joining(required: association) } + with { + $0.relation = $0.relation._joining(required: association) + } } } @@ -279,13 +358,17 @@ extension QueryInterfaceRequest: TableRequest { /// .aliased(playerAlias) /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { - map(\.relation) { $0.aliased(alias) } + with { + $0.relation = $0.relation.aliased(alias) + } } } extension QueryInterfaceRequest: DerivableRequest { public func distinct() -> QueryInterfaceRequest { - with(\.relation.isDistinct, true) + with { + $0.relation.isDistinct = true + } } /// Creates a request which fetches *limit* rows, starting at *offset*. @@ -296,11 +379,15 @@ extension QueryInterfaceRequest: DerivableRequest { /// /// Any previous limit is replaced. public func limit(_ limit: Int, offset: Int?) -> QueryInterfaceRequest { - with(\.relation.limit, SQLLimit(limit: limit, offset: offset)) + with { + $0.relation.limit = SQLLimit(limit: limit, offset: offset) + } } public func with(_ cte: CommonTableExpression) -> Self { - with(\.relation.ctes[cte.tableName], cte.cte) + with { + $0.relation.ctes[cte.tableName] = cte.cte + } } } @@ -325,7 +412,7 @@ extension QueryInterfaceRequest { // MARK: - Batch Delete -extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { +extension QueryInterfaceRequest { /// Deletes matching rows; returns the number of deleted rows. /// /// - parameter db: A database connection. @@ -340,7 +427,20 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { // MARK: - Batch Update -extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { +extension QueryInterfaceRequest { + /// The conflict resolution to use for batch updates + private var defaultConflictResolutionForUpdate: Database.ConflictResolution { + // In order to look for the default conflict resolution, we perform a + // runtime check for MutablePersistableRecord, and look for a + // user-defined default. Such dynamic dispatch is unusual in GRDB, but + // static dispatch is likely to create bad surprises in generic contexts. + if let recordType = RowDecoder.self as? MutablePersistableRecord.Type { + return recordType.persistenceConflictPolicy.conflictResolutionForUpdate + } else { + return .abort + } + } + /// Updates matching rows; returns the number of updated rows. /// /// For example: @@ -351,8 +451,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { /// } /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution, - /// defaulting to the record's persistenceConflictPolicy. + /// - parameter conflictResolution: A policy for conflict resolution. /// - parameter assignments: An array of column assignments. /// - returns: The number of updated rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @@ -362,7 +461,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { onConflict conflictResolution: Database.ConflictResolution? = nil, _ assignments: [ColumnAssignment]) throws -> Int { - let conflictResolution = conflictResolution ?? RowDecoder.persistenceConflictPolicy.conflictResolutionForUpdate + let conflictResolution = conflictResolution ?? defaultConflictResolutionForUpdate guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement( db, conflictResolution: conflictResolution, @@ -385,8 +484,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { /// } /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution, - /// defaulting to the record's persistenceConflictPolicy. + /// - parameter conflictResolution: A policy for conflict resolution. /// - parameter assignment: A column assignment. /// - parameter otherAssignments: Eventual other column assignments. /// - returns: The number of updated rows. @@ -659,7 +757,11 @@ func makePrefetchRequest( let pivotAlias = TableAlias() let prefetchRelation = association - .map(\.pivot.relation, { $0.aliased(pivotAlias).filter(pivotFilter) }) + .with { + $0.pivot.relation = $0.pivot.relation + .aliased(pivotAlias) + .filter(pivotFilter) + } .destinationRelation() .annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") }) @@ -704,11 +806,13 @@ throws -> DatabaseRegion let pivotFilter = pivotMapping.joinExpression(leftRows: [DummyRow()]) let prefetchRelation = association - .map(\.pivot.relation) { $0.filter(pivotFilter) } + .with { + $0.pivot.relation = $0.pivot.relation.filter(pivotFilter) + } .destinationRelation() return try SQLQueryGenerator(relation: prefetchRelation) - .makeSelectStatement(db) + .makeStatement(db) .databaseRegion // contains region of nested associations } diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index 97811b3c5..7f3f35147 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -16,7 +16,7 @@ /// 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 +/// See public protocol ColumnExpression: SQLSpecificExpressible { /// The unqualified name of a database column. /// @@ -35,7 +35,7 @@ extension ColumnExpression { /// 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 +/// See public struct Column: ColumnExpression, Equatable { /// The hidden rowID column public static let rowID = Column("rowid") diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index 3e6585cf1..f756bc22d 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -87,7 +87,9 @@ public struct _SQLAssociation { /// Changes the destination key func forDestinationKey(_ key: SQLAssociationKey) -> Self { - with(\.destination.key, key) + with { + $0.destination.key = key + } } /// Returns a new association @@ -126,7 +128,9 @@ public struct _SQLAssociation { .removingChildrenForPrefetchedAssociations() // Don't interfere with user-defined keys that could be added later - let key = step.key.map(\.baseName) { "grdb_\($0)" } + let key = step.key.with { + $0.baseName = "grdb_\($0.baseName)" + } return SQLAssociationStep( key: key, diff --git a/GRDB/QueryInterface/SQL/SQLCollection.swift b/GRDB/QueryInterface/SQL/SQLCollection.swift index d4f8782bc..817d61366 100644 --- a/GRDB/QueryInterface/SQL/SQLCollection.swift +++ b/GRDB/QueryInterface/SQL/SQLCollection.swift @@ -1,6 +1,6 @@ /// The right-hand side of the `IN` or `NOT IN` SQL operators /// -/// See https://sqlite.org/lang_expr.html#the_in_and_not_in_operators +/// See struct SQLCollection { private var impl: Impl diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index fa1c1da26..e76711e5f 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1,5 +1,5 @@ /// SQLExpression is the type that represents an SQL expression, as -/// described at https://www.sqlite.org/lang_expr.html +/// described at public struct SQLExpression { private var impl: Impl @@ -370,7 +370,7 @@ public typealias SQLAssociativeBinaryOperator = SQLExpression.AssociativeBinaryO extension SQLExpression { /// SQLite row values were shipped in SQLite 3.15: - /// https://www.sqlite.org/releaselog/3_15_0.html + /// static let rowValuesAreAvailable = (sqlite3_libversion_number() >= 3015000) // MARK: Basic Expressions @@ -1204,7 +1204,7 @@ extension SQLExpression { /// /// The `= 1` and `= 0` tests allow the SQLite query planner to /// optimize queries with indices on boolean columns and expressions. - /// See https://github.com/groue/GRDB.swift/issues/816 + /// See /// /// Some specific expressions can produce idiomatic SQL. /// @@ -1559,7 +1559,7 @@ extension SQLExpression { /// It is adopted by protocols like `DatabaseValueConvertible`, and types /// like `Column`. /// -/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// See public protocol SQLExpressible { /// Returns an SQL expression. var sqlExpression: SQLExpression { get } @@ -1665,14 +1665,14 @@ extension SQLSpecificExpressible { /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// See public var asc: SQLOrdering { .asc(sqlExpression) } /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// See public var desc: SQLOrdering { .desc(sqlExpression) } @@ -1680,21 +1680,21 @@ extension SQLSpecificExpressible { #if GRDBCUSTOMSQLITE /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// See public var ascNullsLast: SQLOrdering { .ascNullsLast(sqlExpression) } /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// See public var descNullsFirst: SQLOrdering { .descNullsFirst(sqlExpression) } #elseif !GRDBCIPHER /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// See @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) public var ascNullsLast: SQLOrdering { .ascNullsLast(sqlExpression) @@ -1702,7 +1702,7 @@ extension SQLSpecificExpressible { /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// See @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) public var descNullsFirst: SQLOrdering { .descNullsFirst(sqlExpression) diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 7c39dd23a..ddd05786f 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -174,7 +174,7 @@ extension SQLSpecificExpressible { /// A date modifier for SQLite date functions such as `julianDay(_:_:)` and /// `dateTime(_:_:)`. /// -/// For more information, see https://www.sqlite.org/lang_datefunc.html +/// For more information, see public enum SQLDateModifier: SQLSpecificExpressible { /// Adds the specified amount of seconds case second(Double) @@ -203,16 +203,16 @@ public enum SQLDateModifier: SQLSpecificExpressible { /// Shifts the date backwards to the beginning of the current year case startOfYear - /// See https://www.sqlite.org/lang_datefunc.html + /// See case weekday(Int) - /// See https://www.sqlite.org/lang_datefunc.html + /// See case unixEpoch - /// See https://www.sqlite.org/lang_datefunc.html + /// See case localTime - /// See https://www.sqlite.org/lang_datefunc.html + /// See case utc public var sqlExpression: SQLExpression { @@ -261,7 +261,7 @@ public enum SQLDateModifier: SQLSpecificExpressible { /// // JULIANDAY(date, '1 days') /// julianDay(Column("date"), .day(1)) /// -/// For more information, see https://www.sqlite.org/lang_datefunc.html +/// For more information, see public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { .function("JULIANDAY", [value.sqlExpression] + modifiers.map(\.sqlExpression)) } @@ -276,7 +276,7 @@ public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModif /// // DATETIME(date, '1 days') /// dateTime(Column("date"), .day(1)) /// -/// For more information, see https://www.sqlite.org/lang_datefunc.html +/// For more information, see public func dateTime(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { .function("DATETIME", [value.sqlExpression] + modifiers.map(\.sqlExpression)) } diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index 944331b91..8150f6acd 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -1,5 +1,5 @@ /// The type that can be used as an SQL ordering term, as described at -/// https://www.sqlite.org/syntax/ordering-term.html +/// public struct SQLOrdering { private var impl: Impl @@ -117,7 +117,7 @@ extension SQLOrdering { // MARK: - SQLOrderingTerm /// The protocol for all types that can be used as an SQL ordering term, as -/// described at https://www.sqlite.org/syntax/ordering-term.html +/// described at public protocol SQLOrderingTerm { /// Returns an SQL ordering. var sqlOrdering: SQLOrdering { get } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index dd4759c52..3be12514e 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -190,7 +190,9 @@ extension SQLRelation { extension SQLRelation: Refinable { func select(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self { - with(\.selectionPromise, DatabasePromise(selection)) + with { + $0.selectionPromise = DatabasePromise(selection) + } } // Convenience @@ -208,18 +210,21 @@ extension SQLRelation: Refinable { func selectOnly(_ selection: [SQLSelection]) -> Self { self .select(selection) - .with(\.isDistinct, false) - .map(\.children) { children in - children.mapValues { child in - child.map(\.relation) { $0.selectOnly([]) } + .with { + $0.isDistinct = false + $0.children = children.mapValues { child in + child.with { + $0.relation = $0.relation.selectOnly([]) + } } } } func annotated(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self { - map(\.selectionPromise) { selectionPromise in - DatabasePromise { db in - try selectionPromise.resolve(db) + selection(db) + with { + let old = $0.selectionPromise + $0.selectionPromise = DatabasePromise { db in + try old.resolve(db) + selection(db) } } } @@ -230,13 +235,13 @@ extension SQLRelation: Refinable { } func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { - map(\.filterPromise) { promise in - DatabasePromise { db in - if let filter = try promise?.resolve(db) { - return try filter && predicate(db) - } else { - return try predicate(db) + with { + if let old = $0.filterPromise { + $0.filterPromise = DatabasePromise { db in + try old.resolve(db) && predicate(db) } + } else { + $0.filterPromise = DatabasePromise(predicate) } } } @@ -247,41 +252,50 @@ extension SQLRelation: Refinable { } func order(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self { - with(\.ordering, SQLRelation.Ordering(orderings: orderings)) + with { + $0.ordering = SQLRelation.Ordering(orderings: orderings) + } } func reversed() -> Self { - map(\.ordering, \.reversed) + with { + $0.ordering = $0.ordering.reversed + } } func unordered() -> Self { - self - .with(\.ordering, SQLRelation.Ordering()) - .map(\.children) { children in - children.mapValues { child in - child.map(\.relation) { $0.unordered() } - } - } - } - - func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self { - with(\.groupPromise, DatabasePromise(expressions)) - } - - func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { - map(\.havingExpressionPromise) { promise in - DatabasePromise { db in - if let filter = try promise?.resolve(db) { - return try filter && predicate(db) - } else { - return try predicate(db) + with { + $0.ordering = SQLRelation.Ordering() + $0.children = children.mapValues { child in + child.with { + $0.relation = $0.relation.unordered() } } } } + func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self { + with { + $0.groupPromise = DatabasePromise(expressions) + } + } + + func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { + with { + if let old = $0.havingExpressionPromise { + $0.havingExpressionPromise = DatabasePromise { db in + try old.resolve(db) && predicate(db) + } + } else { + $0.havingExpressionPromise = DatabasePromise(predicate) + } + } + } + func aliased(_ alias: TableAlias) -> Self { - map(\.source) { $0.aliased(alias) } + with { + $0.source = $0.source.aliased(alias) + } } } @@ -296,9 +310,9 @@ extension SQLRelation { return child.relation.prefetchedAssociations.map { association in // Remove redundant pivot child let pivotKey = association.pivot.keyName - let child = child.map(\.relation) { relation in - assert(relation.children[pivotKey] != nil) - return relation.removingChild(forKey: pivotKey) + let child = child.with { + assert($0.relation.children[pivotKey] != nil) + $0.relation = $0.relation.removingChild(forKey: pivotKey) } return association.through(child.makeAssociationForKey(key)) } @@ -488,11 +502,15 @@ extension SQLRelation { } func removingChild(forKey key: String) -> Self { - mapInto(\.children) { $0.removeValue(forKey: key) } + with { + $0.children.removeValue(forKey: key) + } } func filteringChildren(_ included: (Child) throws -> Bool) rethrows -> Self { - try map(\.children) { try $0.filter { try included($1) } } + try with { + $0.children = try $0.children.filter { (_, child) in try included(child) } + } } func removingChildrenForPrefetchedAssociations() -> Self { @@ -519,11 +537,19 @@ extension SQLRelation { } func _joining(optional association: _SQLAssociation) -> Self { - appendingChild(for: association.map(\.destination.relation, { $0.select([]) }), kind: .oneOptional) + // Remove association selection + let associationWithEmptySelection = association.with { + $0.destination.relation = $0.destination.relation.select([]) + } + return appendingChild(for: associationWithEmptySelection, kind: .oneOptional) } func _joining(required association: _SQLAssociation) -> Self { - appendingChild(for: association.map(\.destination.relation, { $0.select([]) }), kind: .oneRequired) + // Remove association selection + let associationWithEmptySelection = association.with { + $0.destination.relation = $0.destination.relation.select([]) + } + return appendingChild(for: associationWithEmptySelection, kind: .oneRequired) } } @@ -869,33 +895,46 @@ extension JoinMapping { return true.sqlExpression } + // SQLite doesn't match foreign keys on NULL: https://www.sqlite.org/foreignkeys.html + // > The foreign key constraint is satisfied if for each row in the + // > child table either one or more of the child key columns are NULL, + // > or there exists a row in the parent table for which each parent key + // > column contains a value equal to the value in its associated child + // > key column. + // + // Since a single NULL value satisfies the foreign key constraint + // without requiring a matching matching parent row, below we'll ignore + // left rows (children) that attempt at matching on NULL. if mappings.count == 1 { // Join on a single right column. + // table.a IN (1, 2, 3, ...) - // Unique database values and filter out NULL: + // Unique database values and filter out NULL because SQLite doesn't + // match foreign keys on NULL let leftIndex = mapping.leftIndex var dbValues = Set(leftRows.map { $0.databaseValue(at: leftIndex) }) - dbValues.remove(.null) // SQLite doesn't match foreign keys on NULL - // table.a IN (1, 2, 3, ...) + dbValues.remove(.null) + // Sort database values for nicer output. return dbValues.sorted(by: <).contains(mapping.rightColumn) } else { // Join on a multiple columns. // ((table.a = 1) AND (table.b = 2)) OR ((table.a = 3) AND (table.b = 4)) ... return leftRows - .map({ leftRow in + .compactMap { leftRow -> SQLExpression? in // (table.a = 1) AND (table.b = 2) - mappings - .map({ mapping -> SQLExpression in - let leftValue = leftRow.databaseValue(at: mapping.leftIndex) - // Force `=` operator, because SQLite doesn't match foreign keys on NULL - return SQLExpression.compare( - .equal, - mapping.rightColumn.sqlExpression, - leftValue.sqlExpression) - }) - .joined(operator: .and) - }) + var conditions: [SQLExpression] = [] + for mapping in mappings { + let dbValue = leftRow.databaseValue(at: mapping.leftIndex) + if dbValue.isNull { + // SQLite doesn't match foreign keys on NULL: + // give up this left row. + return nil + } + conditions.append(mapping.rightColumn == dbValue) + } + return conditions.joined(operator: .and) + } .joined(operator: .or) } } @@ -941,10 +980,7 @@ extension PersistenceContainer: ColumnAddressable { func index(forColumn column: String) -> String? { column } @inline(__always) func databaseValue(at column: String) -> DatabaseValue { - guard let value = self[caseInsensitive: column] else { - fatalError("Missing column: \(column)") - } - return value.databaseValue + self[caseInsensitive: column]?.databaseValue ?? .null } } diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index 07b704ead..3daf976bf 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -1,5 +1,5 @@ /// The type that can be selected, as described at -/// https://www.sqlite.org/syntax/result-column.html +/// public struct SQLSelection { private var impl: Impl @@ -175,7 +175,7 @@ extension SQLSelection { /// COUNT(*) /// (score + bonus) AS total /// - /// See https://sqlite.org/syntax/result-column.html + /// See /// /// - parameter context: An SQL generation context which accepts /// statement arguments. @@ -285,7 +285,7 @@ enum SQLCount { // MARK: - SQLSelectable /// SQLSelectable is the protocol for types that can be selected, as -/// described at https://www.sqlite.org/syntax/result-column.html +/// described at public protocol SQLSelectable { /// Returns an SQL selection. var sqlSelection: SQLSelection { get } diff --git a/GRDB/QueryInterface/SQL/SQLSubquery.swift b/GRDB/QueryInterface/SQL/SQLSubquery.swift index 9b77a1c1f..f7d91a98a 100644 --- a/GRDB/QueryInterface/SQL/SQLSubquery.swift +++ b/GRDB/QueryInterface/SQL/SQLSubquery.swift @@ -45,7 +45,7 @@ extension SQLSubquery { // do not execute the statement or modify its arguments. let context = SQLGenerationContext(db) let sql = try sqlLiteral.sql(context) - let statement = try db.cachedSelectStatement(sql: sql) + let statement = try db.cachedStatement(sql: sql) return statement.columnCount case let .relation(relation): diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift new file mode 100644 index 000000000..2a6481328 --- /dev/null +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -0,0 +1,1517 @@ +/// `Table` can build query interface requests. +/// +/// // SELECT * FROM player WHERE score >= 1000 +/// let table = Table("player") +/// let rows: [Row] = try dbQueue.read { db in +/// table.all() +/// .filter(Column("score") >= 1000) +/// .fetchAll(db) +/// } +public struct Table { + /// The table name + public var tableName: String + + private init(_ tableName: String, _ type: RowDecoder.Type) { + self.tableName = tableName + } + + /// Create a `Table` + /// + /// let table = Table("player") + /// let table = Table("player") + public init(_ tableName: String) { + self.init(tableName, RowDecoder.self) + } +} + +extension Table where RowDecoder == Row { + /// Create a `Table` of `Row`. + /// + /// let table = Table("player") // Table + public init(_ tableName: String) { + self.init(tableName, Row.self) + } +} + +// MARK: Request Derivation + +extension Table { + var relationForAll: SQLRelation { + .all(fromTable: tableName) + } + + /// Creates a request for all rows of the table. + /// + /// // Fetch all players + /// let table = Table("player") + /// let request = table.all() + /// let players: [Player] = try request.fetchAll(db) + public func all() -> QueryInterfaceRequest { + QueryInterfaceRequest(relation: relationForAll) + } + + /// Creates a request which fetches no row. + /// + /// // Fetch no players + /// let table = Table("player") + /// let request = table.none() + /// let players: [Player] = try request.fetchAll(db) // Empty array + public func none() -> QueryInterfaceRequest { + all().none() // don't laugh + } + + /// Creates a request which selects *selection*. + /// + /// // SELECT id, email FROM player + /// let table = Table("player") + /// let request = table.select(Column("id"), Column("email")) + public func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { + all().select(selection) + } + + /// Creates a request which selects *selection*. + /// + /// // SELECT id, email FROM player + /// let table = Table("player") + /// let request = table.select([Column("id"), Column("email")]) + public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { + all().select(selection) + } + + /// Creates a request which selects *sql*. + /// + /// // SELECT id, email FROM player + /// let table = Table("player") + /// let request = table.select(sql: "id, email") + public func select( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { + all().select(SQL(sql: sql, arguments: arguments)) + } + + /// Creates a request which selects an SQL *literal*. + /// + /// Literals allow you to safely embed raw values in your SQL, without any + /// risk of syntax errors or SQL injection: + /// + /// // SELECT id, email, score + 1000 FROM player + /// let table = Table("player") + /// let bonus = 1000 + /// let request = table.select(literal: """ + /// id, email, score + \(bonus) + /// """) + public func select(literal sqlLiteral: SQL) -> QueryInterfaceRequest { + all().select(sqlLiteral) + } + + /// Creates a request which selects *selection*, and fetches values of + /// type *type*. + /// + /// try dbQueue.read { db in + /// // SELECT max(score) FROM player + /// let table = Table("player") + /// let request = table.select([max(Column("score"))], as: Int.self) + /// let maxScore: Int? = try request.fetchOne(db) + /// } + public func select( + _ selection: [SQLSelectable], + as type: RowDecoder.Type = RowDecoder.self) + -> QueryInterfaceRequest + { + all().select(selection, as: type) + } + + /// Creates a request which selects *selection*, and fetches values of + /// type *type*. + /// + /// try dbQueue.read { db in + /// // SELECT max(score) FROM player + /// let table = Table("player") + /// let request = table.select(max(Column("score")), as: Int.self) + /// let maxScore: Int? = try request.fetchOne(db) + /// } + public func select( + _ selection: SQLSelectable..., + as type: RowDecoder.Type = RowDecoder.self) + -> QueryInterfaceRequest + { + all().select(selection, as: type) + } + + /// Creates a request which selects *sql*, and fetches values of + /// type *type*. + /// + /// try dbQueue.read { db in + /// // SELECT max(score) FROM player + /// let table = Table("player") + /// let request = table.select(sql: "max(score)", as: Int.self) + /// let maxScore: Int? = try request.fetchOne(db) + /// } + public func select( + sql: String, + arguments: StatementArguments = StatementArguments(), + as type: RowDecoder.Type = RowDecoder.self) + -> QueryInterfaceRequest + { + all().select(SQL(sql: sql, arguments: arguments), as: type) + } + + /// Creates a request which selects an SQL *literal*, and fetches values of + /// type *type*. + /// + /// Literals allow you to safely embed raw values in your SQL, without any + /// risk of syntax errors or SQL injection: + /// + /// // SELECT IFNULL(name, 'Anonymous') FROM player + /// let table = Table("player") + /// let defaultName = "Anonymous" + /// let request = table.select( + /// literal: "IFNULL(name, \(defaultName))", + /// as: String.self) + /// let name: String? = try request.fetchOne(db) + public func select( + literal sqlLiteral: SQL, + as type: RowDecoder.Type = RowDecoder.self) + -> QueryInterfaceRequest + { + all().select(sqlLiteral, as: type) + } + + /// Creates a request which appends *selection*. + /// + /// // SELECT id, email, name FROM player + /// let table = Table("player") + /// let request = table + /// .select([Column("id"), Column("email")]) + /// .annotated(with: [Column("name")]) + public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { + all().annotated(with: selection) + } + + /// Creates a request which appends *selection*. + /// + /// // SELECT id, email, name FROM player + /// let table = Table("player") + /// let request = table + /// .select([Column("id"), Column("email")]) + /// .annotated(with: Column("name")) + public func annotated(with selection: SQLSelectable...) -> QueryInterfaceRequest { + all().annotated(with: selection) + } + + /// Creates a request with the provided *predicate*. + /// + /// // SELECT * FROM player WHERE email = 'arthur@example.com' + /// let table = Table("player") + /// let request = table.filter(Column("email") == "arthur@example.com") + public func filter(_ predicate: SQLSpecificExpressible) -> QueryInterfaceRequest { + all().filter(predicate) + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// // SELECT * FROM player WHERE id = 1 + /// let table = Table("player") + /// let request = table.filter(key: 1) + public func filter(key: PrimaryKeyType?) + -> QueryInterfaceRequest + where PrimaryKeyType: DatabaseValueConvertible + { + all().filter(key: key) + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// // SELECT * FROM player WHERE id IN (1, 2, 3) + /// let table = Table("player") + /// let request = table.filter(keys: [1, 2, 3]) + public func filter(keys: Sequence) + -> QueryInterfaceRequest + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { + all().filter(keys: keys) + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// // SELECT * FROM passport WHERE personId = 1 AND countryCode = 'FR' + /// let table = Table("passport") + /// let request = table.filter(key: ["personId": 1, "countryCode": "FR"]) + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { + all().filter(key: key) + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// // SELECT * FROM passport WHERE (personId = 1 AND countryCode = 'FR') OR ... + /// let table = Table("passport") + /// let request = table.filter(keys: [["personId": 1, "countryCode": "FR"], ...]) + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { + all().filter(keys: keys) + } + + /// Creates a request with the provided *predicate*. + /// + /// // SELECT * FROM player WHERE email = 'arthur@example.com' + /// let table = Table("player") + /// let request = table.filter(sql: "email = ?", arguments: ["arthur@example.com"]) + public func filter( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { + filter(SQL(sql: sql, arguments: arguments)) + } + + /// Creates a request with the provided *predicate* added to the + /// eventual set of already applied predicates. + /// + /// Literals allow you to safely embed raw values in your SQL, without any + /// risk of syntax errors or SQL injection: + /// + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let table = Table("player") + /// let name = "O'Brien" + /// let request = table.filter(literal: "email = \(email)") + public func filter(literal sqlLiteral: SQL) -> QueryInterfaceRequest { + all().filter(sqlLiteral) + } + + /// Creates a request sorted according to the + /// provided *orderings*. + /// + /// // SELECT * FROM player ORDER BY name + /// let table = Table("player") + /// let request = table.order(Column("name")) + public func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { + all().order(orderings) + } + + /// Creates a request sorted according to the + /// provided *orderings*. + /// + /// // SELECT * FROM player ORDER BY name + /// let table = Table("player") + /// let request = table.order([Column("name")]) + public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { + all().order(orderings) + } + + /// Creates a request sorted by primary key. + /// + /// // SELECT * FROM player ORDER BY id + /// let table = Table("player") + /// let request = table.orderByPrimaryKey() + /// + /// // SELECT * FROM country ORDER BY code + /// let request = Country.orderByPrimaryKey() + public func orderByPrimaryKey() -> QueryInterfaceRequest { + all().orderByPrimaryKey() + } + + /// Creates a request sorted according to *sql*. + /// + /// // SELECT * FROM player ORDER BY name + /// let table = Table("player") + /// let request = table.order(sql: "name") + public func order( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { + all().order(SQL(sql: sql, arguments: arguments)) + } + + /// Creates a request sorted according to an SQL *literal*. + /// + /// // SELECT * FROM player ORDER BY name + /// let table = Table("player") + /// let request = table.order(literal: "name") + public func order(literal sqlLiteral: SQL) -> QueryInterfaceRequest { + all().order(sqlLiteral) + } + + /// Creates a request which fetches *limit* rows, starting at + /// *offset*. + /// + /// // SELECT * FROM player LIMIT 1 + /// let table = Table("player") + /// let request = table.limit(1) + public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { + all().limit(limit, offset: offset) + } + + /// Creates a request that allows you to define expressions that target + /// a specific database table. + /// + /// See `TableRecord.aliased(_:)` for more information. + public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + all().aliased(alias) + } + + /// Returns a request which embeds the common table expression. + /// + /// See `TableRecord.with(_:)` for more information. + /// + /// - parameter cte: A common table expression. + /// - returns: A request. + public func with(_ cte: CommonTableExpression) -> QueryInterfaceRequest { + all().with(cte) + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { + /// Creates a request filtered by primary key. + /// + /// // SELECT * FROM player WHERE id = 1 + /// let table = Table("player") + /// let request = table.filter(id: 1) + /// + /// - parameter id: A primary key + public func filter(id: RowDecoder.ID) -> QueryInterfaceRequest { + all().filter(id: id) + } + + /// Creates a request filtered by primary key. + /// + /// // SELECT * FROM player WHERE id IN (1, 2, 3) + /// let table = Table("player") + /// let request = table.filter(ids: [1, 2, 3]) + /// + /// - parameter ids: A collection of primary keys + public func filter(ids: Collection) + -> QueryInterfaceRequest + where Collection: Swift.Collection, Collection.Element == RowDecoder.ID + { + all().filter(ids: ids) + } + + /// Creates a request which selects the primary key. + /// + /// // SELECT id FROM player + /// let table = Table("player") + /// let request = try table.selectID() + public func selectID() -> QueryInterfaceRequest { + all().selectID() + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension Table +where RowDecoder: Identifiable, + RowDecoder.ID: _OptionalProtocol, + RowDecoder.ID.Wrapped: DatabaseValueConvertible +{ + /// Creates a request filtered by primary key. + /// + /// // SELECT * FROM player WHERE id = 1 + /// let table = Table("player") + /// let request = table.filter(id: 1) + /// + /// - parameter id: A primary key + public func filter(id: RowDecoder.ID.Wrapped) -> QueryInterfaceRequest { + all().filter(id: id) + } + + /// Creates a request filtered by primary key. + /// + /// // SELECT * FROM player WHERE id IN (1, 2, 3) + /// let table = Table("player") + /// let request = table.filter(ids: [1, 2, 3]) + /// + /// - parameter ids: A collection of primary keys + public func filter(ids: Collection) + -> QueryInterfaceRequest + where Collection: Swift.Collection, Collection.Element == RowDecoder.ID.Wrapped + { + all().filter(ids: ids) + } + + /// Creates a request which selects the primary key. + /// + /// // SELECT id FROM player + /// let table = Table("player") + /// let request = try table.selectID() + public func selectID() -> QueryInterfaceRequest { + all().selectID() + } +} + +extension Table { + + // MARK: - Counting All + + /// The number of rows. + /// + /// - parameter db: A database connection. + public func fetchCount(_ db: Database) throws -> Int { + try all().fetchCount(db) + } +} + +// MARK: - Fetching Records from Table + +extension Table where RowDecoder: FetchableRecord { + /// A cursor over all records fetched from the database. + /// + /// // SELECT * FROM player + /// let table = Table("player") + /// let players = try table.fetchCursor(db) // Cursor of Player + /// while let player = try players.next() { // Player + /// ... + /// } + /// + /// Records are iterated in the natural ordering of the table. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispatch 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 { + try all().fetchCursor(db) + } + + /// An array of all records fetched from the database. + /// + /// // SELECT * FROM player + /// let table = Table("player") + /// let players = try table.fetchAll(db) // [Player] + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder] { + try all().fetchAll(db) + } + + /// The first found record. + /// + /// // SELECT * FROM player LIMIT 1 + /// let table = Table("player") + /// let player = try table.fetchOne(db) // Player? + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder? { + try all().fetchOne(db) + } +} + +extension Table where RowDecoder: FetchableRecord & Hashable { + /// A set of all records fetched from the database. + /// + /// // SELECT * FROM player + /// let table = Table("player") + /// let players = try table.fetchSet(db) // Set + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchSet(_ db: Database) throws -> Set { + try all().fetchSet(db) + } +} + +// MARK: - Fetching Rows from Table + +extension Table where RowDecoder == Row { + /// A cursor over all rows fetched from the database. + /// + /// // SELECT * FROM player + /// let table = Table("player") + /// let rows = try table.fetchCursor(db) // Cursor of Row + /// while let row = try rows.next() { // Row + /// ... + /// } + /// + /// Rows are iterated in the natural ordering of the table. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispatch 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 -> RowCursor { + try all().fetchCursor(db) + } + + /// An array of all rows fetched from the database. + /// + /// // SELECT * FROM player + /// let table = Table("player") + /// let players = try table.fetchAll(db) // [Row] + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [Row] { + try all().fetchAll(db) + } + + /// The first found row. + /// + /// // SELECT * FROM player LIMIT 1 + /// let table = Table("player") + /// let row = try table.fetchOne(db) // Row? + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> Row? { + try all().fetchOne(db) + } + + /// A set of all rows fetched from the database. + /// + /// // SELECT * FROM player + /// let table = Table("player") + /// let rows = try table.fetchSet(db) // Set + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchSet(_ db: Database) throws -> Set { + try all().fetchSet(db) + } +} + +// MARK: - Fetching Values from Table + +extension Table where RowDecoder: DatabaseValueConvertible { + /// A cursor over all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchCursor(db) // Cursor of String + /// while let name = try names.next() { // String + /// ... + /// } + /// + /// Values are iterated in the natural ordering of the table. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispatch 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 -> DatabaseValueCursor { + try all().fetchCursor(db) + } + + /// An array of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchAll(db) // [String] + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder] { + try all().fetchAll(db) + } + + /// The value from the leftmost column of the first row. + /// + /// // SELECT * FROM name LIMIT 1 + /// let table = Table("name") + /// let name = try table.fetchOne(db) // String? + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder? { + try all().fetchOne(db) + } +} + +extension Table where RowDecoder: DatabaseValueConvertible & Hashable { + /// A set of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchSet(db) // Set + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchSet(_ db: Database) throws -> Set { + try all().fetchSet(db) + } +} + +extension Table where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible { + /// A cursor over all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchCursor(db) // Cursor of String? + /// while let name = try names.next() { // String? + /// ... + /// } + /// + /// Values are iterated in the natural ordering of the table. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispatch 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 -> NullableDatabaseValueCursor { + try all().fetchCursor(db) + } + + /// An array of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchAll(db) // [String?] + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] { + try all().fetchAll(db) + } + + /// The value from the leftmost column of the first row. + /// + /// // SELECT * FROM name LIMIT 1 + /// let table = Table("name") + /// let name = try table.fetchOne(db) // String? + /// + /// The result is nil if the query returns no row, or if no value can be + /// extracted from the first row. + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? { + try all().fetchOne(db) + } +} + +extension Table where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible & Hashable { + /// A set of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchSet(db) // Set + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchSet(_ db: Database) throws -> Set { + try all().fetchSet(db) + } +} + +// MARK: - Fetching Fast Values from Table + +extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible { + /// A cursor over all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchCursor(db) // Cursor of String + /// while let name = try names.next() { // String + /// ... + /// } + /// + /// Values are iterated in the natural ordering of the table. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispatch 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 -> FastDatabaseValueCursor { + try all().fetchCursor(db) + } + + /// An array of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchAll(db) // [String] + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder] { + try all().fetchAll(db) + } + + /// The value from the leftmost column of the first row. + /// + /// // SELECT * FROM name LIMIT 1 + /// let table = Table("name") + /// let name = try table.fetchOne(db) // String? + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder? { + try all().fetchOne(db) + } +} + +extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible & Hashable { + /// A set of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchSet(db) // Set + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchSet(_ db: Database) throws -> Set { + try all().fetchSet(db) + } +} + +extension Table +where RowDecoder: _OptionalProtocol, + RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible +{ + /// A cursor over all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchCursor(db) // Cursor of String? + /// while let name = try names.next() { // String? + /// ... + /// } + /// + /// Values are iterated in the natural ordering of the table. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispatch 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 -> FastNullableDatabaseValueCursor { + try all().fetchCursor(db) + } + + /// An array of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchAll(db) // [String?] + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] { + try all().fetchAll(db) + } + + /// The value from the leftmost column of the first row. + /// + /// // SELECT * FROM name LIMIT 1 + /// let table = Table("name") + /// let name = try table.fetchOne(db) // String? + /// + /// The result is nil if the query returns no row, or if no value can be + /// extracted from the first row. + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? { + try all().fetchOne(db) + } +} + +extension Table +where RowDecoder: _OptionalProtocol, + RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable +{ + /// A set of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchSet(db) // Set + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchSet(_ db: Database) throws -> Set { + try all().fetchSet(db) + } +} + +// MARK: - Associations to TableRecord + +extension Table { + /// Creates a "Belongs To" association between Self and the destination + /// type, based on a database foreign key. + /// + /// For more information, see `TableRecord.belongsTo(_:key:using:)`. + /// + /// - 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 func belongsTo( + _ destination: Destination.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + where Destination: TableRecord + { + BelongsToAssociation( + to: Destination.relationForAll, + key: key, + using: foreignKey) + } + + /// Creates a "Has many" association between Self and the destination type, + /// based on a database foreign key. + /// + /// For more information, see `TableRecord.hasMany(_:key:using:)`. + /// + /// - 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 func hasMany( + _ destination: Destination.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + where Destination: TableRecord + { + HasManyAssociation( + to: Destination.relationForAll, + key: key, + using: foreignKey) + } + + /// Creates a "Has one" association between Self and the destination type, + /// based on a database foreign key. + /// + /// For more information, see `TableRecord.hasOne(_:key:using:)`. + /// + /// - 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 func hasOne( + _ destination: Destination.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + where Destination: TableRecord + { + HasOneAssociation( + to: Destination.relationForAll, + key: key, + using: foreignKey) + } +} + +// MARK: - Associations to Table + +extension Table { + /// Creates a "Belongs To" association between Self and the destination + /// table, based on a database foreign key. + /// + /// For more information, see `TableRecord.belongsTo(_:key:using:)`. + /// + /// - parameters: + /// - destination: The table at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.tableName`. + /// - 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 func belongsTo( + _ destination: Table, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + { + BelongsToAssociation( + to: destination.relationForAll, + key: key, + using: foreignKey) + } + + /// Creates a "Has many" association between Self and the destination table, + /// based on a database foreign key. + /// + /// For more information, see `TableRecord.hasMany(_:key:using:)`. + /// + /// - parameters: + /// - destination: The table at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.tableName`. + /// - 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 func hasMany( + _ destination: Table, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + { + HasManyAssociation( + to: destination.relationForAll, + key: key, + using: foreignKey) + } + + /// Creates a "Has one" association between Self and the destination table, + /// based on a database foreign key. + /// + /// For more information, see `TableRecord.hasOne(_:key:using:)`. + /// + /// - parameters: + /// - destination: The table 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 func hasOne( + _ destination: Table, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + { + HasOneAssociation( + to: destination.relationForAll, + key: key, + using: foreignKey) + } +} + +// MARK: - Associations to CommonTableExpression + +extension Table { + /// Creates an association to a common table expression that you can join + /// or include in another request. + /// + /// For more information, see `TableRecord.association(to:on:)`. + /// + /// - parameter cte: A common table expression. + /// - parameter condition: A function that returns the joining clause. + /// - parameter left: A `TableAlias` for the left table. + /// - parameter right: A `TableAlias` for the right table. + /// - returns: An association to the common table expression. + public func association( + to cte: CommonTableExpression, + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + -> JoinAssociation + { + JoinAssociation( + to: cte.relationForAll, + condition: .expression { condition($0, $1).sqlExpression }) + } + + /// Creates an association to a common table expression that you can join + /// or include in another request. + /// + /// The key of the returned association is the table name of the common + /// table expression. + /// + /// - parameter cte: A common table expression. + /// - returns: An association to the common table expression. + public func association( + to cte: CommonTableExpression) + -> JoinAssociation + { + JoinAssociation(to: cte.relationForAll, condition: .none) + } +} + +// MARK: - "Through" Associations + +extension Table { + /// Creates a "Has Many Through" association between Self and the + /// destination type. + /// + /// For more information, see `TableRecord.hasMany(_:through:using:key:)`. + /// + /// - parameters: + /// - destination: The record type at the other side of the association. + /// - pivot: An association from Self to the intermediate type. + /// - target: A target association from the intermediate type to the + /// destination type. + /// - key: An eventual decoding key for the association. By default, it + /// is the same key as the target. + public func hasMany( + _ destination: Target.RowDecoder.Type, + through pivot: Pivot, + using target: Target, + key: String? = nil) + -> HasManyThroughAssociation + where Pivot: Association, + Target: Association, + Pivot.OriginRowDecoder == RowDecoder, + Pivot.RowDecoder == Target.OriginRowDecoder + { + let association = HasManyThroughAssociation( + _sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + + if let key = key { + return association.forKey(key) + } else { + return association + } + } + + /// Creates a "Has One Through" association between Self and the + /// destination type. + /// + /// For more information, see `TableRecord.hasOne(_:through:using:key:)`. + /// + /// - parameters: + /// - destination: The record type at the other side of the association. + /// - pivot: An association from Self to the intermediate type. + /// - target: A target association from the intermediate type to the + /// destination type. + /// - key: An eventual decoding key for the association. By default, it + /// is the same key as the target. + public func hasOne( + _ destination: Target.RowDecoder.Type, + through pivot: Pivot, + using target: Target, + key: String? = nil) + -> HasOneThroughAssociation + where Pivot: AssociationToOne, + Target: AssociationToOne, + Pivot.OriginRowDecoder == RowDecoder, + Pivot.RowDecoder == Target.OriginRowDecoder + { + let association = HasOneThroughAssociation( + _sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + + if let key = key { + return association.forKey(key) + } else { + return association + } + } +} + +// MARK: - Joining Methods + +extension Table { + /// Creates a request that prefetches an association. + public func including(all association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == RowDecoder + { + all().including(all: association) + } + + /// 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 + { + 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 func including(required association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == RowDecoder + { + 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 func joining(optional association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == RowDecoder + { + 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 func joining(required association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == RowDecoder + { + all().joining(required: association) + } +} + +// MARK: - Association Aggregates + +extension Table { + /// Creates a request with *aggregates* appended to the selection. + /// + /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount + /// // FROM player LEFT JOIN book ... + /// let table = Table("player") + /// let request = table.annotated(with: Player.books.count) + public func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { + all().annotated(with: aggregates) + } + + /// Creates a request with *aggregates* appended to the selection. + /// + /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount + /// // FROM player LEFT JOIN book ... + /// let table = Table("player") + /// let request = table.annotated(with: [Player.books.count]) + public func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { + all().annotated(with: aggregates) + } + + /// Creates a request with the provided aggregate *predicate*. + /// + /// // SELECT player.* + /// // FROM player LEFT JOIN book ... + /// // HAVING COUNT(DISTINCT book.id) = 0 + /// let table = Table("player") + /// var request = table.all() + /// request = request.having(Player.books.isEmpty) + /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. + public func having(_ predicate: AssociationAggregate) -> QueryInterfaceRequest { + all().having(predicate) + } +} + +// MARK: - Batch Delete + +extension Table { + /// Deletes all rows; returns the number of deleted rows. + /// + /// - parameter db: A database connection. + /// - returns: The number of deleted rows + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @discardableResult + public func deleteAll(_ db: Database) throws -> Int { + try all().deleteAll(db) + } +} + +// MARK: - Deleting by Single-Column Primary Key + +extension Table { + /// Delete rows identified by their primary keys; returns the number of + /// deleted rows. + /// + /// // DELETE FROM player WHERE id IN (1, 2, 3) + /// try Table("player").deleteAll(db, keys: [1, 2, 3]) + /// + /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') + /// try Table("country").deleteAll(db, keys: ["FR", "US", "DE"]) + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid IN (1, 2, 3) + /// try Table("document").deleteAll(db, keys: [1, 2, 3]) + /// + /// - parameters: + /// - db: A database connection. + /// - keys: A sequence of primary keys. + /// - returns: The number of deleted rows + @discardableResult + public func deleteAll(_ db: Database, keys: Sequence) + throws -> Int + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { + let keys = Array(keys) + if keys.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(keys: keys).deleteAll(db) + } + + /// Delete a row, identified by its primary key; returns whether a + /// database row was deleted. + /// + /// // DELETE FROM player WHERE id = 123 + /// try Table("player").deleteOne(db, key: 123) + /// + /// // DELETE FROM country WHERE code = 'FR' + /// try Table("country").deleteOne(db, key: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid = 1 + /// try Table("document").deleteOne(db, key: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A primary key value. + /// - returns: Whether a database row was deleted. + @discardableResult + public func deleteOne(_ db: Database, key: PrimaryKeyType?) + throws -> Bool + where PrimaryKeyType: DatabaseValueConvertible + { + guard let key = key else { + // Avoid hitting the database + return false + } + return try deleteAll(db, keys: [key]) > 0 + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension Table +where RowDecoder: Identifiable, + RowDecoder.ID: DatabaseValueConvertible +{ + /// Delete rows identified by their primary keys; returns the number of + /// deleted rows. + /// + /// // DELETE FROM player WHERE id IN (1, 2, 3) + /// try Table("player").deleteAll(db, ids: [1, 2, 3]) + /// + /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') + /// try Table("country").deleteAll(db, ids: ["FR", "US", "DE"]) + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid IN (1, 2, 3) + /// try Table("document").deleteAll(db, ids: [1, 2, 3]) + /// + /// - parameters: + /// - db: A database connection. + /// - ids: A collection of primary keys. + /// - returns: The number of deleted rows + @discardableResult + public func deleteAll(_ db: Database, ids: Collection) + throws -> Int + where Collection: Swift.Collection, Collection.Element == RowDecoder.ID + { + if ids.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(ids: ids).deleteAll(db) + } + + /// Delete a row, identified by its primary key; returns whether a + /// database row was deleted. + /// + /// // DELETE FROM player WHERE id = 123 + /// try Player.deleteOne(db, id: 123) + /// + /// // DELETE FROM country WHERE code = 'FR' + /// try Country.deleteOne(db, id: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid = 1 + /// try Document.deleteOne(db, id: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - id: A primary key value. + /// - returns: Whether a database row was deleted. + @discardableResult + public func deleteOne(_ db: Database, id: RowDecoder.ID) throws -> Bool { + try deleteAll(db, ids: [id]) > 0 + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension Table +where RowDecoder: Identifiable, + RowDecoder.ID: _OptionalProtocol, + RowDecoder.ID.Wrapped: DatabaseValueConvertible +{ + /// Delete rows identified by their primary keys; returns the number of + /// deleted rows. + /// + /// // DELETE FROM player WHERE id IN (1, 2, 3) + /// try Table("player").deleteAll(db, ids: [1, 2, 3]) + /// + /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') + /// try Table("country").deleteAll(db, ids: ["FR", "US", "DE"]) + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid IN (1, 2, 3) + /// try Table("document").deleteAll(db, ids: [1, 2, 3]) + /// + /// - parameters: + /// - db: A database connection. + /// - ids: A collection of primary keys. + /// - returns: The number of deleted rows + @discardableResult + public func deleteAll(_ db: Database, ids: Collection) + throws -> Int + where Collection: Swift.Collection, Collection.Element == RowDecoder.ID.Wrapped + { + if ids.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(ids: ids).deleteAll(db) + } + + /// Delete a row, identified by its primary key; returns whether a + /// database row was deleted. + /// + /// // DELETE FROM player WHERE id = 123 + /// try Table("player").deleteOne(db, id: 123) + /// + /// // DELETE FROM country WHERE code = 'FR' + /// try Table("country").deleteOne(db, id: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid = 1 + /// try Table("document").deleteOne(db, id: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - id: A primary key value. + /// - returns: Whether a database row was deleted. + @discardableResult + public func deleteOne(_ db: Database, id: RowDecoder.ID.Wrapped) throws -> Bool { + try deleteAll(db, ids: [id]) > 0 + } +} + +// MARK: - Deleting by Key + +extension Table { + /// Delete rows identified by the provided unique keys (primary key or + /// any key with a unique index on it); returns the number of deleted rows. + /// + /// try Table("player").deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) + /// + /// - parameters: + /// - db: A database connection. + /// - keys: An array of key dictionaries. + /// - returns: The number of deleted rows + @discardableResult + public func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int { + if keys.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(keys: keys).deleteAll(db) + } + + /// Delete a row, identified by a unique key (the primary key or any key + /// with a unique index on it); returns whether a database row was deleted. + /// + /// Table("player").deleteOne(db, key: ["name": Arthur"]) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A dictionary of values. + /// - returns: Whether a database row was deleted. + @discardableResult + public func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + try deleteAll(db, keys: [key]) > 0 + } +} + +// MARK: - Batch Update + +extension Table { + /// Updates all rows; returns the number of updated rows. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try Table("player").updateAll(db, [Column("score").set(to: 0)]) + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: An array of column assignments. + /// - returns: The number of updated rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @discardableResult + public func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignments: [ColumnAssignment]) + throws -> Int + { + try all().updateAll(db, onConflict: conflictResolution, assignments) + } + + /// Updates all rows; returns the number of updated rows. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try Table("player").updateAll(db, Column("score").set(to: 0)) + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignment: A column assignment. + /// - parameter otherAssignments: Eventual other column assignments. + /// - returns: The number of updated rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @discardableResult + public func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignment: ColumnAssignment, + _ otherAssignments: ColumnAssignment...) + throws -> Int + { + try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments) + } +} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 00a1f4f43..dbe6271c0 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -93,7 +93,7 @@ struct SQLQueryGenerator: Refinable { func makePreparedRequest(_ db: Database) throws -> PreparedRequest { try PreparedRequest( - statement: makeSelectStatement(db), + statement: makeStatement(db), adapter: rowAdapter(SQLGenerationContext(db, ctes: relation.ctes))) } @@ -105,14 +105,14 @@ struct SQLQueryGenerator: Refinable { .columnCount(SQLGenerationContext(db, ctes: relation.ctes)) } - /// Returns a select statement - func makeSelectStatement(_ db: Database) throws -> SelectStatement { + /// Returns a prepared statement + func makeStatement(_ db: Database) throws -> Statement { // Build let context = SQLGenerationContext(db) let sql = try requestSQL(context) // Compile & set arguments - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) statement.arguments = context.arguments // Optimize statement region. This allows us to track individual rowids, @@ -197,7 +197,7 @@ struct SQLQueryGenerator: Refinable { return false } - func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { + func makeDeleteStatement(_ db: Database) throws -> Statement { switch try grouping(db) { case .none: guard relation.joins.isEmpty else { @@ -225,7 +225,7 @@ struct SQLQueryGenerator: Refinable { sql += " LIMIT " + limit.sql } - let statement = try db.makeUpdateStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) statement.arguments = context.arguments return statement @@ -239,20 +239,23 @@ struct SQLQueryGenerator: Refinable { } /// DELETE FROM table WHERE id IN (SELECT id FROM table ...) - private func makeTrivialDeleteStatement(_ db: Database) throws -> UpdateStatement { + private func makeTrivialDeleteStatement(_ db: Database) throws -> Statement { let tableName = relation.source.tableName let alias = TableAlias(tableName: tableName) let context = SQLGenerationContext(db, aliases: [alias]) let subqueryContext = context.subqueryContext(aliases: relation.allAliases, ctes: relation.ctes) let primaryKey = SQLExpression.fastPrimaryKey + let selectPrimaryKey = self.with { + $0.relation = $0.relation.selectOnly([.expression(primaryKey)]) + } var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE " sql += try alias[primaryKey].sql(context) sql += " IN (" - sql += try map(\.relation, { $0.selectOnly([.expression(primaryKey)]) }).requestSQL(subqueryContext) + sql += try selectPrimaryKey.requestSQL(subqueryContext) sql += ")" - let statement = try db.makeUpdateStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) statement.arguments = context.arguments return statement } @@ -262,7 +265,7 @@ struct SQLQueryGenerator: Refinable { _ db: Database, conflictResolution: Database.ConflictResolution, assignments: [ColumnAssignment]) - throws -> UpdateStatement? + throws -> Statement? { switch try grouping(db) { case .none: @@ -311,7 +314,7 @@ struct SQLQueryGenerator: Refinable { sql += " LIMIT " + limit.sql } - let statement = try db.makeUpdateStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) statement.arguments = context.arguments return statement @@ -330,7 +333,7 @@ struct SQLQueryGenerator: Refinable { _ db: Database, conflictResolution: Database.ConflictResolution, assignments: [ColumnAssignment]) - throws -> UpdateStatement? + throws -> Statement? { // Check for empty assignments after all programmer errors have // been checked. @@ -343,6 +346,9 @@ struct SQLQueryGenerator: Refinable { let context = SQLGenerationContext(db, aliases: [alias]) let subqueryContext = context.subqueryContext(aliases: relation.allAliases, ctes: relation.ctes) let primaryKey = SQLExpression.fastPrimaryKey + let selectPrimaryKey = self.with { + $0.relation = $0.relation.selectOnly([.expression(primaryKey)]) + } // UPDATE table... var sql = "UPDATE " @@ -361,10 +367,10 @@ struct SQLQueryGenerator: Refinable { sql += " WHERE " sql += try alias[primaryKey].sql(context) sql += " IN (" - sql += try map(\.relation, { $0.selectOnly([.expression(primaryKey)]) }).requestSQL(subqueryContext) + sql += try selectPrimaryKey.requestSQL(subqueryContext) sql += ")" - let statement = try db.makeUpdateStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) statement.arguments = context.arguments return statement } @@ -654,17 +660,18 @@ private struct SQLQualifiedRelation { /// Sets the selection, removes all selections from joins, and clears the /// `isDistinct` flag. func selectOnly(_ selection: [SQLSelection]) -> Self { - let sourceSelectionPromise = DatabasePromise(value: selection.map { + let qualifiedSelection = selection.map { $0.qualified(with: source.alias) - }) - return self - .with(\.sourceSelectionPromise, sourceSelectionPromise) - .with(\.isDistinct, false) - .map(\.joins, { joins in - joins.mapValues { join in - join.map(\.relation) { $0.selectOnly([]) } + } + return with { + $0.sourceSelectionPromise = DatabasePromise(value: qualifiedSelection) + $0.isDistinct = false + $0.joins = $0.joins.mapValues { join in + join.with { + $0.relation = $0.relation.selectOnly([]) } - }) + } + } } } diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 0ed59c289..aee99a78f 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -12,8 +12,8 @@ extension Database { /// t.column("latitude", .double).notNull() /// } /// - /// See https://www.sqlite.org/lang_createtable.html and - /// https://www.sqlite.org/withoutrowid.html + /// See and + /// /// /// - parameters: /// - name: The table name. @@ -44,7 +44,7 @@ extension Database { /// Renames a database table. /// - /// See https://www.sqlite.org/lang_altertable.html + /// See /// /// - throws: A DatabaseError whenever an SQLite error occurs. public func rename(table name: String, to newName: String) throws { @@ -57,7 +57,7 @@ extension Database { /// t.add(column: "url", .text) /// } /// - /// See https://www.sqlite.org/lang_altertable.html + /// See /// /// - parameters: /// - name: The table name. @@ -72,7 +72,7 @@ extension Database { /// Deletes a database table. /// - /// See https://www.sqlite.org/lang_droptable.html + /// See /// /// - throws: A DatabaseError whenever an SQLite error occurs. public func drop(table name: String) throws { @@ -89,7 +89,7 @@ extension Database { /// /// try db.execute(sql: "CREATE INDEX ...") /// - /// See https://www.sqlite.org/lang_createindex.html + /// See /// /// - parameters: /// - name: The index name. @@ -98,7 +98,7 @@ extension Database { /// - unique: If true, creates a unique index. /// - ifNotExists: If false, no error is thrown if index already exists. /// - condition: If not nil, creates a partial index - /// (see https://www.sqlite.org/partialindex.html). + /// (see ). public func create( index name: String, on table: String, @@ -121,7 +121,7 @@ extension Database { /// Deletes a database index. /// - /// See https://www.sqlite.org/lang_dropindex.html + /// See /// /// - throws: A DatabaseError whenever an SQLite error occurs. public func drop(index name: String) throws { @@ -133,7 +133,7 @@ extension Database { /// This method is useful when the definition of a collation sequence /// has changed. /// - /// See https://www.sqlite.org/lang_reindex.html + /// See /// /// - throws: A DatabaseError whenever an SQLite error occurs. public func reindex(collation: Database.CollationName) throws { @@ -145,7 +145,7 @@ extension Database { /// This method is useful when the definition of a collation sequence /// has changed. /// - /// See https://www.sqlite.org/lang_reindex.html + /// See /// /// - throws: A DatabaseError whenever an SQLite error occurs. public func reindex(collation: DatabaseCollation) throws { @@ -162,7 +162,7 @@ extension Database { /// t.column(...) /// } /// -/// See https://www.sqlite.org/lang_createtable.html +/// See public final class TableDefinition { private typealias KeyConstraint = ( columns: [String], @@ -238,11 +238,11 @@ public final class TableDefinition { /// 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 + /// See and + /// /// /// - parameter conflictResolution: An optional conflict resolution - /// (see https://www.sqlite.org/lang_conflict.html). + /// (see ). /// - returns: Self so that you can further refine the column definition. @discardableResult public func autoIncrementedPrimaryKey( @@ -259,7 +259,7 @@ public final class TableDefinition { /// t.column("name", .text) /// } /// - /// See https://www.sqlite.org/lang_createtable.html#tablecoldef + /// See /// /// - parameter name: the column name. /// - parameter type: the eventual column type. @@ -305,12 +305,12 @@ public final class TableDefinition { /// t.primaryKey(["citizenID", "countryCode"]) /// } /// - /// See https://www.sqlite.org/lang_createtable.html#primkeyconst and - /// https://www.sqlite.org/lang_createtable.html#rowid + /// See and + /// /// /// - parameter columns: The primary key columns. /// - parameter conflictResolution: An optional conflict resolution - /// (see https://www.sqlite.org/lang_conflict.html). + /// (see ). public func primaryKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil) { guard primaryKeyConstraint == nil else { // Programmer error @@ -327,11 +327,11 @@ public final class TableDefinition { /// t.uniqueKey(["latitude", "longitude"]) /// } /// - /// See https://www.sqlite.org/lang_createtable.html#uniqueconst + /// See /// /// - parameter columns: The unique key columns. /// - parameter conflictResolution: An optional conflict resolution - /// (see https://www.sqlite.org/lang_conflict.html). + /// (see ). public func uniqueKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil) { uniqueKeyConstraints.append((columns: columns, conflictResolution: conflictResolution)) } @@ -345,7 +345,7 @@ public final class TableDefinition { /// t.foreignKey(["citizenID", "countryCode"], references: "citizenship", onDelete: .cascade) /// } /// - /// See https://www.sqlite.org/foreignkeys.html + /// See /// /// - parameters: /// - columns: The foreign key columns. @@ -356,7 +356,7 @@ public final class TableDefinition { /// - deleteAction: Optional action when the referenced row is deleted. /// - updateAction: Optional action when the referenced row is updated. /// - deferred: If true, defines a deferred foreign key constraint. - /// See https://www.sqlite.org/foreignkeys.html#fk_deferred. + /// See . public func foreignKey( _ columns: [String], references table: String, @@ -384,7 +384,7 @@ public final class TableDefinition { /// t.check(personalPhone != nil || workPhone != nil) /// } /// - /// See https://www.sqlite.org/lang_createtable.html#ckconst + /// See /// /// - parameter condition: The checked condition public func check(_ condition: SQLExpressible) { @@ -399,7 +399,7 @@ public final class TableDefinition { /// t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL") /// } /// - /// See https://www.sqlite.org/lang_createtable.html#ckconst + /// See /// /// - parameter sql: An SQL snippet public func check(sql: String) { @@ -572,7 +572,7 @@ public final class TableDefinition { /// t.add(column: ...) /// } /// -/// See https://www.sqlite.org/lang_altertable.html +/// See public final class TableAlteration { private let name: String @@ -594,7 +594,7 @@ public final class TableAlteration { /// t.add(column: "url", .text) /// } /// - /// See https://www.sqlite.org/lang_altertable.html + /// See /// /// - parameter name: the column name. /// - parameter type: the column type. @@ -638,7 +638,7 @@ public final class TableAlteration { /// t.rename(column: "url", to: "homeURL") /// } /// - /// See https://www.sqlite.org/lang_altertable.html + /// See /// /// - parameter name: the column name to rename. /// - parameter newName: the new name of the column. @@ -652,7 +652,7 @@ public final class TableAlteration { /// t.rename(column: "url", to: "homeURL") /// } /// - /// See https://www.sqlite.org/lang_altertable.html + /// See /// /// - parameter name: the column name to rename. /// - parameter newName: the new name of the column. @@ -723,8 +723,8 @@ public final class TableAlteration { /// t.add(column: ...) // ColumnDefinition /// } /// -/// See https://www.sqlite.org/lang_createtable.html and -/// https://www.sqlite.org/lang_altertable.html +/// See and +/// public final class ColumnDefinition { enum Index { case none @@ -743,7 +743,7 @@ public final class ColumnDefinition { /// The `GeneratedColumnQualification` enum defines whether a generated /// column sis virtual or stored. /// - /// See https://sqlite.org/gencol.html#virtual_versus_stored_columns + /// See public enum GeneratedColumnQualification { case virtual case stored @@ -776,12 +776,12 @@ public final class ColumnDefinition { /// t.column("id", .integer).primaryKey() /// } /// - /// See https://www.sqlite.org/lang_createtable.html#primkeyconst and - /// https://www.sqlite.org/lang_createtable.html#rowid + /// See and + /// /// /// - parameters: /// - conflictResolution: An optional conflict resolution - /// (see https://www.sqlite.org/lang_conflict.html). + /// (see ). /// - autoincrement: If true, the primary key is autoincremented. /// - returns: Self so that you can further refine the column definition. @discardableResult @@ -800,10 +800,10 @@ public final class ColumnDefinition { /// t.column("name", .text).notNull() /// } /// - /// See https://www.sqlite.org/lang_createtable.html#notnullconst + /// See /// /// - parameter conflictResolution: An optional conflict resolution - /// (see https://www.sqlite.org/lang_conflict.html). + /// (see ). /// - returns: Self so that you can further refine the column definition. @discardableResult public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { @@ -817,10 +817,10 @@ public final class ColumnDefinition { /// t.column("email", .text).unique() /// } /// - /// See https://www.sqlite.org/lang_createtable.html#uniqueconst + /// See /// /// - parameter conflictResolution: An optional conflict resolution - /// (see https://www.sqlite.org/lang_conflict.html). + /// (see ). /// - returns: Self so that you can further refine the column definition. @discardableResult public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { @@ -834,7 +834,7 @@ public final class ColumnDefinition { /// t.column("email", .text).indexed() /// } /// - /// See https://www.sqlite.org/lang_createtable.html#uniqueconst + /// See /// /// - returns: Self so that you can further refine the column definition. @discardableResult @@ -851,7 +851,7 @@ public final class ColumnDefinition { /// t.column("name", .text).check { length($0) > 0 } /// } /// - /// See https://www.sqlite.org/lang_createtable.html#ckconst + /// See /// /// - parameter condition: A closure whose argument is an Column that /// represents the defined column, and returns the expression to check. @@ -868,7 +868,7 @@ public final class ColumnDefinition { /// t.column("name", .text).check(sql: "LENGTH(name) > 0") /// } /// - /// See https://www.sqlite.org/lang_createtable.html#ckconst + /// See /// /// - parameter sql: An SQL snippet. /// - returns: Self so that you can further refine the column definition. @@ -884,7 +884,7 @@ public final class ColumnDefinition { /// t.column("name", .text).defaults(to: "Anonymous") /// } /// - /// See https://www.sqlite.org/lang_createtable.html#dfltval + /// See /// /// - parameter value: A DatabaseValueConvertible value. /// - returns: Self so that you can further refine the column definition. @@ -900,7 +900,7 @@ public final class ColumnDefinition { /// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP") /// } /// - /// See https://www.sqlite.org/lang_createtable.html#dfltval + /// See /// /// - parameter sql: An SQL snippet. /// - returns: Self so that you can further refine the column definition. @@ -916,7 +916,7 @@ public final class ColumnDefinition { /// t.column("email", .text).collate(.nocase) /// } /// - /// See https://www.sqlite.org/datatype3.html#collation + /// See /// /// - parameter collation: An Database.CollationName. /// - returns: Self so that you can further refine the column definition. @@ -932,7 +932,7 @@ public final class ColumnDefinition { /// t.column("name", .text).collate(.localizedCaseInsensitiveCompare) /// } /// - /// See https://www.sqlite.org/datatype3.html#collation + /// See /// /// - parameter collation: A custom DatabaseCollation. /// - returns: Self so that you can further refine the column definition. @@ -952,7 +952,7 @@ public final class ColumnDefinition { /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus", .stored) /// } /// - /// See https://sqlite.org/gencol.html. Note particularly the limitations of + /// See . Note particularly the limitations of /// generated columns, e.g. they may not have a default value. /// /// - parameters: @@ -982,7 +982,7 @@ public final class ColumnDefinition { /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"), .stored) /// } /// - /// See https://sqlite.org/gencol.html. Note particularly the limitations of + /// See . Note particularly the limitations of /// generated columns, e.g. they may not have a default value. /// /// - parameters: @@ -1009,7 +1009,7 @@ public final class ColumnDefinition { /// t.column("authorId", .integer).references("author", onDelete: .cascade) /// } /// - /// See https://www.sqlite.org/foreignkeys.html + /// See /// /// - parameters /// - table: The referenced table. @@ -1018,7 +1018,7 @@ public final class ColumnDefinition { /// - deleteAction: Optional action when the referenced row is deleted. /// - updateAction: Optional action when the referenced row is updated. /// - deferred: If true, defines a deferred foreign key constraint. - /// See https://www.sqlite.org/foreignkeys.html#fk_deferred. + /// See . /// - returns: Self so that you can further refine the column definition. @discardableResult public func references( diff --git a/GRDB/QueryInterface/Schema/VirtualTableModule.swift b/GRDB/QueryInterface/Schema/VirtualTableModule.swift index 68299bce4..4907d8342 100644 --- a/GRDB/QueryInterface/Schema/VirtualTableModule.swift +++ b/GRDB/QueryInterface/Schema/VirtualTableModule.swift @@ -21,14 +21,26 @@ public protocol VirtualTableModule { /// The name of the module. var moduleName: String { get } + // TODO: remove this requirement /// Returns a table definition that is passed as the closure argument in the /// `Database.create(virtualTable:using:)` method: /// /// try db.create(virtualTable: "item", using: module) { t in /// // t is the result of makeTableDefinition() /// } + /// + /// - warning: This method is DEPRECATED. Define + /// `makeTableDefinition(configuration:)` instead. func makeTableDefinition() -> TableDefinition + /// Returns a table definition that is passed as the closure argument in the + /// `Database.create(virtualTable:using:)` method: + /// + /// try db.create(virtualTable: "item", using: module) { t in + /// // t is the result of makeTableDefinition(configuration:) + /// } + func makeTableDefinition(configuration: VirtualTableConfiguration) -> TableDefinition + /// Returns the module arguments for the `CREATE VIRTUAL TABLE` query. func moduleArguments(for definition: TableDefinition, in db: Database) throws -> [String] @@ -37,6 +49,20 @@ public protocol VirtualTableModule { func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws } +extension VirtualTableModule { + // Support for VirtualTableModule types defined by users + // TODO: remove when `makeTableDefinition()` is no longer a requirement + public func makeTableDefinition(configuration: VirtualTableConfiguration) -> TableDefinition { + makeTableDefinition() + } +} + +public struct VirtualTableConfiguration { + /// If true, existing objects must not be replaced, or generate any error + /// (even if they do not match the objects that would be created otherwise.) + var ifNotExists: Bool +} + extension Database { // MARK: - Database Schema @@ -45,7 +71,7 @@ extension Database { /// /// try db.create(virtualTable: "vocabulary", using: "spellfix1") /// - /// See https://www.sqlite.org/lang_createtable.html + /// See /// /// - parameters: /// - name: The table name. @@ -86,7 +112,7 @@ extension Database { /// t.column("body") /// } /// - /// See https://www.sqlite.org/lang_createtable.html + /// See /// /// - parameters: /// - name: The table name. @@ -104,7 +130,8 @@ extension Database { throws { // Define virtual table - let definition = module.makeTableDefinition() + let configuration = VirtualTableConfiguration(ifNotExists: ifNotExists) + let definition = module.makeTableDefinition(configuration: configuration) if let body = body { body(definition) } diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index def776476..7c2fdaee6 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -209,6 +209,91 @@ extension TableRecord { } } +// MARK: - Associations to Table + +extension TableRecord { + /// Creates a "Belongs To" association between Self and the destination + /// table, based on a database foreign key. + /// + /// For more information, see `TableRecord.belongsTo(_:key:using:)` where + /// the first argument is `TableRecord`. + /// + /// - parameters: + /// - destination: The table at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.tableName`. + /// - 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: Table, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + { + BelongsToAssociation( + to: destination.relationForAll, + key: key, + using: foreignKey) + } + + /// Creates a "Has many" association between Self and the destination table, + /// based on a database foreign key. + /// + /// For more information, see `TableRecord.hasMany(_:key:using:)` where + /// the first argument is `TableRecord`. + /// + /// - parameters: + /// - destination: The table at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.tableName`. + /// - 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: Table, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + { + HasManyAssociation( + to: destination.relationForAll, + key: key, + using: foreignKey) + } + + /// Creates a "Has one" association between Self and the destination table, + /// based on a database foreign key. + /// + /// For more information, see `TableRecord.hasOne(_:key:using:)` where + /// the first argument is `TableRecord`. + /// + /// - parameters: + /// - destination: The table 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: Table, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + { + HasOneAssociation( + to: destination.relationForAll, + key: key, + using: foreignKey) + } +} + // MARK: - Associations to CommonTableExpression extension TableRecord { @@ -351,7 +436,7 @@ extension TableRecord { Pivot.RowDecoder == Target.OriginRowDecoder { let association = HasManyThroughAssociation( - sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + _sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) if let key = key { return association.forKey(key) @@ -433,7 +518,7 @@ extension TableRecord { Pivot.RowDecoder == Target.OriginRowDecoder { let association = HasOneThroughAssociation( - sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + _sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) if let key = key { return association.forKey(key) @@ -471,14 +556,14 @@ extension TableRecord where Self: EncodableRecord { case let .foreignKey(foreignKey): let destinationRelation = association ._sqlAssociation - .map(\.pivot.relation, { pivotRelation in - pivotRelation.filter { db in + .with { + $0.pivot.relation = $0.pivot.relation.filter { db in // Filter the pivot on self try foreignKey .joinMapping(db, from: Self.databaseTableName) .joinExpression(leftRows: [PersistenceContainer(db, self)]) } - }) + } .destinationRelation() return QueryInterfaceRequest(relation: destinationRelation) } @@ -544,7 +629,7 @@ extension TableRecord { /// /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount /// // FROM player LEFT JOIN book ... - /// var request = Player.annotated(with: Player.books.count) + /// let request = Player.annotated(with: Player.books.count) public static func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { all().annotated(with: aggregates) } @@ -553,7 +638,7 @@ extension TableRecord { /// /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount /// // FROM player LEFT JOIN book ... - /// var request = Player.annotated(with: [Player.books.count]) + /// let request = Player.annotated(with: [Player.books.count]) public static func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { all().annotated(with: aggregates) } diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 30676c8be..78ce4f920 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -133,7 +133,7 @@ extension TableRecord { /// Creates a request which appends *selection*. /// /// // SELECT id, email, name FROM player - /// le request = Player + /// let request = Player /// .select([Column("id"), Column("email")]) /// .annotated(with: [Column("name")]) public static func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { @@ -143,7 +143,7 @@ extension TableRecord { /// Creates a request which appends *selection*. /// /// // SELECT id, email, name FROM player - /// le request = Player + /// let request = Player /// .select([Column("id"), Column("email")]) /// .annotated(with: Column("name")) public static func annotated(with selection: SQLSelectable...) -> QueryInterfaceRequest { @@ -380,6 +380,14 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { { all().filter(ids: ids) } + + /// Creates a request which selects the primary key. + /// + /// // SELECT id FROM player + /// let request = try Player.selectID() + public static func selectID() -> QueryInterfaceRequest { + all().selectID() + } } @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) @@ -406,4 +414,12 @@ extension TableRecord where Self: Identifiable, ID: _OptionalProtocol, ID.Wrappe { all().filter(ids: ids) } + + /// Creates a request which selects the primary key. + /// + /// // SELECT id FROM player + /// let request = try Player.selectID() + public static func selectID() -> QueryInterfaceRequest { + all().selectID() + } } diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index 0e511bc40..e61e57e4e 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -88,7 +88,7 @@ private class RecordEncoder: Encoder { func encodeIfPresent(_ value: Float?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Double?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: String?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } - // swiftlint:disable comma + // swiftlint:enable comma func encodeIfPresent(_ value: T?, forKey key: Key) throws where T: Encodable { if let value = value { @@ -182,20 +182,24 @@ private class ColumnEncoder: Encoder { } func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { - // Keyed values require JSON encoding: we need to throw - // JSONRequiredError. Since we can't throw right from here, let's - // delegate the job to a dedicated container. + // We need to perform JSON encoding. Unfortunately we can't access the + // inner container of Foundation's JSONEncoder. At this point we must + // throw an error so that the caller can retry encoding from scratch. + // Unfortunately (bis), we can't throw right from here, so let's + // return a JSONRequiredEncoder that will throw as soon as possible. requiresJSON = true - let container = JSONRequiredEncoder.KeyedContainer(codingPath: codingPath) + let container = JSONRequiredEncoder.KeyedContainer(codingPath: codingPath) return KeyedEncodingContainer(container) } func unkeyedContainer() -> UnkeyedEncodingContainer { - // Keyed values require JSON encoding: we need to throw - // JSONRequiredError. Since we can't throw right from here, let's - // delegate the job to a dedicated container. + // We need to perform JSON encoding. Unfortunately we can't access the + // inner container of Foundation's JSONEncoder. At this point we must + // throw an error so that the caller can retry encoding from scratch. + // Unfortunately (bis), we can't throw right from here, so let's + // return a JSONRequiredEncoder that will throw as soon as possible. requiresJSON = true - return JSONRequiredEncoder(codingPath: codingPath) + return JSONRequiredEncoder(codingPath: codingPath) } func singleValueContainer() -> SingleValueEncodingContainer { self } @@ -224,105 +228,6 @@ extension ColumnEncoder: SingleValueEncodingContainer { } } -// MARK: - JSONRequiredEncoder - -/// The error that triggers JSON encoding -private struct JSONRequiredError: Error { } - -/// The encoder that always ends up with a JSONRequiredError -private struct JSONRequiredEncoder: Encoder { - var codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } - - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { - let container = KeyedContainer(codingPath: codingPath) - return KeyedEncodingContainer(container) - } - - func unkeyedContainer() -> UnkeyedEncodingContainer { self } - - func singleValueContainer() -> SingleValueEncodingContainer { self } - - struct KeyedContainer: KeyedEncodingContainerProtocol { - var codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } - - func encodeNil(forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: Bool, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: Int, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: Int8, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: Int16, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: Int32, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: Int64, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: UInt, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: UInt8, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: UInt16, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: UInt32, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: UInt64, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() } - - func nestedContainer( - keyedBy keyType: NestedKey.Type, - forKey key: KeyType) - -> KeyedEncodingContainer - where NestedKey: CodingKey - { - let container = KeyedContainer(codingPath: codingPath + [key]) - return KeyedEncodingContainer(container) - } - - func nestedUnkeyedContainer(forKey key: KeyType) -> UnkeyedEncodingContainer { - JSONRequiredEncoder(codingPath: codingPath) - } - - func superEncoder() -> Encoder { - JSONRequiredEncoder(codingPath: codingPath) - } - - func superEncoder(forKey key: KeyType) -> Encoder { - JSONRequiredEncoder(codingPath: codingPath) - } - } -} - -extension JSONRequiredEncoder: SingleValueEncodingContainer { - func encodeNil() throws { throw JSONRequiredError() } - func encode(_ value: Bool ) throws { throw JSONRequiredError() } - func encode(_ value: Int ) throws { throw JSONRequiredError() } - func encode(_ value: Int8 ) throws { throw JSONRequiredError() } - func encode(_ value: Int16 ) throws { throw JSONRequiredError() } - func encode(_ value: Int32 ) throws { throw JSONRequiredError() } - func encode(_ value: Int64 ) throws { throw JSONRequiredError() } - func encode(_ value: UInt ) throws { throw JSONRequiredError() } - func encode(_ value: UInt8 ) throws { throw JSONRequiredError() } - func encode(_ value: UInt16) throws { throw JSONRequiredError() } - func encode(_ value: UInt32) throws { throw JSONRequiredError() } - func encode(_ value: UInt64) throws { throw JSONRequiredError() } - func encode(_ value: Float ) throws { throw JSONRequiredError() } - func encode(_ value: Double) throws { throw JSONRequiredError() } - func encode(_ value: String) throws { throw JSONRequiredError() } - func encode(_ value: T) throws where T: Encodable { throw JSONRequiredError() } -} - -extension JSONRequiredEncoder: UnkeyedEncodingContainer { - var count: Int { 0 } - - mutating func nestedContainer(keyedBy keyType: NestedKey.Type) - -> KeyedEncodingContainer - where NestedKey: CodingKey - { - let container = KeyedContainer(codingPath: codingPath) - return KeyedEncodingContainer(container) - } - - mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self } - - mutating func superEncoder() -> Encoder { self } -} - @available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private var iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 68a4d84b9..ae96ce03e 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -396,9 +396,6 @@ extension ColumnDecoder: SingleValueDecodingContainer { } } -/// The error that triggers JSON decoding -private struct JSONRequiredError: Error { } - @available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private var iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index d048ed6bb..1dae5ad2d 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -45,7 +45,7 @@ extension FetchableRecord where Self: TableRecord { /// The first found record. /// - /// // SELECT * FROM player + /// // SELECT * FROM player LIMIT 1 /// let player = try Player.fetchOne(db) // Player? /// /// The selection defaults to all columns. This default can be changed for diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 075f15363..73213ca42 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -12,7 +12,7 @@ import Foundation /// try Player.fetchAll(db, sql: "SELECT ...", arguments:...) // [Player] /// try Player.fetchOne(db, sql: "SELECT ...", arguments:...) // Player? /// -/// let statement = try db.makeSelectStatement(sql: "SELECT ...") +/// let statement = try db.makeStatement(sql: "SELECT ...") /// try Player.fetchCursor(statement, arguments:...) // Cursor of Player /// try Player.fetchAll(statement, arguments:...) // [Player] /// try Player.fetchOne(statement, arguments:...) // Player? @@ -131,11 +131,11 @@ extension FetchableRecord { extension FetchableRecord { - // MARK: Fetching From SelectStatement + // MARK: Fetching From Prepared Statement /// A cursor over records fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player") + /// let statement = try db.makeStatement(sql: "SELECT * FROM player") /// let players = try Player.fetchCursor(statement) // Cursor of Player /// while let player = try players.next() { // Player /// ... @@ -153,7 +153,7 @@ extension FetchableRecord { /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor @@ -163,7 +163,7 @@ extension FetchableRecord { /// Returns an array of records fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player") + /// let statement = try db.makeStatement(sql: "SELECT * FROM player") /// let players = try Player.fetchAll(statement) // [Player] /// /// - parameters: @@ -173,7 +173,7 @@ extension FetchableRecord { /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] @@ -183,7 +183,7 @@ extension FetchableRecord { /// Returns a single record fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player") + /// let statement = try db.makeStatement(sql: "SELECT * FROM player") /// let player = try Player.fetchOne(statement) // Player? /// /// - parameters: @@ -193,7 +193,7 @@ extension FetchableRecord { /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? @@ -205,7 +205,7 @@ extension FetchableRecord { extension FetchableRecord where Self: Hashable { /// Returns a set of records fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player") + /// let statement = try db.makeStatement(sql: "SELECT * FROM player") /// let players = try Player.fetchSet(statement) // Set /// /// - parameters: @@ -215,7 +215,7 @@ extension FetchableRecord where Self: Hashable { /// - returns: A set of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchSet( - _ statement: SelectStatement, + _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Set @@ -494,22 +494,29 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable { /// let players: RecordCursor = try Player.fetchCursor(db, sql: "SELECT * FROM player") /// } public final class RecordCursor: Cursor { - @usableFromInline let _statement: SelectStatement + @usableFromInline enum _State { + case idle, busy, done, failed + } + + @usableFromInline let _statement: Statement @usableFromInline let _row: Row // Reused for performance @usableFromInline let _sqliteStatement: SQLiteStatement - @usableFromInline var _done = false + @usableFromInline var _state = _State.idle - init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { _statement = statement _row = try Row(statement: statement).adapted(with: adapter, layout: statement) _sqliteStatement = statement.sqliteStatement - _statement.reset(withArguments: arguments) - // Assume cursor is created for iteration - try statement.database.selectStatementWillExecute(statement) + // Assume cursor is created for immediate iteration: reset and set arguments + statement.reset(withArguments: arguments) } deinit { + if _state == .busy { + try? _statement.database.statementDidExecute(_statement) + } + // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. try? _statement.reset() @@ -517,19 +524,34 @@ public final class RecordCursor: Cursor { @inlinable public func next() throws -> Record? { - if _done { + switch _state { + case .done: // make sure this instance never yields a value again, even if the // statement is reset by another cursor. return nil + case .idle: + guard try _statement.database.statementWillExecute(_statement) == nil else { + throw DatabaseError( + resultCode: SQLITE_MISUSE, + message: "Can't run statement that requires a customized authorizer from a cursor", + sql: _statement.sql, + arguments: _statement.arguments) + } + _state = .busy + default: + break } + switch sqlite3_step(_sqliteStatement) { case SQLITE_DONE: - _done = true + _state = .done + try _statement.database.statementDidExecute(_statement) return nil case SQLITE_ROW: return Record(row: _row) case let code: - try _statement.didFail(withResultCode: code) + _state = .failed + try _statement.database.statementDidFail(_statement, withResultCode: code) } } } diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 85535feac..782b49fb1 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -38,7 +38,7 @@ extension PersistenceError { /// /// See `MutablePersistableRecord.persistenceConflictPolicy`. /// -/// See https://www.sqlite.org/lang_conflict.html +/// See public struct PersistenceConflictPolicy { /// The conflict resolution algorithm for insertions public let conflictResolutionForInsert: Database.ConflictResolution @@ -67,7 +67,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// `didInsert(with:for:)` method is not called upon successful insertion, /// even if a row was actually inserted without any conflict. /// - /// See https://www.sqlite.org/lang_conflict.html + /// See static var persistenceConflictPolicy: PersistenceConflictPolicy { get } /// Notifies the record that it was successfully inserted. @@ -504,305 +504,6 @@ extension MutablePersistableRecord where Self: AnyObject { } } -extension MutablePersistableRecord { - - // MARK: Batch Delete - - /// Deletes all records; returns the number of deleted rows. - /// - /// - parameter db: A database connection. - /// - returns: The number of deleted rows - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @discardableResult - public static func deleteAll(_ db: Database) throws -> Int { - try all().deleteAll(db) - } - - // MARK: Batch Update - - /// Updates all records; returns the number of updated records. - /// - /// For example: - /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = 0 - /// try Player.updateAll(db, [Column("score").set(to: 0)]) - /// } - /// - /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution, - /// defaulting to the record's persistenceConflictPolicy. - /// - parameter assignments: An array of column assignments. - /// - returns: The number of updated rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @discardableResult - public static func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, - _ assignments: [ColumnAssignment]) - throws -> Int - { - try all().updateAll(db, onConflict: conflictResolution, assignments) - } - - /// Updates all records; returns the number of updated records. - /// - /// For example: - /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = 0 - /// try Player.updateAll(db, Column("score").set(to: 0)) - /// } - /// - /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution, - /// defaulting to the record's persistenceConflictPolicy. - /// - parameter assignment: A column assignment. - /// - parameter otherAssignments: Eventual other column assignments. - /// - returns: The number of updated rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @discardableResult - public static func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, - _ assignment: ColumnAssignment, - _ otherAssignments: ColumnAssignment...) - throws -> Int - { - try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments) - } -} - -extension MutablePersistableRecord { - - // MARK: - Deleting by Single-Column Primary Key - - /// Delete records identified by their primary keys; returns the number of - /// deleted rows. - /// - /// // DELETE FROM player WHERE id IN (1, 2, 3) - /// try Player.deleteAll(db, keys: [1, 2, 3]) - /// - /// // 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 document WHERE rowid IN (1, 2, 3) - /// try Document.deleteAll(db, keys: [1, 2, 3]) - /// - /// - parameters: - /// - db: A database connection. - /// - keys: A sequence of primary keys. - /// - returns: The number of deleted rows - @discardableResult - public static func deleteAll(_ db: Database, keys: Sequence) - throws -> Int - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible - { - let keys = Array(keys) - if keys.isEmpty { - // Avoid hitting the database - return 0 - } - return try filter(keys: keys).deleteAll(db) - } - - /// Delete a record, identified by its primary key; returns whether a - /// database row was deleted. - /// - /// // DELETE FROM player WHERE id = 123 - /// try Player.deleteOne(db, key: 123) - /// - /// // 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 document WHERE rowid = 1 - /// try Document.deleteOne(db, key: 1) - /// - /// - parameters: - /// - db: A database connection. - /// - key: A primary key value. - /// - returns: Whether a database row was deleted. - @discardableResult - public static func deleteOne(_ db: Database, key: PrimaryKeyType?) - throws -> Bool - where PrimaryKeyType: DatabaseValueConvertible - { - guard let key = key else { - // Avoid hitting the database - return false - } - return try deleteAll(db, keys: [key]) > 0 - } -} - -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) -extension MutablePersistableRecord where Self: Identifiable, ID: DatabaseValueConvertible { - - // MARK: - Deleting by Single-Column Primary Key - - /// Delete records identified by their primary keys; returns the number of - /// deleted rows. - /// - /// // DELETE FROM player WHERE id IN (1, 2, 3) - /// try Player.deleteAll(db, ids: [1, 2, 3]) - /// - /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') - /// try Country.deleteAll(db, ids: ["FR", "US", "DE"]) - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid IN (1, 2, 3) - /// try Document.deleteAll(db, ids: [1, 2, 3]) - /// - /// - parameters: - /// - db: A database connection. - /// - ids: A collection of primary keys. - /// - returns: The number of deleted rows - @discardableResult - public static func deleteAll(_ db: Database, ids: Collection) - throws -> Int - where Collection: Swift.Collection, Collection.Element == ID - { - if ids.isEmpty { - // Avoid hitting the database - return 0 - } - return try filter(ids: ids).deleteAll(db) - } - - /// Delete a record, identified by its primary key; returns whether a - /// database row was deleted. - /// - /// // DELETE FROM player WHERE id = 123 - /// try Player.deleteOne(db, key: 123) - /// - /// // 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 document WHERE rowid = 1 - /// try Document.deleteOne(db, key: 1) - /// - /// - parameters: - /// - db: A database connection. - /// - id: A primary key value. - /// - returns: Whether a database row was deleted. - @discardableResult - public static func deleteOne(_ db: Database, id: ID) throws -> Bool { - try deleteAll(db, ids: [id]) > 0 - } -} - -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) -extension MutablePersistableRecord -where Self: Identifiable, - ID: _OptionalProtocol, - ID.Wrapped: DatabaseValueConvertible -{ - // MARK: - Deleting by Single-Column Primary Key - - /// Delete records identified by their primary keys; returns the number of - /// deleted rows. - /// - /// // DELETE FROM player WHERE id IN (1, 2, 3) - /// try Player.deleteAll(db, ids: [1, 2, 3]) - /// - /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') - /// try Country.deleteAll(db, ids: ["FR", "US", "DE"]) - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid IN (1, 2, 3) - /// try Document.deleteAll(db, ids: [1, 2, 3]) - /// - /// - parameters: - /// - db: A database connection. - /// - ids: A collection of primary keys. - /// - returns: The number of deleted rows - @discardableResult - public static func deleteAll(_ db: Database, ids: Collection) - throws -> Int - where Collection: Swift.Collection, Collection.Element == ID.Wrapped - { - if ids.isEmpty { - // Avoid hitting the database - return 0 - } - return try filter(ids: ids).deleteAll(db) - } - - /// Delete a record, identified by its primary key; returns whether a - /// database row was deleted. - /// - /// // DELETE FROM player WHERE id = 123 - /// try Player.deleteOne(db, key: 123) - /// - /// // 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 document WHERE rowid = 1 - /// try Document.deleteOne(db, key: 1) - /// - /// - parameters: - /// - db: A database connection. - /// - id: A primary key value. - /// - returns: Whether a database row was deleted. - @discardableResult - public static func deleteOne(_ db: Database, id: ID.Wrapped) throws -> Bool { - try deleteAll(db, ids: [id]) > 0 - } -} - -extension MutablePersistableRecord { - - // MARK: - Deleting by Key - - /// Delete records identified by the provided unique keys (primary key or - /// any key with a unique index on it); returns the number of deleted rows. - /// - /// try Player.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) - /// - /// - parameters: - /// - db: A database connection. - /// - keys: An array of key dictionaries. - /// - returns: The number of deleted rows - @discardableResult - public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int { - if keys.isEmpty { - // Avoid hitting the database - return 0 - } - return try filter(keys: keys).deleteAll(db) - } - - /// Delete a record, identified by a unique key (the primary key or any key - /// with a unique index on it); returns whether a database row was deleted. - /// - /// Player.deleteOne(db, key: ["name": Arthur"]) - /// - /// - parameters: - /// - db: A database connection. - /// - key: A dictionary of values. - /// - returns: Whether a database row was deleted. - @discardableResult - public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { - try deleteAll(db, keys: [key]) > 0 - } -} - // MARK: - PersistableRecord /// Types that adopt `PersistableRecord` can be inserted, updated, and deleted. @@ -976,19 +677,19 @@ final class DAO { } @usableFromInline - func insertStatement(onConflict: Database.ConflictResolution) throws -> UpdateStatement { + func insertStatement(onConflict: Database.ConflictResolution) throws -> Statement { let query = InsertQuery( onConflict: onConflict, tableName: databaseTableName, insertedColumns: persistenceContainer.columns) - let statement = try db.internalCachedUpdateStatement(sql: query.sql) + let statement = try db.internalCachedStatement(sql: query.sql) statement.setUncheckedArguments(StatementArguments(persistenceContainer.values)) return statement } /// Returns nil if and only if primary key is nil @usableFromInline - func updateStatement(columns: Set, onConflict: Database.ConflictResolution) throws -> UpdateStatement? { + func updateStatement(columns: Set, onConflict: Database.ConflictResolution) throws -> Statement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { @@ -1031,14 +732,14 @@ final class DAO { tableName: databaseTableName, updatedColumns: updatedColumns, conditionColumns: primaryKeyColumns) - let statement = try db.internalCachedUpdateStatement(sql: query.sql) + let statement = try db.internalCachedStatement(sql: query.sql) statement.setUncheckedArguments(StatementArguments(updatedValues + primaryKeyValues)) return statement } /// Returns nil if and only if primary key is nil @usableFromInline - func deleteStatement() throws -> UpdateStatement? { + func deleteStatement() throws -> Statement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { @@ -1051,14 +752,14 @@ final class DAO { let query = DeleteQuery( tableName: databaseTableName, conditionColumns: primaryKeyColumns) - let statement = try db.internalCachedUpdateStatement(sql: query.sql) + let statement = try db.internalCachedStatement(sql: query.sql) statement.setUncheckedArguments(StatementArguments(primaryKeyValues)) return statement } /// Returns nil if and only if primary key is nil @usableFromInline - func existsStatement() throws -> SelectStatement? { + func existsStatement() throws -> Statement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { @@ -1071,7 +772,7 @@ final class DAO { let query = ExistsQuery( tableName: databaseTableName, conditionColumns: primaryKeyColumns) - let statement = try db.internalCachedSelectStatement(sql: query.sql) + let statement = try db.internalCachedStatement(sql: query.sql) statement.setUncheckedArguments(StatementArguments(primaryKeyValues)) return statement } diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index caff971d5..b8413abd6 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -55,7 +55,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// `didInsert(with:for:)` method is not called upon successful insertion, /// even if a row was actually inserted without any conflict. /// - /// See https://www.sqlite.org/lang_conflict.html + /// See open class var persistenceConflictPolicy: PersistenceConflictPolicy { PersistenceConflictPolicy(insert: .abort, update: .abort) } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index f6d658e6f..9f3f8e623 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -140,6 +140,302 @@ extension TableRecord { } } +// MARK: - Batch Delete + +extension TableRecord { + + /// Deletes all records; returns the number of deleted rows. + /// + /// - parameter db: A database connection. + /// - returns: The number of deleted rows + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @discardableResult + public static func deleteAll(_ db: Database) throws -> Int { + try all().deleteAll(db) + } +} + +// MARK: - Deleting by Single-Column Primary Key + +extension TableRecord { + + /// Delete records identified by their primary keys; returns the number of + /// deleted rows. + /// + /// // DELETE FROM player WHERE id IN (1, 2, 3) + /// try Player.deleteAll(db, keys: [1, 2, 3]) + /// + /// // 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 document WHERE rowid IN (1, 2, 3) + /// try Document.deleteAll(db, keys: [1, 2, 3]) + /// + /// - parameters: + /// - db: A database connection. + /// - keys: A sequence of primary keys. + /// - returns: The number of deleted rows + @discardableResult + public static func deleteAll(_ db: Database, keys: Sequence) + throws -> Int + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { + let keys = Array(keys) + if keys.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(keys: keys).deleteAll(db) + } + + /// Delete a record, identified by its primary key; returns whether a + /// database row was deleted. + /// + /// // DELETE FROM player WHERE id = 123 + /// try Player.deleteOne(db, key: 123) + /// + /// // 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 document WHERE rowid = 1 + /// try Document.deleteOne(db, key: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A primary key value. + /// - returns: Whether a database row was deleted. + @discardableResult + public static func deleteOne(_ db: Database, key: PrimaryKeyType?) + throws -> Bool + where PrimaryKeyType: DatabaseValueConvertible + { + guard let key = key else { + // Avoid hitting the database + return false + } + return try deleteAll(db, keys: [key]) > 0 + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { + /// Delete records identified by their primary keys; returns the number of + /// deleted rows. + /// + /// // DELETE FROM player WHERE id IN (1, 2, 3) + /// try Player.deleteAll(db, ids: [1, 2, 3]) + /// + /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') + /// try Country.deleteAll(db, ids: ["FR", "US", "DE"]) + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid IN (1, 2, 3) + /// try Document.deleteAll(db, ids: [1, 2, 3]) + /// + /// - parameters: + /// - db: A database connection. + /// - ids: A collection of primary keys. + /// - returns: The number of deleted rows + @discardableResult + public static func deleteAll(_ db: Database, ids: Collection) + throws -> Int + where Collection: Swift.Collection, Collection.Element == ID + { + if ids.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(ids: ids).deleteAll(db) + } + + /// Delete a record, identified by its primary key; returns whether a + /// database row was deleted. + /// + /// // DELETE FROM player WHERE id = 123 + /// try Player.deleteOne(db, id: 123) + /// + /// // DELETE FROM country WHERE code = 'FR' + /// try Country.deleteOne(db, id: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid = 1 + /// try Document.deleteOne(db, id: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - id: A primary key value. + /// - returns: Whether a database row was deleted. + @discardableResult + public static func deleteOne(_ db: Database, id: ID) throws -> Bool { + try deleteAll(db, ids: [id]) > 0 + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension TableRecord +where Self: Identifiable, + ID: _OptionalProtocol, + ID.Wrapped: DatabaseValueConvertible +{ + /// Delete records identified by their primary keys; returns the number of + /// deleted rows. + /// + /// // DELETE FROM player WHERE id IN (1, 2, 3) + /// try Player.deleteAll(db, ids: [1, 2, 3]) + /// + /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') + /// try Country.deleteAll(db, ids: ["FR", "US", "DE"]) + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid IN (1, 2, 3) + /// try Document.deleteAll(db, ids: [1, 2, 3]) + /// + /// - parameters: + /// - db: A database connection. + /// - ids: A collection of primary keys. + /// - returns: The number of deleted rows + @discardableResult + public static func deleteAll(_ db: Database, ids: Collection) + throws -> Int + where Collection: Swift.Collection, Collection.Element == ID.Wrapped + { + if ids.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(ids: ids).deleteAll(db) + } + + /// Delete a record, identified by its primary key; returns whether a + /// database row was deleted. + /// + /// // DELETE FROM player WHERE id = 123 + /// try Player.deleteOne(db, id: 123) + /// + /// // DELETE FROM country WHERE code = 'FR' + /// try Country.deleteOne(db, id: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid = 1 + /// try Document.deleteOne(db, id: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - id: A primary key value. + /// - returns: Whether a database row was deleted. + @discardableResult + public static func deleteOne(_ db: Database, id: ID.Wrapped) throws -> Bool { + try deleteAll(db, ids: [id]) > 0 + } +} + +// MARK: - Deleting by Key + +extension TableRecord { + /// Delete records identified by the provided unique keys (primary key or + /// any key with a unique index on it); returns the number of deleted rows. + /// + /// try Player.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) + /// + /// - parameters: + /// - db: A database connection. + /// - keys: An array of key dictionaries. + /// - returns: The number of deleted rows + @discardableResult + public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int { + if keys.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(keys: keys).deleteAll(db) + } + + /// Delete a record, identified by a unique key (the primary key or any key + /// with a unique index on it); returns whether a database row was deleted. + /// + /// Player.deleteOne(db, key: ["name": Arthur"]) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A dictionary of values. + /// - returns: Whether a database row was deleted. + @discardableResult + public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + try deleteAll(db, keys: [key]) > 0 + } +} + +// MARK: - Batch Update + +extension TableRecord { + + /// Updates all records; returns the number of updated records. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try Player.updateAll(db, [Column("score").set(to: 0)]) + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution, + /// defaulting to the record's persistenceConflictPolicy. + /// - parameter assignments: An array of column assignments. + /// - returns: The number of updated rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @discardableResult + public static func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignments: [ColumnAssignment]) + throws -> Int + { + try all().updateAll(db, onConflict: conflictResolution, assignments) + } + + /// Updates all records; returns the number of updated records. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try Player.updateAll(db, Column("score").set(to: 0)) + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution, + /// defaulting to the record's persistenceConflictPolicy. + /// - parameter assignment: A column assignment. + /// - parameter otherAssignments: Eventual other column assignments. + /// - returns: The number of updated rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @discardableResult + public static func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignment: ColumnAssignment, + _ otherAssignments: ColumnAssignment...) + throws -> Int + { + try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments) + } +} + /// Calculating `defaultDatabaseTableName` is somewhat expensive due to the regular expression evaluation /// /// This cache mitigates the cost of the calculation by storing the name for later retrieval diff --git a/GRDB/Utils/CaseInsensitiveIdentifier.swift b/GRDB/Utils/CaseInsensitiveIdentifier.swift index d9bcd172d..f1fd12c5d 100644 --- a/GRDB/Utils/CaseInsensitiveIdentifier.swift +++ b/GRDB/Utils/CaseInsensitiveIdentifier.swift @@ -1,44 +1,19 @@ /// A case-preserving, case-insensitive identifier /// that matches the ASCII version of sqlite3_stricmp struct CaseInsensitiveIdentifier: Hashable { - var rawValue: String + private let lowercased: String + let rawValue: String init(rawValue: String) { + self.lowercased = rawValue.lowercased() self.rawValue = rawValue } static func == (lhs: CaseInsensitiveIdentifier, rhs: CaseInsensitiveIdentifier) -> Bool { - guard lhs.rawValue.utf8.count == rhs.rawValue.utf8.count else { return false } - for (l, r) in zip(lhs.rawValue.utf8, rhs.rawValue.utf8) - where upperToLower[Int(l)] != upperToLower[Int(r)] { - return false - } - return true + lhs.lowercased == rhs.lowercased } func hash(into hasher: inout Hasher) { - for c in rawValue.utf8 { - hasher.combine(upperToLower[Int(c)]) - } + hasher.combine(lowercased) } } - -// swiftlint:disable comma -/// The same table as SQLite -private let upperToLower: [UTF8.CodeUnit] = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, - 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, - 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, - 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, - 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, - 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, - 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, - 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, - 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, - 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, - 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, - 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, - 252,253,254,255 -] diff --git a/GRDB/Utils/ReceiveValuesOn.swift b/GRDB/Utils/ReceiveValuesOn.swift index 00d2ac1eb..88a252103 100644 --- a/GRDB/Utils/ReceiveValuesOn.swift +++ b/GRDB/Utils/ReceiveValuesOn.swift @@ -10,7 +10,7 @@ import Foundation /// /// This scheduling guarantee is used by GRDB in order to be able /// to make promises on the scheduling of database values without surprising -/// the users as in https://forums.swift.org/t/28631. +/// the users as in . @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) struct ReceiveValuesOn: Publisher { typealias Output = Upstream.Output diff --git a/GRDB/Utils/Refinable.swift b/GRDB/Utils/Refinable.swift index ea4b1a065..253cbf8d4 100644 --- a/GRDB/Utils/Refinable.swift +++ b/GRDB/Utils/Refinable.swift @@ -10,13 +10,14 @@ /// extension Player: Refinable { } /// /// let player = Player(name: "Arthur", score: 1000) -/// player.with { $0.score = 100 } // Player(name: "Arthur", score: 100) -/// player.with(\.score, 100) // Player(name: "Arthur", score: 100) -/// player.map(\.score) { $0 + 100 } // Player(name: "Arthur", score: 1100) +/// +/// // Player(name: "Arthur", score: 100) +/// let newPlayer = player.with { +/// $0.score = 100 +/// } protocol Refinable { } extension Refinable { - /// Returns self modified with the *update* function. /// /// For example: @@ -33,49 +34,4 @@ extension Refinable { try update(&result) return result } - - /// Returns self with the given value set on the given key path. - /// - /// For example: - /// - /// let player = Player(name: "Arthur", score: 1000) - /// let newPlayer = player.with(\.score, 1100) - /// newPlayer.name // "Arthur" - /// newPlayer.score // 1100 - @inline(__always) - func with(_ keyPath: WritableKeyPath, _ value: T) -> Self { - with { $0[keyPath: keyPath] = value } - } - - /// Returns self with the given transform function applied to the given key path. - /// - /// For example: - /// - /// let player = Player(name: "Arthur", score: 1000) - /// let newPlayer = player.map(\.score) { $0 + 100 } - /// newPlayer.name // "Arthur" - /// newPlayer.score // 1100 - @inline(__always) - func map(_ keyPath: WritableKeyPath, _ transform: (T) throws -> T) rethrows -> Self { - try with { - $0[keyPath: keyPath] = try transform($0[keyPath: keyPath]) - } - } - - /// Returns self with the given update function applied to the given key path. - /// - /// For example: - /// - /// let player = Player(name: "Arthur", scores: [100, 10]) - /// let newPlayer = player.mapInto(\.scores) { $0.append(1000) } - /// newPlayer.name // "Arthur" - /// newPlayer.scores // [100, 10, 1000] - @inline(__always) - func mapInto(_ keyPath: WritableKeyPath, _ update: (inout T) throws -> Void) rethrows -> Self { - try with { - try update(&$0[keyPath: keyPath]) - } - } } - -extension Array: Refinable where Element: Refinable { } diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index d881e0875..01c296fcb 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -8,7 +8,7 @@ extension String { /// /// db.execute(sql: "SELECT * FROM \(tableName.quotedDatabaseIdentifier)") @inlinable public var quotedDatabaseIdentifier: String { - // See https://www.sqlite.org/lang_keywords.html + // See return "\"\(self)\"" } } @@ -45,8 +45,8 @@ func GRDBPrecondition( line: UInt = #line) { /// Custom precondition function which aims at solving - /// https://bugs.swift.org/browse/SR-905 and - /// https://github.com/groue/GRDB.swift/issues/37 + /// and + /// if !condition() { fatalError(message(), file: file, line: line) } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index a7950f933..86e6f89e5 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -32,7 +32,7 @@ public struct ValueObservation { /// /// Don't set this flag to true unless you really need it. A read/write /// observation is less efficient than a read-only observation. - public var requiresWriteAccess: Bool = false + public var requiresWriteAccess = false /// Returns a ValueObservation with a transformed reducer. func mapReducer(_ transform: @escaping (Reducer) -> R) -> ValueObservation { @@ -103,8 +103,8 @@ extension ValueObservation: Refinable { onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable { - let observation = map(\.events) { events in - events.map(\.didFail) { concat($0, onError) } + let observation = self.with { + $0.events.didFail = concat($0.events.didFail, onError) } observation.events.willStart?() return reader._add( @@ -157,14 +157,13 @@ extension ValueObservation: Refinable { // the type of the value may change with the `map` operator. didReceiveValue: didReceiveValue ?? { _ in }) }) - .map(\.events, { events in - events - .map(\.willStart) { concat($0, willStart) } - .map(\.willTrackRegion) { concat($0, willTrackRegion) } - .map(\.databaseDidChange) { concat($0, databaseDidChange) } - .map(\.didFail) { concat($0, didFail) } - .map(\.didCancel) { concat($0, didCancel) } - }) + .with { + $0.events.willStart = concat($0.events.willStart, willStart) + $0.events.willTrackRegion = concat($0.events.willTrackRegion, willTrackRegion) + $0.events.databaseDidChange = concat($0.events.databaseDidChange, databaseDidChange) + $0.events.didFail = concat($0.events.didFail, didFail) + $0.events.didCancel = concat($0.events.didCancel, didCancel) + } } /// Prints log messages for all ValueObservation events. @@ -173,16 +172,31 @@ extension ValueObservation: Refinable { to stream: TextOutputStream? = nil) -> ValueObservation> { + let lock = NSLock() let prefix = prefix.isEmpty ? "" : "\(prefix): " var stream = stream ?? PrintOutputStream() return handleEvents( - willStart: { stream.write("\(prefix)start") }, - willFetch: { stream.write("\(prefix)fetch") }, - willTrackRegion: { stream.write("\(prefix)tracked region: \($0)") }, - databaseDidChange: { stream.write("\(prefix)database did change") }, - didReceiveValue: { stream.write("\(prefix)value: \($0)") }, - didFail: { stream.write("\(prefix)failure: \($0)") }, - didCancel: { stream.write("\(prefix)cancel") }) + willStart: { + lock.lock(); defer { lock.unlock() } + stream.write("\(prefix)start") }, + willFetch: { + lock.lock(); defer { lock.unlock() } + stream.write("\(prefix)fetch") }, + willTrackRegion: { + lock.lock(); defer { lock.unlock() } + stream.write("\(prefix)tracked region: \($0)") }, + databaseDidChange: { + lock.lock(); defer { lock.unlock() } + stream.write("\(prefix)database did change") }, + didReceiveValue: { + lock.lock(); defer { lock.unlock() } + stream.write("\(prefix)value: \($0)") }, + didFail: { + lock.lock(); defer { lock.unlock() } + stream.write("\(prefix)failure: \($0)") }, + didCancel: { + lock.lock(); defer { lock.unlock() } + stream.write("\(prefix)cancel") }) } // MARK: - Fetching Values diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index ba4f998b3..f93bbb72d 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -23,7 +23,7 @@ final class ValueObserver { private let reduceQueue: DispatchQueue private var isChanged = false private let onChange: (Reducer.Value) -> Void - private var lock = NSRecursiveLock() // protects _isCompleted + private var lock = NSRecursiveLock() // protects _isCompleted and reducer init( events: ValueObservationEvents, @@ -94,13 +94,15 @@ extension ValueObserver: TransactionObserver { // Synchronously fetchedFuture = DatabaseFuture(Result { try recordingSelectedRegionIfNeeded(db) { - try reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + try synchronized { + try reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } } }) } else { // Concurrently guard let writer = writer else { return } - fetchedFuture = writer.concurrentRead(reducer._fetch) + fetchedFuture = writer.concurrentRead { db in try self.synchronized { try self.reducer._fetch(db) } } } // 2. Reduce @@ -113,7 +115,7 @@ extension ValueObserver: TransactionObserver { if self.isCompleted { return } do { let fetchedValue = try fetchedFuture.wait() - if let value = self.reducer._value(fetchedValue) { + if let value = self.synchronized({ self.reducer._value(fetchedValue) }) { self.notifyChange(value) } } catch { @@ -144,7 +146,9 @@ extension ValueObserver { /// Fetch an observed value, and moves the reducer forward. func fetchValue(_ db: Database) throws -> Reducer.Value? { try recordingSelectedRegionIfNeeded(db) { - try reducer.fetchAndReduce(db, requiringWriteAccess: requiresWriteAccess) + try synchronized { + try reducer.fetchAndReduce(db, requiringWriteAccess: requiresWriteAccess) + } } } @@ -199,7 +203,7 @@ extension ValueObserver { } private var needsRecordingSelectedRegion: Bool { - observedRegion == nil || !reducer._isSelectedRegionDeterministic + observedRegion == nil || synchronized { !reducer._isSelectedRegionDeterministic } } private func recordingSelectedRegionIfNeeded( diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 220ca551e..d224c905a 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -43,8 +43,8 @@ 561729562235340E0006E219 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561729532235340E0006E219 /* EncodableRecord.swift */; }; 56176C7E1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; 56176C801EACCD31000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; - 561CFA7D2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */; }; - 561CFA7E2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */; }; + 561CFA7D2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */; }; + 561CFA7E2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */; }; 561CFAA12376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */; }; 561CFAA22376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */; }; 561CFAA42376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; @@ -98,6 +98,8 @@ 563B071321862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */; }; 563B071B21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; 563B071C21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; + 563B533B267E2FA4009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5339267E2FA4009549B5 /* TableTests.swift */; }; + 563B533C267E2FA4009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5339267E2FA4009549B5 /* TableTests.swift */; }; 563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; }; 563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; }; 563B8F9E249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */; }; @@ -322,6 +324,8 @@ 5670329C212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; }; 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; }; + 56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */; }; + 56713FE42691F487006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */; }; 5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; 5671FC251DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; 56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; @@ -358,6 +362,8 @@ 567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; + 56894F332604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; }; + 56894F342604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; }; 56894FE3260658A400268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; }; 56894FE8260658A500268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; }; 56894FF2260658E600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */; }; @@ -523,8 +529,8 @@ 56FEB8FF248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.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 */; }; + 56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; }; + 56FF45471D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.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 */; }; @@ -795,7 +801,7 @@ 5615B284222B17B900061C1C /* AssociationHasOneThroughDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughDecodableRecordTests.swift; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 561729532235340E0006E219 /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = ""; }; - 561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = ""; }; + 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = ""; }; 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; }; 561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; }; 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = ""; }; @@ -833,6 +839,7 @@ 563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = ""; }; 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; + 563B5339267E2FA4009549B5 /* TableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableTests.swift; sourceTree = ""; }; 563B8F99249E74E5007A48C9 /* Trace.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = ""; }; 563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = ""; }; 563B8FB024A1CE9E007A48C9 /* DatabasePublishers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePublishers.swift; sourceTree = ""; }; @@ -950,6 +957,7 @@ 566BE7132342541F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = ""; }; 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; + 56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONRequiredEncoder.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = ""; }; 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3TokenizerDescriptor.swift; sourceTree = ""; }; @@ -974,6 +982,7 @@ 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.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 = ""; }; + 56894F322604FC1E00268F4D /* Table.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = ""; }; 56894FA0260657F600268F4D /* Decimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = ""; }; 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; }; 568ECB0C25D904CA00B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = ""; }; @@ -1109,7 +1118,7 @@ 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.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 = ""; }; + 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.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,6 +1218,7 @@ 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */, 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */, 5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */, + 56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */, 5605F1581C672E4000235C62 /* StandardLibrary.swift */, ); path = StandardLibrary; @@ -1243,11 +1253,9 @@ 5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */, 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */, 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */, - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, - 561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */, 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, ); name = PersistableRecord; @@ -1302,7 +1310,9 @@ 56176C9C1EACEA8C000F3F2B /* TableRecord */ = { isa = PBXGroup; children = ( + 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */, 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */, + 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */, ); name = TableRecord; sourceTree = ""; @@ -1371,6 +1381,7 @@ 56F34FC524B0A0C8007513FC /* SQLIdentifyingColumnsTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, + 563B5339267E2FA4009549B5 /* TableTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, 5653EB5620961F8900F46237 /* Association */, ); @@ -1562,6 +1573,7 @@ 5656A84E2295BD56001FF3FF /* SQLRelation.swift */, 568ECB0C25D904CA00B71526 /* SQLSelection.swift */, 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */, + 56894F322604FC1E00268F4D /* Table.swift */, ); path = SQL; sourceTree = ""; @@ -2263,6 +2275,7 @@ buildActionMask = 2147483647; files = ( 5656A8722295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */, + 56713FE42691F487006153C3 /* JSONRequiredEncoder.swift in Sources */, 5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */, F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */, 563B8FBE24A1D388007A48C9 /* OnDemandFuture.swift in Sources */, @@ -2280,6 +2293,7 @@ 56CEB4F61EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 5656A8522295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift in Sources */, 56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, + 56894F342604FC1E00268F4D /* Table.swift in Sources */, F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */, 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, @@ -2395,7 +2409,7 @@ files = ( F3BA80D71CFB300A003DC1BA /* DatabaseValueTests.swift in Sources */, F3BA80C81CFB2FD8003DC1BA /* DatabaseQueueTests.swift in Sources */, - 56FF45471D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56FF45471D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */, F3BA810C1CFB3056003DC1BA /* StatementArguments+FoundationTests.swift in Sources */, F3BA80B91CFB2FD1003DC1BA /* DatabasePoolBackupTests.swift in Sources */, F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, @@ -2544,7 +2558,7 @@ 5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */, - 561CFA7E2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, + 561CFA7E2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */, 56B964D21DA521450002DA19 /* FTS5RecordTests.swift in Sources */, F3BA80F91CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 5604484F25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, @@ -2559,6 +2573,7 @@ 5653EB7120961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, F3BA812B1CFB3063003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, 5698ACA51DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, + 563B533C267E2FA4009549B5 /* TableTests.swift in Sources */, 5653EB6F20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 564CE5C721B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */, F3BA80B11CFB2FC4003DC1BA /* DatabaseTests.swift in Sources */, @@ -2624,6 +2639,7 @@ buildActionMask = 2147483647; files = ( 5656A8712295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */, + 56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */, 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */, F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */, 563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */, @@ -2641,6 +2657,7 @@ 56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 5656A8512295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift in Sources */, 56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, + 56894F332604FC1E00268F4D /* Table.swift in Sources */, F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */, 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, @@ -2862,7 +2879,7 @@ 5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */, F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, 56419C7F24A51D6E004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */, - 56FF45431D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */, F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */, 5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 56419C8924A51D7D004967E1 /* RecordingError.swift in Sources */, @@ -2905,7 +2922,7 @@ 5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */, - 561CFA7D2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, + 561CFA7D2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */, 5623936C1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, F3BA80E01CFB300F003DC1BA /* DatabaseTimestampTests.swift in Sources */, 5604484E25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, @@ -2920,6 +2937,7 @@ 5653EB7020961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, F3BA81311CFB3064003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */, 5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, + 563B533B267E2FA4009549B5 /* TableTests.swift in Sources */, 5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */, F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */, diff --git a/Makefile b/Makefile index c5d834054..fd253ecd6 100644 --- a/Makefile +++ b/Makefile @@ -50,7 +50,14 @@ TEST_ACTIONS = clean build build-for-testing test-without-building # When adding support for an Xcode version, look for available devices with # `xcrun xctrace list devices` (or the deprecated `instruments -s devices`). -ifeq ($(XCODEVERSION),12.4) +ifeq ($(XCODEVERSION),12.5) + MAX_SWIFT_VERSION = 5.4 + MIN_SWIFT_VERSION = 5.2 + MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.5" + MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=11.4" + MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=14.5" + MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" +else ifeq ($(XCODEVERSION),12.4) MAX_SWIFT_VERSION = 5.3 MIN_SWIFT_VERSION = 5.2 MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.4" @@ -431,10 +438,10 @@ ifdef JAZZY --author 'Gwendal Roué' \ --author_url https://github.com/groue \ --github_url https://github.com/groue/GRDB.swift \ - --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.8.0 \ - --module-version 5.8.0 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.9.0 \ + --module-version 5.9.0 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/5.8/ \ + --root-url http://groue.github.io/GRDB.swift/docs/5.9/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index 76cea8dc4..dbd51914e 100644 --- a/README.md +++ b/README.md @@ -6,18 +6,17 @@ Swift 5.2 Platforms License - Build Status

--- -**Latest release**: May 16, 2021 • version 5.8.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +**Latest release**: August 15, 2021 • version 5.9.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) **Requirements**: iOS 10.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.2+ / Xcode 11.4+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.2+** | **v5.8.0** | +| **Swift 5.2+** | **v5.9.0** | | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | @@ -316,7 +315,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.8/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.9/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -510,7 +509,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.8/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.9/Structs/Configuration.html) for more details. ## Database Pools @@ -590,7 +589,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.8/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.9/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -650,7 +649,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.8/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details. @@ -798,6 +797,29 @@ try Row.fetchOne(...) // Row? let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) ...") // Int? ``` +**All those fetching methods require an SQL string that contains a single SQL statement.** When you want to fetch from multiple statements joined with a semicolon, iterate the multiple [prepared statements](#prepared-statements) found in the SQL string: + +```swift +let statements = try db.allStatements(sql: """ + SELECT ...; + SELECT ...; + SELECT ...; + """) +while let statement = try statements.next() { + let players = try Player.fetchAll(statement) +} +``` + +You can join the results of all statements yielded by the `allStatements` method, like the SQLite [`sqlite3_exec`](https://www.sqlite.org/c3ref/exec.html) function: + +```swift +// A single cursor of all rows from all statements +let rows = try db + .allStatements(sql: "...") + .flatMap { statement in try Row.fetchCursor(statement) } +``` + +See [prepared statements](#prepared-statements) for more information about `allStatements()`. ### Cursors @@ -885,7 +907,7 @@ try dbQueue.read { db in let dictionary = try Dictionary(uniqueKeysWithValues: cursor) ``` -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.8/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.9/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // Prints all Github links @@ -964,7 +986,7 @@ let rows = try Row.fetchAll(db, arguments: ["name": "Arthur"]) ``` -See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.8/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.9/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: @@ -1249,7 +1271,7 @@ GRDB ships with built-in support for the following value types: - Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol. -Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.8/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1552,6 +1574,23 @@ 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). +Value types that adopt both `DatabaseValueConvertible` and an archival protocol ([Codable, Encodable or Decodable](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types)) are automatically coded and decoded from JSON arrays and objects: + +```swift +// Encoded as a JSON object in the database: +struct Color: Codable, DatabaseValueConvertible { + var r: Double + var g: Double + var b: Double +} +``` + +For such codable value types, GRDB uses the standard [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder) and [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) from Foundation. By default, Data values are handled with the `.base64` strategy, Date with the `.millisecondsSince1970` strategy, and non conforming floats with the `.throw` strategy. + +In order to customize the JSON format, provide a custom implementation of the `DatabaseValueConvertible` requirements. + +> :point_up: **Note**: standard sequences such as `Array`, `Set`, or `Dictionary` do not conform to `DatabaseValueConvertible`, even conditionally. You won't be able to directly fetch or store arrays, sets, or dictionaries as JSON database values. You can get free JSON support from these standard types when they are embedded as properties of [Codable Records], though. + ## Transactions and Savepoints @@ -1679,7 +1718,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction } ``` -Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.8/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.9/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1781,40 +1820,38 @@ dbQueue.inTransaction(.exclusive) { db in ... } **Prepared Statements** let you prepare an SQL query and execute it later, several times if you need, with different arguments. -There are two kinds of prepared statements: **select statements**, and **update statements**: - ```swift try dbQueue.write { db in - let updateSQL = "INSERT INTO player (name, score) VALUES (:name, :score)" - let updateStatement = try db.makeUpdateStatement(sql: updateSQL) + let insertSQL = "INSERT INTO player (name, score) VALUES (:name, :score)" + let insertStatement = try db.makeStatement(sql: insertSQL) let selectSQL = "SELECT * FROM player WHERE name = ?" - let selectStatement = try db.makeSelectStatement(sql: selectSQL) + let selectStatement = try db.makeStatement(sql: 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/5.8/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). +The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift -updateStatement.arguments = ["name": "Arthur", "score": 1000] +insertStatement.arguments = ["name": "Arthur", "score": 1000] selectStatement.arguments = ["Arthur"] ``` Alternatively, you can create a prepared statement with [SQL Interpolation]: ```swift -let updateStatement = try db.makeUpdateStatement(literal: "INSERT ...") -let selectStatement = try db.makeSelectStatement(literal: "SELECT ...") -// ~~~~~~~ +let insertStatement = try db.makeStatement(literal: "INSERT ...") +let selectStatement = try db.makeStatement(literal: "SELECT ...") +// ~~~~~~~ ``` -Update statements can be executed: +Statements can be executed: ```swift -try updateStatement.execute() +try insertStatement.execute() ``` -Select statements can be used wherever a raw SQL query string would fit (see [fetch queries](#fetch-queries)): +Statements can be used wherever a raw SQL query string would fit (see [fetch queries](#fetch-queries)): ```swift let rows = try Row.fetchCursor(selectStatement) // A Cursor of Row @@ -1826,13 +1863,57 @@ let player = try Player.fetchOne(selectStatement) // Player? You can set the arguments at the moment of the statement execution: ```swift -try updateStatement.execute(arguments: ["name": "Arthur", "score": 1000]) +try insertStatement.execute(arguments: ["name": "Arthur", "score": 1000]) let player = try Player.fetchOne(selectStatement, arguments: ["Arthur"]) ``` +**When you want to build multiple statements joined with a semicolon**, use the `allStatements` method: + +```swift +let statements = try db.allStatements(sql: """ + INSERT INTO player (name, score) VALUES (?, ?); + INSERT INTO player (name, score) VALUES (?, ?); + """, arguments: ["Arthur", 100, "O'Brien", 1000]) +while let statement = try statements.next() { + try statement.execute() +} +``` + +`allStatements` also supports [SQL Interpolation]: + +```swift +let statements = try db.allStatements(literal: """ + INSERT INTO player (name, score) VALUES (\("Arthur"), \(100)); + INSERT INTO player (name, score) VALUES (\("O'Brien"), \(1000)); + """) +while let statement = try statements.next() { + try statement.execute() +} +``` + +You can turn the [cursor](#cursors) returned from `allStatements` into a regular Swift array, but in this case make sure all individual statements can compile even if the previous ones were not run: + +```swift +// OK: Array of statements +let statements = try Array(db.allStatements(sql: """ + INSERT ...; + UPDATE ...; + SELECT ...; + """)) + +// FAILURE: Can't build an array of statements since +// the INSERT won't compile until CREATE TABLE is run. +let statements = try Array(db.allStatements(sql: """ + CREATE TABLE player ...; + INSERT INTO player ...; + """)) +``` + +See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates) chapter. + > :point_up: **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so. -See [row queries](#row-queries), [value queries](#value-queries), and [Records](#records) for more information. +For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.9/Classes/Statement.html). ### Prepared Statements Cache @@ -1843,14 +1924,20 @@ When the same query will be used several times in the lifetime of your applicati > :point_up: **Note**: This is because you don't have the necessary tools. Statements are tied to specific SQLite connections and dispatch queues which you don't manage yourself, especially when you use [database pools](#database-pools). A change in the database schema [may, or may not](https://www.sqlite.org/compile.html#max_schema_retry) invalidate a statement. -Instead, use the `cachedUpdateStatement` and `cachedSelectStatement` methods. GRDB does all the hard caching and [memory management](#memory-management) stuff for you: +Instead, use the `cachedStatement` method. GRDB does all the hard caching and [memory management](#memory-management) stuff for you: ```swift -let updateStatement = try db.cachedUpdateStatement(sql: sql) -let selectStatement = try db.cachedSelectStatement(sql: sql) +let statement = try db.cachedStatement(sql: sql) ``` -Should a cached prepared statement throw an error, don't reuse it (it is a programmer error). Instead, reload it from the cache. +Cached statements also support [SQL Interpolation]: + +```swift +let statement = try db.cachedStatement(literal: "INSERT ...") +// ~~~~~~~ +``` + +> :warning: **Warning**: Should a cached prepared statement throw an error, don't reuse it (it is a programmer error). Instead, reload one from the cache. ## Custom SQL Functions and Aggregates @@ -2263,7 +2350,7 @@ try dbQueue.read { db in let sqliteConnection = db.sqliteConnection // The raw pointer to a statement: - let statement = try db.makeSelectStatement(sql: "SELECT ...") + let statement = try db.makeStatement(sql: "SELECT ...") let sqliteStatement = statement.sqliteStatement } ``` @@ -2390,7 +2477,7 @@ try Player .updateAll(db, Column("score") += 1) ``` -:point_right: update methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol. +:point_right: update methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol. Batch updates are available on the [TableRecord] protocol. ### Deleting Records @@ -2413,7 +2500,7 @@ try Player .deleteAll(db) ``` -:point_right: delete methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol. +:point_right: delete methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol. Batch deletes are available on the [TableRecord] protocol. ### Counting Records @@ -2569,7 +2656,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.8/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html) for more information about the query arguments. > :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. @@ -2747,7 +2834,11 @@ try place.updateChanges(db) { ... } // Maybe UPDATE try place.updateChanges(db) // Maybe UPDATE (Record class only) try place.delete(db) // DELETE try place.exists(db) +``` +The [TableRecord] protocol comes with batch operations: + +```swift // Type methods try Place.updateAll(db, ...) // UPDATE try Place.deleteAll(db) // DELETE @@ -2848,6 +2939,9 @@ let players = try Player.fetchSet(db, ids: [1, 2, 3]) let request = Player.filter(id: 1) let request = Player.filter(ids: [1, 2, 3]) +let ids = try Player.selectID().fetchAll(db) +let ids = try Player.filter(...).selectID().fetchSet(db) + try Player.deleteOne(db, id: 1) try Player.deleteAll(db, ids: [1, 2, 3]) ``` @@ -2998,7 +3092,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.8/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.8/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.8/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.9/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.9/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.9/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. > :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings). @@ -3829,16 +3923,16 @@ This is the list of record methods, along with their required protocols. The [Re | `record.updateChanges(db, from:...)` | [PersistableRecord] | [*](#record-comparison) | | `record.updateChanges(db) { ... }` | [PersistableRecord] | [*](#record-comparison) | | `record.updateChanges(db)` | [Record](#record-class) | [*](#record-comparison) | -| `Type.updateAll(db, ...)` | [PersistableRecord] | | -| `Type.filter(...).updateAll(db, ...)` | [PersistableRecord] | ² | +| `Type.updateAll(db, ...)` | [TableRecord] | | +| `Type.filter(...).updateAll(db, ...)` | [TableRecord] | ² | | **Delete Records** | | | | `record.delete(db)` | [PersistableRecord] | | -| `Type.deleteOne(db, key:...)` | [PersistableRecord] | ¹ | -| `Type.deleteOne(db, id:...)` | [PersistableRecord] & [Identifiable] | ¹ | -| `Type.deleteAll(db)` | [PersistableRecord] | | -| `Type.deleteAll(db, keys:...)` | [PersistableRecord] | ¹ | -| `Type.deleteAll(db, ids:...)` | [PersistableRecord] & [Identifiable] | ¹ | -| `Type.filter(...).deleteAll(db)` | [PersistableRecord] | ² | +| `Type.deleteOne(db, key:...)` | [TableRecord] | ¹ | +| `Type.deleteOne(db, id:...)` | [TableRecord] & [Identifiable] | ¹ | +| `Type.deleteAll(db)` | [TableRecord] | | +| `Type.deleteAll(db, keys:...)` | [TableRecord] | ¹ | +| `Type.deleteAll(db, ids:...)` | [TableRecord] & [Identifiable] | ¹ | +| `Type.filter(...).deleteAll(db)` | [TableRecord] | ² | | **Check Record Existence** | | | | `record.exists(db)` | [PersistableRecord] | | | **Convert Record to Dictionary** | | | @@ -3894,8 +3988,11 @@ This is the list of record methods, along with their required protocols. The [Re | `Type.none()` | [TableRecord] | ² | | `Type.select(...)` | [TableRecord] | ² | | `Type.select(..., as:...)` | [TableRecord] | ² | +| `Type.selectID()` | [TableRecord] & Identifiable | [*](#identifiable-records) | | `Type.annotated(with:...)` | [TableRecord] | ² | | `Type.filter(...)` | [TableRecord] | ² | +| `Type.filter(id:)` | [TableRecord] & Identifiable | [*](#identifiable-records) | +| `Type.filter(ids:)` | [TableRecord] & Identifiable | [*](#identifiable-records) | | `Type.matching(...)` | [TableRecord] | ² | | `Type.including(all:)` | [TableRecord] | ² | | `Type.including(optional:)` | [TableRecord] | ² | @@ -3943,7 +4040,7 @@ let player = try Player.fetchOne(db, sql: "SELECT * FROM player WHERE id = ?", a ⁴ See [Prepared Statements](#prepared-statements): ```swift -let statement = try db.makeSelectStatement(sql: "SELECT * FROM player WHERE id = ?") +let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?") let player = try Player.fetchOne(statement, arguments: [1]) // Player? ``` @@ -4237,13 +4334,33 @@ let players = try request.fetchAll(db) // [Player] let count = try request.fetchCount(db) // Int ``` -All requests start from **a type** that adopts the `TableRecord` protocol, such as a `Record` subclass (see [Records](#records)): +Query interface requests usually start from **a type** that adopts the `TableRecord` protocol, such as a `Record` subclass (see [Records](#records)): ```swift -class Player : Record { ... } +class Player: Record { ... } + +// The request for all players: +let request = Player.all() +let players = try request.fetchAll(db) // [Player] ``` -Declare the table **columns** that you want to use for filtering, or sorting: +When you can not use a record type, use `Table`: + +```swift +// The request for all rows from the player table: +let table = Table("player") +let request = table.all() +let rows = try request.fetchAll(db) // [Row] + +// The request for all players from the player table: +let table = Table("player") +let request = table.all() +let players = try request.fetchAll(db) // [Player] +``` + +> :point_up: **Note**: all examples in the documentation below use a record type, but you can always substitute a `Table` instead. + +Next, declare the table **columns** that you want to use for filtering, or sorting: ```swift let idColumn = Column("id") @@ -4279,6 +4396,16 @@ You can now build requests with the following methods: `all`, `none`, `select`, Player.select(nameColumn, as: String.self) ``` +- `selectID()` is available on [Identifiable Records]. It supports all tables that have a single-column primary key: + + ```swift + // SELECT id FROM player + Player.selectID() + + // SELECT id FROM player WHERE name IS NOT NULL + Player.filter(nameColumn != nil).selectID() + ``` + - `annotated(with: expression...)` extends the selection. ```swift @@ -4495,7 +4622,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.8/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -4512,16 +4639,24 @@ By default, query interface requests select all columns: ```swift // SELECT * FROM player +struct Player: TableRecord { ... } let request = Player.all() + +// SELECT * FROM player +let table = Table("player") +let request = table.all() ``` -**The selection can be changed for each individual requests, or for all requests built from a given type.** +**The selection can be changed for each individual requests, or in the case of record-based requests, for all requests built from this record type.** The `select(...)` and `select(..., as:)` methods change the selection of a single request (see [Fetching from Requests] for detailed information): ```swift -let request = Player.select(max(scoreColumn)) -let maxScore: Int? = try Int.fetchOne(db, request) +let request = Player.select(max(Column("score"))) +let maxScore = try Int.fetchOne(db, request) // Int? + +let request = Player.select(max(Column("score")), as: Int.self) +let maxScore = try request.fetchOne(db) // Int? ``` The default selection for a record type is controlled by the `databaseSelection` property: @@ -5037,7 +5172,13 @@ try Player .deleteAll(db) ``` -> :point_up: **Note** Deletion methods are only available for records that adopts the [PersistableRecord] protocol. +> :point_up: **Note** Deletion methods are available on types that adopt the [TableRecord] protocol, and `Table`: +> +> ```swift +> struct Player: TableRecord { ... } +> try Player.deleteAll(db) // Fine +> try Table("player").deleteAll(db) // Just as fine +> ``` **Deleting records according to their primary key** is a common task. @@ -5114,7 +5255,13 @@ Default [Conflict Resolution] rules apply, and you may also provide a specific o try Player.updateAll(db, onConflict: .ignore, /* assignments... */) ``` -> :point_up: **Note** The `updateAll` method is only available for records that adopts the [PersistableRecord] protocol. +> :point_up: **Note** The `updateAll` method is available on types that adopt the [TableRecord] protocol, and `Table`: +> +> ```swift +> struct Player: TableRecord { ... } +> try Player.updateAll(db, ...) // Fine +> try Table("player").updateAll(db, ...) // Just as fine +> ``` ## Custom Requests @@ -5194,7 +5341,7 @@ try Player.customRequest().fetchAll(db) // [Player] - The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. -- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.8/Structs/AnyFetchRequest.html): a type-erased request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.9/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -6372,7 +6519,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.8/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. +**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.9/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion. @@ -6382,7 +6529,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. -For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.8/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.9/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). #### The DatabaseRegionConvertible Protocol @@ -7002,7 +7149,7 @@ In such a situation, you can still avoid fatal errors by exposing and handling e ```swift // Untrusted arguments if let arguments = StatementArguments(arguments) { - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try statement.setArguments(arguments) var cursor = try Row.fetchCursor(statement) @@ -7502,7 +7649,7 @@ try snapshot2.read { db in ### DatabaseWriter and DatabaseReader Protocols -Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.8/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.8/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. +Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.9/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.9/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example: @@ -8176,7 +8323,7 @@ When this is the case, there are two possible explanations: try db.execute(sql: "UPDATE player SET name = ?", arguments: [name]) ``` -For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.8/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). +For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.9/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). @@ -8249,7 +8396,7 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [@alextrob](https://github.com/alextrob), [@alexwlchan](https://github.com/alexwlchan), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@eburns-vmware](https://github.com/eburns-vmware), [@felixscheinost](https://github.com/felixscheinost), [@fpillet](http://github.com/fpillet), [@gcox](https://github.com/gcox), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@holsety](https://github.com/holsety), [@jroselightricks](https://github.com/jroselightricks), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@mallman](https://github.com/mallman), [@MartinP7r](https://github.com/MartinP7r), [@Marus](https://github.com/Marus), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@professordeng](https://github.com/professordeng), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@steipete](https://github.com/steipete), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@valexa](https://github.com/valexa), [@wuyuehyang](https://github.com/wuyuehyang), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. +- [@alextrob](https://github.com/alextrob), [@alexwlchan](https://github.com/alexwlchan), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@eburns-vmware](https://github.com/eburns-vmware), [@felixscheinost](https://github.com/felixscheinost), [@fpillet](http://github.com/fpillet), [@gcox](https://github.com/gcox), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@holsety](https://github.com/holsety), [@jroselightricks](https://github.com/jroselightricks), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@layoutSubviews](https://github.com/layoutSubviews), [@mallman](https://github.com/mallman), [@MartinP7r](https://github.com/MartinP7r), [@Marus](https://github.com/Marus), [@mattgallagher](https://github.com/mattgallagher), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@pp5x](https://github.com/pp5x), [@professordeng](https://github.com/professordeng), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@steipete](https://github.com/steipete), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@tternes](https://github.com/tternes), [@valexa](https://github.com/valexa), [@wuyuehyang](https://github.com/wuyuehyang), [@ZevEisenberg](https://github.com/ZevEisenberg), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [@kali](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. @@ -8343,7 +8490,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Sharing a Database]: Documentation/SharingADatabase.md [FAQ]: #faq [Database Observation]: #database-changes-observation -[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.8/Structs/SQLRequest.html +[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.9/Structs/SQLRequest.html [SQL literal]: Documentation/SQLInterpolation.md#sql-literal [Identifiable]: https://developer.apple.com/documentation/swift/identifiable [Query Interface Organization]: Documentation/QueryInterfaceOrganization.md diff --git a/Support/Info.plist b/Support/Info.plist index f3067889b..b259696f0 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.8.0 + 5.9.0 CFBundleSignature ???? CFBundleVersion diff --git a/TODO.md b/TODO.md index 666172228..6db539a64 100644 --- a/TODO.md +++ b/TODO.md @@ -15,6 +15,8 @@ ## Features +- [ ] Breaking: have DatabaseRegionObservation produce DatabaseCancellable just as ValueObservation. +- [ ] Can Swift 5.5 help us with `select(.all)` (request of RowDecoder), `select(.id)` (request of RowDecoder.ID), `select(.rowid)` (request of Int64)? - [ ] Direct access to statement for bindings - [ ] Breaking: make `fetchOne(key:)` type-safe (have a single dedicated primary key type) - [ ] Property wrapper that decodes dictionaries (but how to tell the key column?) diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 564ec8423..45a096adb 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -113,8 +113,8 @@ 56419DD024A54062004967E1 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD024A54057004967E1 /* GRDBTestCase.swift */; }; 56419DD124A54062004967E1 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD124A54057004967E1 /* ValueObservationRecordTests.swift */; }; 56419DD224A54062004967E1 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD124A54057004967E1 /* ValueObservationRecordTests.swift */; }; - 56419DD324A54062004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD224A54057004967E1 /* MutablePersistableRecordUpdateTests.swift */; }; - 56419DD424A54062004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD224A54057004967E1 /* MutablePersistableRecordUpdateTests.swift */; }; + 56419DD324A54062004967E1 /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */; }; + 56419DD424A54062004967E1 /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */; }; 56419DD524A54062004967E1 /* FTS5TokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD324A54057004967E1 /* FTS5TokenizerTests.swift */; }; 56419DD624A54062004967E1 /* FTS5TokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD324A54057004967E1 /* FTS5TokenizerTests.swift */; }; 56419DD724A54062004967E1 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD424A54057004967E1 /* CGFloatTests.swift */; }; @@ -321,8 +321,8 @@ 56419EA024A54063004967E1 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3824A5405E004967E1 /* FetchableRecordTests.swift */; }; 56419EA124A54063004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3924A5405F004967E1 /* QueryInterfaceExtensibilityTests.swift */; }; 56419EA224A54063004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3924A5405F004967E1 /* QueryInterfaceExtensibilityTests.swift */; }; - 56419EA324A54063004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3A24A5405F004967E1 /* MutablePersistableRecordDeleteTests.swift */; }; - 56419EA424A54063004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3A24A5405F004967E1 /* MutablePersistableRecordDeleteTests.swift */; }; + 56419EA324A54063004967E1 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */; }; + 56419EA424A54063004967E1 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */; }; 56419EA524A54063004967E1 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */; }; 56419EA624A54063004967E1 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */; }; 56419EA724A54063004967E1 /* CursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3C24A5405F004967E1 /* CursorTests.swift */; }; @@ -504,7 +504,7 @@ 56419CCF24A54057004967E1 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 56419CD024A54057004967E1 /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = ""; }; 56419CD124A54057004967E1 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; - 56419CD224A54057004967E1 /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = ""; }; + 56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = ""; }; 56419CD324A54057004967E1 /* FTS5TokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerTests.swift; sourceTree = ""; }; 56419CD424A54057004967E1 /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56419CD524A54057004967E1 /* AssociationBelongsToSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLTests.swift; sourceTree = ""; }; @@ -608,7 +608,7 @@ 56419D3724A5405E004967E1 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; 56419D3824A5405E004967E1 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = ""; }; 56419D3924A5405F004967E1 /* QueryInterfaceExtensibilityTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExtensibilityTests.swift; sourceTree = ""; }; - 56419D3A24A5405F004967E1 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; + 56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = ""; }; 56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordTests.swift; sourceTree = ""; }; 56419D3C24A5405F004967E1 /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = ""; }; 56419D3D24A5405F004967E1 /* DatabasePoolReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReleaseMemoryTests.swift; sourceTree = ""; }; @@ -892,11 +892,11 @@ 56419D0024A5405A004967E1 /* JoinSupportTests.swift */, 56419CDC24A54058004967E1 /* MapCursorTests.swift */, 56419D0224A5405A004967E1 /* MutablePersistableRecordChangesTests.swift */, - 56419D3A24A5405F004967E1 /* MutablePersistableRecordDeleteTests.swift */, + 56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */, 56419D2F24A5405E004967E1 /* MutablePersistableRecordEncodableTests.swift */, 56419D4424A5405F004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */, - 56419CD224A54057004967E1 /* MutablePersistableRecordUpdateTests.swift */, + 56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */, 56419CFD24A5405A004967E1 /* NumericOverflowTests.swift */, 56419D4F24A54060004967E1 /* OrderedDictionaryTests.swift */, 56419D4524A5405F004967E1 /* PersistableRecordTests.swift */, @@ -1358,7 +1358,7 @@ 56419EA924A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56419E7F24A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, 56419EF124A54063004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */, - 56419EA324A54063004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56419EA324A54063004967E1 /* TableRecordDeleteTests.swift in Sources */, 56419EFB24A54063004967E1 /* FoundationDateComponentsTests.swift in Sources */, 56419E3D24A54062004967E1 /* FTS3TableBuilderTests.swift in Sources */, 56419DDF24A54062004967E1 /* FTS4TableBuilderTests.swift in Sources */, @@ -1367,7 +1367,7 @@ 56419D9B24A54062004967E1 /* TransactionObserverSavepointsTests.swift in Sources */, 56419E0F24A54062004967E1 /* InflectionsTests.swift in Sources */, 56419E2724A54062004967E1 /* FoundationURLTests.swift in Sources */, - 56419DD324A54062004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */, + 56419DD324A54062004967E1 /* TableRecordUpdateTests.swift in Sources */, 56419D6D24A54062004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */, 56419E2124A54062004967E1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */, 56419EDF24A54063004967E1 /* AssociationRowScopeSearchTests.swift in Sources */, @@ -1581,7 +1581,7 @@ 56419EAA24A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56419E8024A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, 56419EF224A54063004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */, - 56419EA424A54063004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56419EA424A54063004967E1 /* TableRecordDeleteTests.swift in Sources */, 56419EFC24A54063004967E1 /* FoundationDateComponentsTests.swift in Sources */, 56419E3E24A54062004967E1 /* FTS3TableBuilderTests.swift in Sources */, 56419DE024A54062004967E1 /* FTS4TableBuilderTests.swift in Sources */, @@ -1590,7 +1590,7 @@ 56419D9C24A54062004967E1 /* TransactionObserverSavepointsTests.swift in Sources */, 56419E1024A54062004967E1 /* InflectionsTests.swift in Sources */, 56419E2824A54062004967E1 /* FoundationURLTests.swift in Sources */, - 56419DD424A54062004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */, + 56419DD424A54062004967E1 /* TableRecordUpdateTests.swift in Sources */, 56419D6E24A54062004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */, 56419E2224A54062004967E1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */, 56419EE024A54063004967E1 /* AssociationRowScopeSearchTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 998a8c2cd..e62fc8a7f 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -11,8 +11,8 @@ 56419FC924A540A1004967E1 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFD24A54093004967E1 /* FetchRequestTests.swift */; }; 56419FCA24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */; }; 56419FCB24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */; }; - 56419FCC24A540A1004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFF24A54093004967E1 /* MutablePersistableRecordDeleteTests.swift */; }; - 56419FCD24A540A1004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFF24A54093004967E1 /* MutablePersistableRecordDeleteTests.swift */; }; + 56419FCC24A540A1004967E1 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */; }; + 56419FCD24A540A1004967E1 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */; }; 56419FCE24A540A1004967E1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0024A54093004967E1 /* AssociationBelongsToSQLDerivationTests.swift */; }; 56419FCF24A540A1004967E1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0024A54093004967E1 /* AssociationBelongsToSQLDerivationTests.swift */; }; 56419FD024A540A1004967E1 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0124A54093004967E1 /* MutablePersistableRecordTests.swift */; }; @@ -25,8 +25,8 @@ 56419FD724A540A1004967E1 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0424A54093004967E1 /* DatabaseRegionTests.swift */; }; 56419FD824A540A1004967E1 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */; }; 56419FD924A540A1004967E1 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */; }; - 56419FDA24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0624A54093004967E1 /* MutablePersistableRecordUpdateTests.swift */; }; - 56419FDB24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0624A54093004967E1 /* MutablePersistableRecordUpdateTests.swift */; }; + 56419FDA24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */; }; + 56419FDB24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */; }; 56419FDC24A540A1004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */; }; 56419FDD24A540A1004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */; }; 56419FDE24A540A1004967E1 /* NumericOverflowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0824A54093004967E1 /* NumericOverflowTests.swift */; }; @@ -455,14 +455,14 @@ 47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = ""; }; 56419EFD24A54093004967E1 /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = ""; }; - 56419EFF24A54093004967E1 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; + 56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = ""; }; 56419F0024A54093004967E1 /* AssociationBelongsToSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLDerivationTests.swift; sourceTree = ""; }; 56419F0124A54093004967E1 /* MutablePersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordTests.swift; sourceTree = ""; }; 56419F0224A54093004967E1 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = ""; }; 56419F0324A54093004967E1 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 56419F0424A54093004967E1 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; - 56419F0624A54093004967E1 /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = ""; }; + 56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = ""; }; 56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56419F0824A54093004967E1 /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; 56419F0924A54093004967E1 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; @@ -896,11 +896,11 @@ 56419F6D24A5409A004967E1 /* JoinSupportTests.swift */, 56419F7B24A5409B004967E1 /* MapCursorTests.swift */, 56419F4524A54097004967E1 /* MutablePersistableRecordChangesTests.swift */, - 56419EFF24A54093004967E1 /* MutablePersistableRecordDeleteTests.swift */, + 56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */, 56419F0224A54093004967E1 /* MutablePersistableRecordEncodableTests.swift */, 56419F3124A54096004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 56419F0124A54093004967E1 /* MutablePersistableRecordTests.swift */, - 56419F0624A54093004967E1 /* MutablePersistableRecordUpdateTests.swift */, + 56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */, 56419F0824A54093004967E1 /* NumericOverflowTests.swift */, 56419F0324A54093004967E1 /* OrderedDictionaryTests.swift */, 56419F1A24A54094004967E1 /* PersistableRecordTests.swift */, @@ -1316,7 +1316,7 @@ 5641A10424A540A1004967E1 /* DatabaseValueTests.swift in Sources */, 5641A06824A540A1004967E1 /* RowFetchTests.swift in Sources */, 5641A0E024A540A1004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */, - 56419FDA24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */, + 56419FDA24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */, 5641A01024A540A1004967E1 /* RecordEditedTests.swift in Sources */, 5641A0A624A540A1004967E1 /* AssociationHasManySQLTests.swift in Sources */, 56419FFC24A540A1004967E1 /* QueryInterfaceRequestTests.swift in Sources */, @@ -1366,7 +1366,7 @@ 5641A11424A540A1004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 5641A0D024A540A1004967E1 /* FoundationNSDecimalNumberTests.swift in Sources */, 5641A0C224A540A1004967E1 /* TransactionObserverTests.swift in Sources */, - 56419FCC24A540A1004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56419FCC24A540A1004967E1 /* TableRecordDeleteTests.swift in Sources */, 5641A00624A540A1004967E1 /* SQLExpressionLiteralTests.swift in Sources */, 5641A05824A540A1004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */, 5641A05624A540A1004967E1 /* AssociationPrefetchingSQLTests.swift in Sources */, @@ -1539,7 +1539,7 @@ 5641A10524A540A1004967E1 /* DatabaseValueTests.swift in Sources */, 5641A06924A540A1004967E1 /* RowFetchTests.swift in Sources */, 5641A0E124A540A1004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */, - 56419FDB24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */, + 56419FDB24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */, 5641A01124A540A1004967E1 /* RecordEditedTests.swift in Sources */, 5641A0A724A540A1004967E1 /* AssociationHasManySQLTests.swift in Sources */, 56419FFD24A540A1004967E1 /* QueryInterfaceRequestTests.swift in Sources */, @@ -1589,7 +1589,7 @@ 5641A11524A540A1004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 5641A0D124A540A1004967E1 /* FoundationNSDecimalNumberTests.swift in Sources */, 5641A0C324A540A1004967E1 /* TransactionObserverTests.swift in Sources */, - 56419FCD24A540A1004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56419FCD24A540A1004967E1 /* TableRecordDeleteTests.swift in Sources */, 5641A00724A540A1004967E1 /* SQLExpressionLiteralTests.swift in Sources */, 5641A05924A540A1004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */, 5641A05724A540A1004967E1 /* AssociationPrefetchingSQLTests.swift in Sources */, diff --git a/Tests/Crash/DatabasePoolCrashTests.swift b/Tests/Crash/DatabasePoolCrashTests.swift index 46acfc6a2..72770eacb 100644 --- a/Tests/Crash/DatabasePoolCrashTests.swift +++ b/Tests/Crash/DatabasePoolCrashTests.swift @@ -6,7 +6,7 @@ class DatabasePoolCrashTests: GRDBCrashTestCase { func testReaderCanNotStartTransaction() { assertCrash("DatabasePool readers can not start transactions or savepoints.") { try dbPool.read { db in - let statement = try db.makeUpdateStatement(sql: "BEGIN TRANSACTION") + let statement = try db.makeStatement(sql: "BEGIN TRANSACTION") } } } @@ -14,7 +14,7 @@ class DatabasePoolCrashTests: GRDBCrashTestCase { func testReaderCanNotStartSavepoint() { assertCrash("DatabasePool readers can not start transactions or savepoints.") { try dbPool.read { db in - let statement = try db.makeUpdateStatement(sql: "SAVEPOINT foo") + let statement = try db.makeStatement(sql: "SAVEPOINT foo") } } } diff --git a/Tests/Crash/DatabaseValueConvertibleCrashTests.swift b/Tests/Crash/DatabaseValueConvertibleCrashTests.swift index 6c4c21b3d..14aa7c406 100644 --- a/Tests/Crash/DatabaseValueConvertibleCrashTests.swift +++ b/Tests/Crash/DatabaseValueConvertibleCrashTests.swift @@ -25,7 +25,7 @@ class DatabaseValueConvertibleCrashTests: GRDBCrashTestCase { try db.execute(sql: "INSERT INTO ints (int) VALUES (1)") try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)") - let statement = try db.makeSelectStatement(sql: "SELECT int FROM ints ORDER BY int") + let statement = try db.makeStatement(sql: "SELECT int FROM ints ORDER BY int") let sequence = IntConvertible.fetch(statement) for _ in sequence { } } @@ -39,7 +39,7 @@ class DatabaseValueConvertibleCrashTests: GRDBCrashTestCase { try db.execute(sql: "INSERT INTO ints (int) VALUES (1)") try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)") - let statement = try db.makeSelectStatement(sql: "SELECT int FROM ints ORDER BY int") + let statement = try db.makeStatement(sql: "SELECT int FROM ints ORDER BY int") _ = IntConvertible.fetchAll(statement) } } diff --git a/Tests/Crash/StatementColumnConvertibleCrashTests.swift b/Tests/Crash/StatementColumnConvertibleCrashTests.swift index 52cb950c9..d69f9760a 100644 --- a/Tests/Crash/StatementColumnConvertibleCrashTests.swift +++ b/Tests/Crash/StatementColumnConvertibleCrashTests.swift @@ -10,7 +10,7 @@ class StatementColumnConvertibleCrashTests: GRDBCrashTestCase { try db.execute(sql: "INSERT INTO ints (int) VALUES (1)") try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)") - let statement = try db.makeSelectStatement(sql: "SELECT int FROM ints ORDER BY int") + let statement = try db.makeStatement(sql: "SELECT int FROM ints ORDER BY int") let sequence = try Int.fetch(statement) for _ in sequence { } } @@ -24,7 +24,7 @@ class StatementColumnConvertibleCrashTests: GRDBCrashTestCase { try db.execute(sql: "INSERT INTO ints (int) VALUES (1)") try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)") - let statement = try db.makeSelectStatement(sql: "SELECT int FROM ints ORDER BY int") + let statement = try db.makeStatement(sql: "SELECT int FROM ints ORDER BY int") _ = try Int.fetchAll(statement) } } diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index 68d42d3d8..55c1f8bdb 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -7,8 +7,9 @@ class AssociationBelongsToSQLTests: GRDBTestCase { func testSingleColumnNoForeignKeyNoPrimaryKey() throws { struct Child : TableRecord, EncodableRecord { static let databaseTableName = "children" + var parentID: Int? func encode(to container: inout PersistenceContainer) { - container["parentId"] = 1 + container["parentId"] = parentID } } @@ -28,8 +29,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentId")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -55,15 +60,28 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."rowid" = "children"."parentId") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "rowid" = 1 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentID: 1).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE "custom"."rowid" = 1 """) + + try assertEqualSQL(db, Child(parentID: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -89,12 +107,20 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentID: 1).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 1 """) + + try assertEqualSQL(db, Child(parentID: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } } } @@ -102,8 +128,9 @@ class AssociationBelongsToSQLTests: GRDBTestCase { func testSingleColumnNoForeignKey() throws { struct Child : TableRecord, EncodableRecord { static let databaseTableName = "children" + var parentID: Int? func encode(to container: inout PersistenceContainer) { - container["parentId"] = 1 + container["parentId"] = parentID } } @@ -123,8 +150,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentId")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -150,15 +181,28 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentID: 1).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 1 """) + + try assertEqualSQL(db, Child(parentID: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -184,12 +228,20 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentID: 1).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 1 """) + + try assertEqualSQL(db, Child(parentID: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } } } @@ -197,8 +249,9 @@ class AssociationBelongsToSQLTests: GRDBTestCase { func testSingleColumnSingleForeignKey() throws { struct Child : TableRecord, EncodableRecord { static let databaseTableName = "children" + var parentID: Int? func encode(to container: inout PersistenceContainer) { - container["parentId"] = 1 + container["parentId"] = parentID } } @@ -218,8 +271,10 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self) + for association in [ + Child.belongsTo(Parent.self), + Child.belongsTo(Table(Parent.databaseTableName)), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -245,15 +300,28 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentID: 1).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 1 """) + + try assertEqualSQL(db, Child(parentID: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentId")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -279,15 +347,28 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentID: 1).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 1 """) + + try assertEqualSQL(db, Child(parentID: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -313,12 +394,20 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentID: 1).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 1 """) + + try assertEqualSQL(db, Child(parentID: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } } } @@ -326,9 +415,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase { func testSingleColumnSeveralForeignKeys() throws { struct Child : TableRecord, EncodableRecord { static let databaseTableName = "children" + var parent1ID: Int? + var parent2ID: Int? func encode(to container: inout PersistenceContainer) { - container["parent1Id"] = 1 - container["parent2Id"] = 2 + container["parent1Id"] = parent1ID + container["parent2Id"] = parent2ID } } @@ -349,8 +440,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1Id")])) + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent1Id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent1Id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -376,15 +471,28 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 1 """) + + try assertEqualSQL(db, Child(parent1ID: nil, parent2ID: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1ID: nil, parent2ID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1Id")], to: [Column("id")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent1Id")], to: [Column("id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent1Id")], to: [Column("id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -410,15 +518,28 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 1 """) + + try assertEqualSQL(db, Child(parent1ID: nil, parent2ID: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1ID: nil, parent2ID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2Id")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent2Id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent2Id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -444,15 +565,28 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 2 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 2 """) + + try assertEqualSQL(db, Child(parent1ID: nil, parent2ID: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1ID: nil, parent2ID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2Id")], to: [Column("id")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent2Id")], to: [Column("id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent2Id")], to: [Column("id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -478,12 +612,20 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 2 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 2 """) + + try assertEqualSQL(db, Child(parent1ID: nil, parent2ID: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1ID: nil, parent2ID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } } } @@ -491,9 +633,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase { func testCompoundColumnNoForeignKeyNoPrimaryKey() throws { struct Child : TableRecord, EncodableRecord { static let databaseTableName = "children" + var parentA: Int? + var parentB: Int? func encode(to container: inout PersistenceContainer) { - container["parentA"] = 1 - container["parentB"] = 2 + container["parentA"] = parentA + container["parentB"] = parentB } } @@ -515,8 +659,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -542,12 +690,34 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 1) AND ("custom"."b" = 2) """) + + try assertEqualSQL(db, Child(parentA: 1, parentB: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: 1, parentB: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parentA: nil, parentB: 2).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: nil, parentB: 2).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parentA: nil, parentB: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: nil, parentB: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } } } @@ -555,9 +725,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase { func testCompoundColumnNoForeignKey() throws { struct Child : TableRecord, EncodableRecord { static let databaseTableName = "children" + var parentA: Int? + var parentB: Int? func encode(to container: inout PersistenceContainer) { - container["parentA"] = 1 - container["parentB"] = 2 + container["parentA"] = parentA + container["parentB"] = parentB } } @@ -580,8 +752,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentA"), Column("parentB")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -607,15 +783,42 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 1) AND ("custom"."b" = 2) """) + + try assertEqualSQL(db, Child(parentA: 1, parentB: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: 1, parentB: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parentA: nil, parentB: 2).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: nil, parentB: 2).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parentA: nil, parentB: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: nil, parentB: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -641,12 +844,34 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 1) AND ("custom"."b" = 2) """) + + try assertEqualSQL(db, Child(parentA: 1, parentB: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: 1, parentB: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parentA: nil, parentB: 2).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: nil, parentB: 2).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parentA: nil, parentB: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: nil, parentB: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } } } @@ -654,9 +879,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase { func testCompoundColumnSingleForeignKey() throws { struct Child : TableRecord, EncodableRecord { static let databaseTableName = "children" + var parentA: Int? + var parentB: Int? func encode(to container: inout PersistenceContainer) { - container["parentA"] = 1 - container["parentB"] = 2 + container["parentA"] = parentA + container["parentB"] = parentB } } @@ -680,8 +907,10 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self) + for association in [ + Child.belongsTo(Parent.self), + Child.belongsTo(Table(Parent.databaseTableName)), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -707,15 +936,42 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 1) AND ("custom"."b" = 2) """) + + try assertEqualSQL(db, Child(parentA: 1, parentB: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: 2, parentB: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parentA: nil, parentB: 2).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: nil, parentB: 2).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parentA: nil, parentB: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: nil, parentB: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentA"), Column("parentB")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -741,15 +997,42 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 1) AND ("custom"."b" = 2) """) + + try assertEqualSQL(db, Child(parentA: 1, parentB: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: 1, parentB: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parentA: nil, parentB: 2).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: nil, parentB: 2).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parentA: nil, parentB: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: nil, parentB: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -775,12 +1058,34 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 1) AND ("custom"."b" = 2) """) + + try assertEqualSQL(db, Child(parentA: 1, parentB: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: 1, parentB: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parentA: nil, parentB: 2).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: nil, parentB: 2).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parentA: nil, parentB: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parentA: nil, parentB: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } } } @@ -788,11 +1093,15 @@ class AssociationBelongsToSQLTests: GRDBTestCase { func testCompoundColumnSeveralForeignKeys() throws { struct Child : TableRecord, EncodableRecord { static let databaseTableName = "children" + var parent1A: Int? + var parent1B: Int? + var parent2A: Int? + var parent2B: Int? func encode(to container: inout PersistenceContainer) { - container["parent1A"] = 1 - container["parent1B"] = 2 - container["parent2A"] = 3 - container["parent2B"] = 4 + container["parent1A"] = parent1A + container["parent1B"] = parent1B + container["parent2A"] = parent2A + container["parent2B"] = parent2B } } @@ -819,8 +1128,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1A"), Column("parent1B")])) + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent1A"), Column("parent1B")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent1A"), Column("parent1B")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -846,15 +1159,42 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 1) AND ("custom"."b" = 2) """) + + try assertEqualSQL(db, Child(parent1A: 1, parent1B: nil, parent2A: 3, parent2B: 4).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1A: 1, parent1B: nil, parent2A: 3, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parent1A: nil, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1A: nil, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parent1A: nil, parent1B: nil, parent2A: 3, parent2B: 4).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1A: nil, parent1B: nil, parent2A: 3, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -880,15 +1220,42 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 1) AND ("custom"."b" = 2) """) + + try assertEqualSQL(db, Child(parent1A: 1, parent1B: nil, parent2A: 3, parent2B: 4).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1A: 1, parent1B: nil, parent2A: 3, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parent1A: nil, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1A: nil, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parent1A: nil, parent1B: nil, parent2A: 3, parent2B: 4).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1A: nil, parent1B: nil, parent2A: 3, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2A"), Column("parent2B")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent2A"), Column("parent2B")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent2A"), Column("parent2B")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -914,15 +1281,42 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 3) AND ("b" = 4) """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 3) AND ("custom"."b" = 4) """) + + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: 4).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -948,12 +1342,34 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 3) AND ("b" = 4) """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 3) AND ("custom"."b" = 4) """) + + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: 4).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) + + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: nil).request(for: association), """ + SELECT * FROM "parents" WHERE 0 + """) + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "parents" "custom" WHERE 0 + """) } } } @@ -1002,8 +1418,9 @@ class AssociationBelongsToSQLTests: GRDBTestCase { func testCaseInsensitivity() throws { struct Child : TableRecord, EncodableRecord { static let databaseTableName = "CHILDREN" + var parentID: Int? func encode(to container: inout PersistenceContainer) { - container["PaReNtId"] = 1 + container["PaReNtId"] = parentID } } @@ -1023,8 +1440,10 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self) + for association in [ + Child.belongsTo(Parent.self), + Child.belongsTo(Table(Parent.databaseTableName)), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "CHILDREN".*, "PARENTS".* \ FROM "CHILDREN" \ @@ -1050,15 +1469,28 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "CHILDREN" \ LEFT JOIN "PARENTS" ON ("PARENTS"."id" = "CHILDREN"."parentId") AND ("PARENTS"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "PARENTS" WHERE "id" = 1 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentID: 1).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "PARENTS" "custom" WHERE "custom"."id" = 1 """) + + try assertEqualSQL(db, Child(parentID: nil).request(for: association), """ + SELECT * FROM "PARENTS" WHERE 0 + """) + try assertEqualSQL(db, Child(parentID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "PARENTS" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("PARENTID")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("PARENTID")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("PARENTID")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "CHILDREN".*, "PARENTS".* \ FROM "CHILDREN" \ @@ -1084,15 +1516,28 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "CHILDREN" \ LEFT JOIN "PARENTS" ON ("PARENTS"."id" = "CHILDREN"."parentId") AND ("PARENTS"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "PARENTS" WHERE "id" = 1 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentID: 1).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "PARENTS" "custom" WHERE "custom"."id" = 1 """) + + try assertEqualSQL(db, Child(parentID: nil).request(for: association), """ + SELECT * FROM "PARENTS" WHERE 0 + """) + try assertEqualSQL(db, Child(parentID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "PARENTS" "custom" WHERE 0 + """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("PARENTID")], to: [Column("ID")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("PARENTID")], to: [Column("ID")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("PARENTID")], to: [Column("ID")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "CHILDREN".*, "PARENTS".* \ FROM "CHILDREN" \ @@ -1118,12 +1563,20 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "CHILDREN" \ LEFT JOIN "PARENTS" ON ("PARENTS"."ID" = "CHILDREN"."PARENTID") AND ("PARENTS"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "PARENTS" WHERE "ID" = 1 """) - try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + try assertEqualSQL(db, Child(parentID: 1).request(for: association).aliased(TableAlias(name: "custom")), """ SELECT "custom".* FROM "PARENTS" "custom" WHERE "custom"."ID" = 1 """) + + try assertEqualSQL(db, Child(parentID: nil).request(for: association), """ + SELECT * FROM "PARENTS" WHERE 0 + """) + try assertEqualSQL(db, Child(parentID: nil).request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT "custom".* FROM "PARENTS" "custom" WHERE 0 + """) } } } @@ -1134,7 +1587,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { struct Book: TableRecord { static let author = belongsTo(Author.self) } - + struct Author: TableRecord { } @@ -1162,7 +1615,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { struct Book: TableRecord { static let author = belongsTo(Author.self) } - + struct Author: TableRecord { } diff --git a/Tests/GRDBTests/AssociationHasManySQLTests.swift b/Tests/GRDBTests/AssociationHasManySQLTests.swift index 71ab378b0..ddd47d74e 100644 --- a/Tests/GRDBTests/AssociationHasManySQLTests.swift +++ b/Tests/GRDBTests/AssociationHasManySQLTests.swift @@ -3,7 +3,7 @@ import GRDB /// Test SQL generation class AssociationHasManySQLTests: GRDBTestCase { - + func testSingleColumnNoForeignKeyNoPrimaryKey() throws { struct Child : TableRecord { static let databaseTableName = "children" @@ -11,9 +11,11 @@ class AssociationHasManySQLTests: GRDBTestCase { struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" + var id: Int? + var rowid: Int? func encode(to container: inout PersistenceContainer) { - container["id"] = 1 - container["rowid"] = 2 + container["id"] = id + container["rowid"] = rowid } } @@ -28,8 +30,12 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")])) + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentId")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -50,10 +56,21 @@ class AssociationHasManySQLTests: GRDBTestCase { FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."rowid" """) - try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parentId\" = 2") + + try assertEqualSQL(db, Parent(id: 1, rowid: 2).request(for: association), """ + SELECT * FROM "children" WHERE "parentId" = 2 + """) + try assertEqualSQL(db, Parent(id: 1, rowid: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -74,7 +91,13 @@ class AssociationHasManySQLTests: GRDBTestCase { FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) - try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parentId\" = 1") + + try assertEqualSQL(db, Parent(id: 1, rowid: 2).request(for: association), """ + SELECT * FROM "children" WHERE "parentId" = 1 + """) + try assertEqualSQL(db, Parent(id: nil, rowid: 2).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } } } @@ -86,8 +109,9 @@ class AssociationHasManySQLTests: GRDBTestCase { struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" + var id: Int? func encode(to container: inout PersistenceContainer) { - container["id"] = 1 + container["id"] = id } } @@ -102,8 +126,12 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")])) + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentId")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -124,10 +152,21 @@ class AssociationHasManySQLTests: GRDBTestCase { FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) - try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parentId\" = 1") + + try assertEqualSQL(db, Parent(id: 1).request(for: association), """ + SELECT * FROM "children" WHERE "parentId" = 1 + """) + try assertEqualSQL(db, Parent(id: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -148,7 +187,13 @@ class AssociationHasManySQLTests: GRDBTestCase { FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) - try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parentId\" = 1") + + try assertEqualSQL(db, Parent(id: 1).request(for: association), """ + SELECT * FROM "children" WHERE "parentId" = 1 + """) + try assertEqualSQL(db, Parent(id: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } } } @@ -160,8 +205,9 @@ class AssociationHasManySQLTests: GRDBTestCase { struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" + var id: Int? func encode(to container: inout PersistenceContainer) { - container["id"] = 1 + container["id"] = id } } @@ -176,8 +222,10 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self) + for association in [ + Parent.hasMany(Child.self), + Parent.hasMany(Table(Child.databaseTableName)), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -198,10 +246,21 @@ class AssociationHasManySQLTests: GRDBTestCase { FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) - try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parentId\" = 1") + + try assertEqualSQL(db, Parent(id: 1).request(for: association), """ + SELECT * FROM "children" WHERE "parentId" = 1 + """) + try assertEqualSQL(db, Parent(id: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentId")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -222,10 +281,21 @@ class AssociationHasManySQLTests: GRDBTestCase { FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) - try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parentId\" = 1") + + try assertEqualSQL(db, Parent(id: 1).request(for: association), """ + SELECT * FROM "children" WHERE "parentId" = 1 + """) + try assertEqualSQL(db, Parent(id: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -246,7 +316,13 @@ class AssociationHasManySQLTests: GRDBTestCase { FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) - try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parentId\" = 1") + + try assertEqualSQL(db, Parent(id: 1).request(for: association), """ + SELECT * FROM "children" WHERE "parentId" = 1 + """) + try assertEqualSQL(db, Parent(id: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } } } @@ -258,8 +334,9 @@ class AssociationHasManySQLTests: GRDBTestCase { struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" + var id: Int? func encode(to container: inout PersistenceContainer) { - container["id"] = 1 + container["id"] = id } } @@ -275,8 +352,12 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent1Id")])) + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent1Id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1Id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -297,10 +378,21 @@ class AssociationHasManySQLTests: GRDBTestCase { FROM "parents" \ LEFT JOIN "children" ON "children"."parent1Id" = "parents"."id" """) - try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parent1Id\" = 1") + + try assertEqualSQL(db, Parent(id: 1).request(for: association), """ + SELECT * FROM "children" WHERE "parent1Id" = 1 + """) + try assertEqualSQL(db, Parent(id: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent1Id")], to: [Column("id")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent1Id")], to: [Column("id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1Id")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -321,10 +413,21 @@ class AssociationHasManySQLTests: GRDBTestCase { FROM "parents" \ LEFT JOIN "children" ON "children"."parent1Id" = "parents"."id" """) - try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parent1Id\" = 1") + + try assertEqualSQL(db, Parent(id: 1).request(for: association), """ + SELECT * FROM "children" WHERE "parent1Id" = 1 + """) + try assertEqualSQL(db, Parent(id: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent2Id")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent2Id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2Id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -345,10 +448,21 @@ class AssociationHasManySQLTests: GRDBTestCase { FROM "parents" \ LEFT JOIN "children" ON "children"."parent2Id" = "parents"."id" """) - try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parent2Id\" = 1") + + try assertEqualSQL(db, Parent(id: 1).request(for: association), """ + SELECT * FROM "children" WHERE "parent2Id" = 1 + """) + try assertEqualSQL(db, Parent(id: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent2Id")], to: [Column("id")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent2Id")], to: [Column("id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2Id")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -369,7 +483,13 @@ class AssociationHasManySQLTests: GRDBTestCase { FROM "parents" \ LEFT JOIN "children" ON "children"."parent2Id" = "parents"."id" """) - try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parent2Id\" = 1") + + try assertEqualSQL(db, Parent(id: 1).request(for: association), """ + SELECT * FROM "children" WHERE "parent2Id" = 1 + """) + try assertEqualSQL(db, Parent(id: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } } } @@ -381,9 +501,11 @@ class AssociationHasManySQLTests: GRDBTestCase { struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" + var a: Int? + var b: Int? func encode(to container: inout PersistenceContainer) { - container["a"] = 1 - container["b"] = 2 + container["a"] = a + container["b"] = b } } @@ -400,8 +522,12 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -422,7 +548,19 @@ class AssociationHasManySQLTests: GRDBTestCase { 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)") + + try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2) + """) + try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } } } @@ -434,9 +572,11 @@ class AssociationHasManySQLTests: GRDBTestCase { struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" + var a: Int? + var b: Int? func encode(to container: inout PersistenceContainer) { - container["a"] = 1 - container["b"] = 2 + container["a"] = a + container["b"] = b } } @@ -454,8 +594,12 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -476,10 +620,27 @@ class AssociationHasManySQLTests: GRDBTestCase { 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)") + + try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2) + """) + try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -500,7 +661,19 @@ class AssociationHasManySQLTests: GRDBTestCase { 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)") + + try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2) + """) + try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } } } @@ -512,9 +685,11 @@ class AssociationHasManySQLTests: GRDBTestCase { struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" + var a: Int? + var b: Int? func encode(to container: inout PersistenceContainer) { - container["a"] = 1 - container["b"] = 2 + container["a"] = a + container["b"] = b } } @@ -533,8 +708,10 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self) + for association in [ + Parent.hasMany(Child.self), + Parent.hasMany(Table(Child.databaseTableName)), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -555,10 +732,27 @@ class AssociationHasManySQLTests: GRDBTestCase { 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)") + + try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2) + """) + try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -579,10 +773,27 @@ class AssociationHasManySQLTests: GRDBTestCase { 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)") + + try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2) + """) + try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -603,7 +814,19 @@ class AssociationHasManySQLTests: GRDBTestCase { 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)") + + try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2) + """) + try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } } } @@ -615,9 +838,11 @@ class AssociationHasManySQLTests: GRDBTestCase { struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" + var a: Int? + var b: Int? func encode(to container: inout PersistenceContainer) { - container["a"] = 1 - container["b"] = 2 + container["a"] = a + container["b"] = b } } @@ -639,8 +864,12 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")])) + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent1A"), Column("parent1B")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1A"), Column("parent1B")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -661,10 +890,27 @@ class AssociationHasManySQLTests: GRDBTestCase { 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)") + + try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE ("parent1A" = 1) AND ("parent1B" = 2) + """) + try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -685,10 +931,27 @@ class AssociationHasManySQLTests: GRDBTestCase { 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)") + + try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE ("parent1A" = 1) AND ("parent1B" = 2) + """) + try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent2A"), Column("parent2B")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent2A"), Column("parent2B")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2A"), Column("parent2B")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -709,10 +972,27 @@ class AssociationHasManySQLTests: GRDBTestCase { 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)") + + try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE ("parent2A" = 1) AND ("parent2B" = 2) + """) + try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -733,7 +1013,19 @@ class AssociationHasManySQLTests: GRDBTestCase { 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)") + + try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE ("parent2A" = 1) AND ("parent2B" = 2) + """) + try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) + try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ + SELECT * FROM "children" WHERE 0 + """) } } } @@ -769,8 +1061,9 @@ class AssociationHasManySQLTests: GRDBTestCase { } struct Parent: TableRecord, EncodableRecord { static let children = hasMany(Child.self) + var id: Int? func encode(to container: inout PersistenceContainer) { - container["id"] = 1 + container["id"] = id } } @@ -801,12 +1094,19 @@ class AssociationHasManySQLTests: GRDBTestCase { JOIN "child" ON "child"."parentId" = "parent"."id" \ JOIN "toy" ON "toy"."childId" = "child"."id" """) - try assertEqualSQL(db, Parent().request(for: association), """ + + try assertEqualSQL(db, Parent(id: 1).request(for: association), """ SELECT "child".* \ FROM "child" \ JOIN "toy" ON "toy"."childId" = "child"."id" \ WHERE "child"."parentId" = 1 """) + try assertEqualSQL(db, Parent(id: nil).request(for: association), """ + SELECT "child".* \ + FROM "child" \ + JOIN "toy" ON "toy"."childId" = "child"."id" \ + WHERE 0 + """) } do { // not a realistic use case, but testable anyway @@ -823,12 +1123,19 @@ class AssociationHasManySQLTests: GRDBTestCase { JOIN "child" ON "child"."parentId" = "parent1"."id" \ JOIN "parent" "parent2" ON "parent2"."id" = "child"."parentId" """) - try assertEqualSQL(db, Parent().request(for: association), """ + + try assertEqualSQL(db, Parent(id: 1).request(for: association), """ SELECT "child".* \ FROM "child" \ JOIN "parent" ON "parent"."id" = "child"."parentId" \ WHERE "child"."parentId" = 1 """) + try assertEqualSQL(db, Parent(id: nil).request(for: association), """ + SELECT "child".* \ + FROM "child" \ + JOIN "parent" ON "parent"."id" = "child"."parentId" \ + WHERE 0 + """) } } } diff --git a/Tests/GRDBTests/AssociationHasOneSQLTests.swift b/Tests/GRDBTests/AssociationHasOneSQLTests.swift index 629e2f957..66d704621 100644 --- a/Tests/GRDBTests/AssociationHasOneSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasOneSQLTests.swift @@ -3,7 +3,7 @@ import GRDB /// Test SQL generation class AssociationHasOneSQLTests: GRDBTestCase { - + func testSingleColumnNoForeignKeyNoPrimaryKey() throws { struct Child : TableRecord { static let databaseTableName = "children" @@ -28,8 +28,12 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentId")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -52,8 +56,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -102,8 +111,12 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentId")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -126,8 +139,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -176,8 +194,10 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self) + for association in [ + Parent.hasOne(Child.self), + Parent.hasOne(Table(Child.databaseTableName)), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -200,8 +220,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parentId\" = 1") } - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentId")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -224,8 +249,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -275,8 +305,12 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1Id")])) + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent1Id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1Id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -299,8 +333,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent1Id")], to: [Column("id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1Id")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -323,8 +362,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parent1Id\" = 1") } - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2Id")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent2Id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2Id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -347,8 +391,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent2Id")], to: [Column("id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2Id")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -400,8 +449,12 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -454,8 +507,12 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -478,8 +535,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -533,8 +595,10 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self) + for association in [ + Parent.hasOne(Child.self), + Parent.hasOne(Table(Child.databaseTableName)), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -557,8 +621,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -581,8 +650,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -639,8 +713,12 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")])) + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent1A"), Column("parent1B")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1A"), Column("parent1B")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -663,8 +741,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -687,8 +770,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent2A"), Column("parent2B")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2A"), Column("parent2B")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -711,8 +799,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ diff --git a/Tests/GRDBTests/CommonTableExpressionTests.swift b/Tests/GRDBTests/CommonTableExpressionTests.swift index 0689d0105..1352da2de 100644 --- a/Tests/GRDBTests/CommonTableExpressionTests.swift +++ b/Tests/GRDBTests/CommonTableExpressionTests.swift @@ -295,21 +295,25 @@ class CommonTableExpressionTests: GRDBTestCase { literal: "SELECT \("O'Brien")") let assoc1 = T.association(to: cte1) let assoc2 = cte1.association(to: cte2) - let assoc3 = cte2.association(to: T.self) - let request = T.all() - .with(cte1) - .with(cte2) - .including(required: assoc1.including(required: assoc2.including(required: assoc3))) - try assertEqualSQL(db, request, """ - WITH \ - "cte1" AS (SELECT * FROM "t"), \ - "cte2" AS (SELECT 'O''Brien') \ - SELECT "t1".*, "cte1".*, "cte2".*, "t2".* \ - FROM "t" "t1" \ - JOIN "cte1" \ - JOIN "cte2" \ - JOIN "t" "t2" - """) + for assoc3 in [ + cte2.association(to: T.self), + cte2.association(to: Table("t")), + ] { + let request = T.all() + .with(cte1) + .with(cte2) + .including(required: assoc1.including(required: assoc2.including(required: assoc3))) + try assertEqualSQL(db, request, """ + WITH \ + "cte1" AS (SELECT * FROM "t"), \ + "cte2" AS (SELECT 'O''Brien') \ + SELECT "t1".*, "cte1".*, "cte2".*, "t2".* \ + FROM "t" "t1" \ + JOIN "cte1" \ + JOIN "cte2" \ + JOIN "t" "t2" + """) + } } // Use CTE as a subquery diff --git a/Tests/GRDBTests/DatabaseErrorTests.swift b/Tests/GRDBTests/DatabaseErrorTests.swift index f37868448..7f7155339 100644 --- a/Tests/GRDBTests/DatabaseErrorTests.swift +++ b/Tests/GRDBTests/DatabaseErrorTests.swift @@ -88,7 +88,7 @@ class DatabaseErrorTests: GRDBTestCase { // statement.execute(arguments) try dbQueue.inDatabase { db in do { - let statement = try db.makeUpdateStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)") + let statement = try db.makeStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)") try statement.execute(arguments: [1, "Bobby"]) XCTFail() } catch let error as DatabaseError { @@ -103,7 +103,7 @@ class DatabaseErrorTests: GRDBTestCase { // statement.execute() try dbQueue.inDatabase { db in do { - let statement = try db.makeUpdateStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)") + let statement = try db.makeStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)") statement.arguments = [1, "Bobby"] try statement.execute() XCTFail() diff --git a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift index 78c4acfe6..628f0de63 100644 --- a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift @@ -201,12 +201,12 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { s2.signal() } let block2 = { [weak dbPool] () in - var statement: UpdateStatement? = nil + var statement: Statement? = nil do { if let dbPool = dbPool { do { try dbPool.write { db in - statement = try db.makeUpdateStatement(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") + statement = try db.makeStatement(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") s1.signal() } } catch { diff --git a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift index c73da0ca9..2c15903b0 100644 --- a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift +++ b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift @@ -115,7 +115,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { // // let block1 = { () in // try! dbPool.read { db in -// let stmt = try! db.cachedSelectStatement(sql: "SELECT * FROM items") +// let stmt = try! db.cachedStatement(sql: "SELECT * FROM items") // XCTAssertEqual(try Int.fetchOne(stmt)!, 1) // s1.signal() // } @@ -123,7 +123,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { // let block2 = { () in // try! dbPool.read { db in // _ = s1.wait(timeout: .distantFuture) -// let stmt = try! db.cachedSelectStatement(sql: "SELECT * FROM items") +// let stmt = try! db.cachedStatement(sql: "SELECT * FROM items") // XCTAssertEqual(try Int.fetchOne(stmt)!, 1) // } // } @@ -177,7 +177,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { _ = s1.wait(timeout: .distantFuture) try! dbPool.read { db in // activate snapshot isolation so that foo table is visible during the whole read. Any read is enough. - try db.makeSelectStatement(sql: "SELECT * FROM sqlite_master").makeCursor().next() + try db.makeStatement(sql: "SELECT * FROM sqlite_master").makeCursor().next() // warm cache _ = try db.primaryKey("foo") // cache contains the primary key diff --git a/Tests/GRDBTests/DatabaseQueueReadOnlyTests.swift b/Tests/GRDBTests/DatabaseQueueReadOnlyTests.swift index 8eb7e3f27..577b2e1b5 100644 --- a/Tests/GRDBTests/DatabaseQueueReadOnlyTests.swift +++ b/Tests/GRDBTests/DatabaseQueueReadOnlyTests.swift @@ -22,7 +22,7 @@ class DatabaseQueueReadOnlyTests : GRDBTestCase { dbConfiguration.readonly = true let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") let statement = try dbQueue.inDatabase { db in - try db.makeUpdateStatement(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") + try db.makeStatement(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") } do { try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift b/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift index ec2de36f0..6868f8bb0 100644 --- a/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift @@ -116,12 +116,12 @@ class DatabaseQueueReleaseMemoryTests: GRDBTestCase { s2.signal() } let block2 = { [weak dbQueue] () in - var statement: UpdateStatement? = nil + var statement: Statement? = nil do { if let dbQueue = dbQueue { do { try dbQueue.write { db in - statement = try db.makeUpdateStatement(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") + statement = try db.makeStatement(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") s1.signal() } } catch { diff --git a/Tests/GRDBTests/DatabaseQueueSchemaCacheTests.swift b/Tests/GRDBTests/DatabaseQueueSchemaCacheTests.swift index 2ce7c1dd9..0dc978170 100644 --- a/Tests/GRDBTests/DatabaseQueueSchemaCacheTests.swift +++ b/Tests/GRDBTests/DatabaseQueueSchemaCacheTests.swift @@ -4,35 +4,25 @@ import XCTest class DatabaseQueueSchemaCacheTests : GRDBTestCase { func testCache() throws { - let dbQueue = try makeDatabaseQueue() - - try dbQueue.inDatabase { db in + try makeDatabaseQueue().inDatabase { db in try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") - } - - dbQueue.inDatabase { db in + // Assert that cache is empty XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil) - } - - try dbQueue.inDatabase { db in + // Warm cache let primaryKey = try db.primaryKey("items") XCTAssertEqual(primaryKey.rowIDColumn, "id") // Assert that cache is warmed XCTAssertTrue(db.schemaCache[.main].primaryKey("items") != nil) - } - - try dbQueue.inDatabase { db in + // Empty cache after schema change try db.execute(sql: "DROP TABLE items") // Assert that cache is empty XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil) - } - - try dbQueue.inDatabase { db in + do { // Assert that cache is used: we expect an error now that // the cache is empty. @@ -46,6 +36,32 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase { } } + func testCacheInvalidationWithCursor() throws { + try makeDatabaseQueue().inDatabase { db in + try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") + + // Assert that cache is empty + XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil) + + // Warm cache + let primaryKey = try db.primaryKey("items") + XCTAssertEqual(primaryKey.rowIDColumn, "id") + + // Assert that cache is warmed + XCTAssertTrue(db.schemaCache[.main].primaryKey("items") != nil) + + // Assert that cache is still warm until the DROP TABLE statement has been executed + let statement = try db.makeStatement(sql: "DROP TABLE items") + XCTAssertTrue(db.schemaCache[.main].primaryKey("items") != nil) + let cursor = try Row.fetchCursor(statement) + XCTAssertTrue(db.schemaCache[.main].primaryKey("items") != nil) + _ = try cursor.next() + + // Assert that cache is empty after cursor has run sqlite3_step + XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil) + } + } + func testTempCache() throws { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 316a9b7fd..d6e1db61b 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -265,13 +265,13 @@ class DatabaseRegionTests : GRDBTestCase { do { // Select the rowid - let statement = try db.makeSelectStatement(sql: "SELECT id FROM foo") + let statement = try db.makeStatement(sql: "SELECT id FROM foo") let expectedRegion = DatabaseRegion(table: "foo") XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(*)") } do { - let statement = try db.makeSelectStatement(sql: "SELECT ID FROM FOO") + let statement = try db.makeStatement(sql: "SELECT ID FROM FOO") let expectedRegion = DatabaseRegion(table: "foo") XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(*)") @@ -286,33 +286,33 @@ class DatabaseRegionTests : GRDBTestCase { try db.execute(sql: "CREATE TABLE bar (id INTEGER PRIMARY KEY, fooId INTEGER)") do { - let statement = try db.makeSelectStatement(sql: "SELECT name FROM foo") + let statement = try db.makeStatement(sql: "SELECT name FROM foo") let expectedRegion = DatabaseRegion(table: "foo", columns: ["name"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(name)") } do { - let statement = try db.makeSelectStatement(sql: "SELECT NAME FROM FOO") + let statement = try db.makeStatement(sql: "SELECT NAME FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["name"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(name)") } do { - let statement = try db.makeSelectStatement(sql: "SELECT foo.name FROM foo JOIN bar ON fooId = foo.id") + let statement = try db.makeStatement(sql: "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.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "bar(fooId),foo(id,name)") } do { - let statement = try db.makeSelectStatement(sql: "SELECT FOO.NAME FROM FOO JOIN BAR ON FOOID = FOO.ID") + let statement = try db.makeStatement(sql: "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.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "bar(fooId),foo(id,name)") } do { - let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM foo") + let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM foo") if sqlite3_libversion_number() < 3019000 { let expectedRegion = DatabaseRegion.fullDatabase XCTAssertEqual(statement.databaseRegion, expectedRegion) @@ -324,7 +324,7 @@ class DatabaseRegionTests : GRDBTestCase { } } do { - let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM FOO") + let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM FOO") if sqlite3_libversion_number() < 3019000 { let expectedRegion = DatabaseRegion.fullDatabase XCTAssertEqual(statement.databaseRegion, expectedRegion) @@ -542,7 +542,7 @@ class DatabaseRegionTests : GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (id INTEGER PRIMARY KEY, bar TEXT, baz TEXT, qux TEXT)") do { - let statement = try db.makeUpdateStatement(sql: "UPDATE foo SET bar = 'bar', baz = 'baz' WHERE id = 1") + let statement = try db.makeStatement(sql: "UPDATE foo SET bar = 'bar', baz = 'baz' WHERE id = 1") XCTAssertFalse(statement.invalidatesDatabaseSchemaCache) XCTAssertEqual(statement.databaseEventKinds.count, 1) guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else { @@ -553,7 +553,7 @@ class DatabaseRegionTests : GRDBTestCase { XCTAssertEqual(columnNames, Set(["bar", "baz"])) } do { - let statement = try db.makeUpdateStatement(sql: "UPDATE FOO SET BAR = 'bar', BAZ = 'baz' WHERE ID = 1") + let statement = try db.makeStatement(sql: "UPDATE FOO SET BAR = 'bar', BAZ = 'baz' WHERE ID = 1") XCTAssertFalse(statement.invalidatesDatabaseSchemaCache) XCTAssertEqual(statement.databaseEventKinds.count, 1) guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else { @@ -582,19 +582,19 @@ class DatabaseRegionTests : GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (name TEXT)") do { - let statement = try db.makeSelectStatement(sql: "SELECT rowid FROM FOO") + let statement = try db.makeStatement(sql: "SELECT rowid FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(ROWID)") } do { - let statement = try db.makeSelectStatement(sql: "SELECT _ROWID_ FROM FOO") + let statement = try db.makeStatement(sql: "SELECT _ROWID_ FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(ROWID)") } do { - let statement = try db.makeSelectStatement(sql: "SELECT oID FROM FOO") + let statement = try db.makeStatement(sql: "SELECT oID FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(ROWID)") @@ -611,7 +611,7 @@ class DatabaseRegionTests : GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (name TEXT)") do { - let statement = try db.makeUpdateStatement(sql: "UPDATE foo SET rowid = 1") + let statement = try db.makeStatement(sql: "UPDATE foo SET rowid = 1") XCTAssertEqual(statement.databaseEventKinds.count, 1) guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else { XCTFail() @@ -621,7 +621,7 @@ class DatabaseRegionTests : GRDBTestCase { XCTAssertEqual(columnNames, ["ROWID"]) } do { - let statement = try db.makeUpdateStatement(sql: "UPDATE foo SET _ROWID_ = 1") + let statement = try db.makeStatement(sql: "UPDATE foo SET _ROWID_ = 1") XCTAssertEqual(statement.databaseEventKinds.count, 1) guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else { XCTFail() @@ -631,7 +631,7 @@ class DatabaseRegionTests : GRDBTestCase { XCTAssertEqual(columnNames, ["ROWID"]) } do { - let statement = try db.makeUpdateStatement(sql: "UPDATE foo SET oID = 1") + let statement = try db.makeStatement(sql: "UPDATE foo SET oID = 1") XCTAssertEqual(statement.databaseEventKinds.count, 1) guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else { XCTFail() @@ -647,7 +647,7 @@ class DatabaseRegionTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)") - let statement = try db.makeUpdateStatement(sql: "INSERT INTO foo (id, bar) VALUES (1, 'bar')") + let statement = try db.makeStatement(sql: "INSERT INTO foo (id, bar) VALUES (1, 'bar')") XCTAssertFalse(statement.invalidatesDatabaseSchemaCache) XCTAssertEqual(statement.databaseEventKinds.count, 1) guard case .insert(let tableName) = statement.databaseEventKinds[0] else { @@ -662,7 +662,7 @@ class DatabaseRegionTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)") - let statement = try db.makeUpdateStatement(sql: "DELETE FROM foo") + let statement = try db.makeStatement(sql: "DELETE FROM foo") XCTAssertFalse(statement.invalidatesDatabaseSchemaCache) XCTAssertEqual(statement.databaseEventKinds.count, 1) guard case .delete(let tableName) = statement.databaseEventKinds[0] else { @@ -677,16 +677,16 @@ class DatabaseRegionTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - let statement = try db.makeUpdateStatement(sql: "CREATE TABLE foo (id INTEGER)") + let statement = try db.makeStatement(sql: "CREATE TABLE foo (id INTEGER)") XCTAssertTrue(statement.invalidatesDatabaseSchemaCache) try statement.execute() } do { - let statement = try db.makeUpdateStatement(sql: "ALTER TABLE foo ADD COLUMN name TEXT") + let statement = try db.makeStatement(sql: "ALTER TABLE foo ADD COLUMN name TEXT") XCTAssertTrue(statement.invalidatesDatabaseSchemaCache) } do { - let statement = try db.makeUpdateStatement(sql: "DROP TABLE foo") + let statement = try db.makeStatement(sql: "DROP TABLE foo") XCTAssertTrue(statement.invalidatesDatabaseSchemaCache) } } @@ -870,34 +870,34 @@ class DatabaseRegionTests : GRDBTestCase { // INTEGER PRIMARY KEY do { // TODO: contact SQLite and ask if this test is expected to fail -// let statement = try db.makeSelectStatement(sql: "SELECT id FROM a") +// let statement = try db.makeStatement(sql: "SELECT id FROM a") // let expectedRegion = DatabaseRegion(table: "a", columns: ["id"]) // XCTAssertEqual(statement.databaseRegion, expectedRegion) } do { - let statement = try db.makeSelectStatement(sql: "SELECT name FROM a") + let statement = try db.makeStatement(sql: "SELECT name FROM a") let expectedRegion = DatabaseRegion(table: "a", columns: ["name"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) } do { - let statement = try db.makeSelectStatement(sql: "SELECT id, name FROM a") + let statement = try db.makeStatement(sql: "SELECT id, name FROM a") let expectedRegion = DatabaseRegion(table: "a", columns: ["id", "name"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) } // TEXT primary key do { - let statement = try db.makeSelectStatement(sql: "SELECT id FROM b") + let statement = try db.makeStatement(sql: "SELECT id FROM b") let expectedRegion = DatabaseRegion(table: "b", columns: ["id"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) } do { - let statement = try db.makeSelectStatement(sql: "SELECT name FROM b") + let statement = try db.makeStatement(sql: "SELECT name FROM b") let expectedRegion = DatabaseRegion(table: "b", columns: ["name"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) } do { - let statement = try db.makeSelectStatement(sql: "SELECT id, name FROM b") + let statement = try db.makeStatement(sql: "SELECT id, name FROM b") let expectedRegion = DatabaseRegion(table: "b", columns: ["id", "name"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) } diff --git a/Tests/GRDBTests/DatabaseTests.swift b/Tests/GRDBTests/DatabaseTests.swift index 9a1d1dadc..4ed00d41e 100644 --- a/Tests/GRDBTests/DatabaseTests.swift +++ b/Tests/GRDBTests/DatabaseTests.swift @@ -51,7 +51,7 @@ class DatabaseTests : GRDBTestCase { try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") // The tested function: - let statement = try db.makeUpdateStatement(sql: "INSERT INTO persons (name, age) VALUES ('Arthur', 41)") + let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES ('Arthur', 41)") try statement.execute() let row = try Row.fetchOne(db, sql: "SELECT * FROM persons")! @@ -65,7 +65,7 @@ class DatabaseTests : GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") - let statement = try db.makeUpdateStatement(sql: "INSERT INTO persons (name, age) VALUES (?, ?)") + let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (?, ?)") try statement.execute(arguments: ["Arthur", 41]) let row = try Row.fetchOne(db, sql: "SELECT * FROM persons")! @@ -79,7 +79,7 @@ class DatabaseTests : GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") - let statement = try db.makeUpdateStatement(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)") + let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)") try statement.execute(arguments: ["name": "Arthur", "age": 41]) let row = try Row.fetchOne(db, sql: "SELECT * FROM persons")! @@ -94,7 +94,7 @@ class DatabaseTests : GRDBTestCase { try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") // The tested function: - let statement = try db.makeUpdateStatement(literal: "INSERT INTO persons (name, age) VALUES ('Arthur', 41)") + let statement = try db.makeStatement(literal: "INSERT INTO persons (name, age) VALUES ('Arthur', 41)") try statement.execute() let row = try Row.fetchOne(db, sql: "SELECT * FROM persons")! @@ -109,7 +109,7 @@ class DatabaseTests : GRDBTestCase { try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") // The tested function: - let statement = try db.makeUpdateStatement(literal: "INSERT INTO persons (name, age) VALUES (\("Arthur"), \(41))") + let statement = try db.makeStatement(literal: "INSERT INTO persons (name, age) VALUES (\("Arthur"), \(41))") try statement.execute() let row = try Row.fetchOne(db, sql: "SELECT * FROM persons")! @@ -123,7 +123,7 @@ class DatabaseTests : GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") - let statement = try db.makeUpdateStatement(literal: "INSERT INTO persons (name, age) VALUES (?, ?)") + let statement = try db.makeStatement(literal: "INSERT INTO persons (name, age) VALUES (?, ?)") try statement.execute(arguments: ["Arthur", 41]) let row = try Row.fetchOne(db, sql: "SELECT * FROM persons")! @@ -137,7 +137,7 @@ class DatabaseTests : GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") - let statement = try db.makeUpdateStatement(literal: "INSERT INTO persons (name, age) VALUES (:name, :age)") + let statement = try db.makeStatement(literal: "INSERT INTO persons (name, age) VALUES (:name, :age)") try statement.execute(arguments: ["name": "Arthur", "age": 41]) let row = try Row.fetchOne(db, sql: "SELECT * FROM persons")! @@ -146,6 +146,64 @@ class DatabaseTests : GRDBTestCase { } } + func testCachedUpdateStatementLiteral() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") + + // The tested function: + let statement = try db.cachedStatement(literal: "INSERT INTO persons (name, age) VALUES ('Arthur', 41)") + try statement.execute() + + let row = try Row.fetchOne(db, sql: "SELECT * FROM persons")! + XCTAssertEqual(row[0] as String, "Arthur") + XCTAssertEqual(row[1] as Int, 41) + } + } + + func testCachedUpdateStatementLiteralWithArguments() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") + + // The tested function: + let statement = try db.cachedStatement(literal: "INSERT INTO persons (name, age) VALUES (\("Arthur"), \(41))") + try statement.execute() + + let row = try Row.fetchOne(db, sql: "SELECT * FROM persons")! + XCTAssertEqual(row[0] as String, "Arthur") + XCTAssertEqual(row[1] as Int, 41) + } + } + + func testCachedUpdateStatementLiteralWithArrayBinding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") + + let statement = try db.cachedStatement(literal: "INSERT INTO persons (name, age) VALUES (?, ?)") + try statement.execute(arguments: ["Arthur", 41]) + + let row = try Row.fetchOne(db, sql: "SELECT * FROM persons")! + XCTAssertEqual(row[0] as String, "Arthur") + XCTAssertEqual(row[1] as Int, 41) + } + } + + func testCachedUpdateStatementLiteralWithDictionaryBinding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") + + let statement = try db.cachedStatement(literal: "INSERT INTO persons (name, age) VALUES (:name, :age)") + try statement.execute(arguments: ["name": "Arthur", "age": 41]) + + let row = try Row.fetchOne(db, sql: "SELECT * FROM persons")! + XCTAssertEqual(row[0] as String, "Arthur") + XCTAssertEqual(row[1] as Int, 41) + } + } + func testDatabaseExecute() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -221,7 +279,7 @@ class DatabaseTests : GRDBTestCase { try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41]) try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil]) - let statement = try db.makeSelectStatement(sql: "SELECT * FROM persons") + let statement = try db.makeStatement(sql: "SELECT * FROM persons") let rows = try Row.fetchAll(statement) XCTAssertEqual(rows.count, 2) } @@ -234,7 +292,7 @@ class DatabaseTests : GRDBTestCase { try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41]) try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil]) - let statement = try db.makeSelectStatement(sql: "SELECT * FROM persons WHERE name = ?") + let statement = try db.makeStatement(sql: "SELECT * FROM persons WHERE name = ?") let rows = try Row.fetchAll(statement, arguments: ["Arthur"]) XCTAssertEqual(rows.count, 1) } @@ -247,7 +305,7 @@ class DatabaseTests : GRDBTestCase { try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41]) try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil]) - let statement = try db.makeSelectStatement(sql: "SELECT * FROM persons WHERE name = :name") + let statement = try db.makeStatement(sql: "SELECT * FROM persons WHERE name = :name") let rows = try Row.fetchAll(statement, arguments: ["name": "Arthur"]) XCTAssertEqual(rows.count, 1) } @@ -260,7 +318,7 @@ class DatabaseTests : GRDBTestCase { try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41]) try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil]) - let statement = try db.makeSelectStatement(literal: "SELECT * FROM persons") + let statement = try db.makeStatement(literal: "SELECT * FROM persons") let rows = try Row.fetchAll(statement) XCTAssertEqual(rows.count, 2) } @@ -273,7 +331,7 @@ class DatabaseTests : GRDBTestCase { try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41]) try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil]) - let statement = try db.makeSelectStatement(literal: "SELECT * FROM persons WHERE name = \("Arthur")") + let statement = try db.makeStatement(literal: "SELECT * FROM persons WHERE name = \("Arthur")") let rows = try Row.fetchAll(statement) XCTAssertEqual(rows.count, 1) } @@ -286,7 +344,7 @@ class DatabaseTests : GRDBTestCase { try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41]) try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil]) - let statement = try db.makeSelectStatement(literal: "SELECT * FROM persons WHERE name = ?") + let statement = try db.makeStatement(literal: "SELECT * FROM persons WHERE name = ?") let rows = try Row.fetchAll(statement, arguments: ["Arthur"]) XCTAssertEqual(rows.count, 1) } @@ -299,12 +357,64 @@ class DatabaseTests : GRDBTestCase { try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41]) try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil]) - let statement = try db.makeSelectStatement(literal: "SELECT * FROM persons WHERE name = :name") + let statement = try db.makeStatement(literal: "SELECT * FROM persons WHERE name = :name") let rows = try Row.fetchAll(statement, arguments: ["name": "Arthur"]) XCTAssertEqual(rows.count, 1) } } + func testCachedSelectStatementLiteral() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") + try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41]) + try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil]) + + let statement = try db.cachedStatement(literal: "SELECT * FROM persons") + let rows = try Row.fetchAll(statement) + XCTAssertEqual(rows.count, 2) + } + } + + func testCachedSelectStatementLiteralWithArguments() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") + try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41]) + try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil]) + + let statement = try db.cachedStatement(literal: "SELECT * FROM persons WHERE name = \("Arthur")") + let rows = try Row.fetchAll(statement) + XCTAssertEqual(rows.count, 1) + } + } + + func testCachedSelectStatementLiteralWithArrayBinding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") + try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41]) + try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil]) + + let statement = try db.cachedStatement(literal: "SELECT * FROM persons WHERE name = ?") + let rows = try Row.fetchAll(statement, arguments: ["Arthur"]) + XCTAssertEqual(rows.count, 1) + } + } + + func testCachedSelectStatementLiteralWithDictionaryBinding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)") + try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41]) + try db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil]) + + let statement = try db.cachedStatement(literal: "SELECT * FROM persons WHERE name = :name") + let rows = try Row.fetchAll(statement, arguments: ["name": "Arthur"]) + XCTAssertEqual(rows.count, 1) + } + } + func testRowValueAtIndex() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift b/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift index aede3116f..34cb521f5 100644 --- a/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift +++ b/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift @@ -15,7 +15,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { // conversion error try dbQueue.read { db in - let statement = try db.makeSelectStatement(sql: "SELECT ? AS name") + let statement = try db.makeStatement(sql: "SELECT ? AS name") statement.arguments = [nil] do { @@ -69,7 +69,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { // missing column try dbQueue.read { db in - let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused") + let statement = try db.makeStatement(sql: "SELECT ? AS unused") statement.arguments = ["ignored"] do { @@ -137,7 +137,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { // conversion error try dbQueue.read { db in - let statement = try db.makeSelectStatement(sql: "SELECT 1, ? AS value") + let statement = try db.makeStatement(sql: "SELECT 1, ? AS value") statement.arguments = ["invalid"] do { @@ -191,7 +191,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { // missing column try dbQueue.read { db in - let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused") + let statement = try db.makeStatement(sql: "SELECT ? AS unused") statement.arguments = ["ignored"] do { @@ -252,7 +252,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { // conversion error try dbQueue.read { db in - let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS team") + let statement = try db.makeStatement(sql: "SELECT NULL AS name, ? AS team") statement.arguments = ["invalid"] do { @@ -308,7 +308,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { // missing column try dbQueue.read { db in - let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused") + let statement = try db.makeStatement(sql: "SELECT ? AS unused") statement.arguments = ["ignored"] do { @@ -374,7 +374,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { // conversion error try dbQueue.read { db in - let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS value") + let statement = try db.makeStatement(sql: "SELECT NULL AS name, ? AS value") statement.arguments = ["invalid"] do { @@ -430,7 +430,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { // missing column try dbQueue.read { db in - let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused") + let statement = try db.makeStatement(sql: "SELECT ? AS unused") statement.arguments = ["ignored"] do { @@ -496,7 +496,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { // conversion error try dbQueue.read { db in - let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS value") + let statement = try db.makeStatement(sql: "SELECT NULL AS name, ? AS value") statement.arguments = ["invalid"] do { @@ -550,7 +550,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { // missing column try dbQueue.read { db in - let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused") + let statement = try db.makeStatement(sql: "SELECT ? AS unused") statement.arguments = ["ignored"] do { @@ -606,7 +606,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { func testStatementColumnConvertible1() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in - let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS team") + let statement = try db.makeStatement(sql: "SELECT NULL AS name, ? AS team") statement.arguments = ["invalid"] do { @@ -684,7 +684,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { func testStatementColumnConvertible2() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in - let statement = try db.makeSelectStatement(sql: "SELECT ? AS foo") + let statement = try db.makeStatement(sql: "SELECT ? AS foo") statement.arguments = [1000] do { @@ -790,7 +790,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in - let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS team") + let statement = try db.makeStatement(sql: "SELECT NULL AS name, ? AS team") statement.arguments = ["invalid"] do { diff --git a/Tests/GRDBTests/DatabaseValueConvertibleDecodableTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleDecodableTests.swift index 3d9e19470..4b75c9e9f 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleDecodableTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleDecodableTests.swift @@ -129,6 +129,169 @@ class DatabaseValueConvertibleDecodableTests: GRDBTestCase { } } + func testDatabaseValueConvertibleImplementationDerivedFromDecodable4() throws { + struct Value: Decodable, DatabaseValueConvertible { + let strings: [String] + + var databaseValue: DatabaseValue { + preconditionFailure("not tested") + } + } + + do { + // Success from DatabaseValue + let value = Value.fromDatabaseValue(#"{ "strings": ["foo", "bar"] }"#.databaseValue)! + XCTAssertEqual(value.strings, ["foo", "bar"]) + } + do { + // Success from database + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let value = try Value.fetchOne(db, sql: #"SELECT '{ "strings": ["foo", "bar"] }'"#)! + XCTAssertEqual(value.strings, ["foo", "bar"]) + } + } + do { + // Failure from DatabaseValue + let value = Value.fromDatabaseValue(1.databaseValue) + XCTAssertNil(value) + } + } + + func testDatabaseValueConvertibleImplementationDerivedFromDecodable5() throws { + struct Value: Decodable, DatabaseValueConvertible { + let dictionary: [String: Int] + + init(from decoder: Decoder) throws { + dictionary = try .init(from: decoder) + } + + var databaseValue: DatabaseValue { + preconditionFailure("not tested") + } + } + + do { + // Success from DatabaseValue + let value = Value.fromDatabaseValue(#"{"foo": 1}"#.databaseValue)! + XCTAssertEqual(value.dictionary, ["foo": 1]) + } + do { + // Success from database + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let value = try Value.fetchOne(db, sql: #"SELECT '{"foo": 1}'"#)! + XCTAssertEqual(value.dictionary, ["foo": 1]) + } + } + do { + // Failure from DatabaseValue + let value = Value.fromDatabaseValue(1.databaseValue) + XCTAssertNil(value) + } + } + + func testDatabaseValueConvertibleImplementationDerivedFromDecodable6() throws { + struct Value: Decodable, DatabaseValueConvertible { + let strings: [String] + + init(from decoder: Decoder) throws { + strings = try .init(from: decoder) + } + + var databaseValue: DatabaseValue { + preconditionFailure("not tested") + } + } + + do { + // Success from DatabaseValue + let value = Value.fromDatabaseValue(#"["foo", "bar"]"#.databaseValue)! + XCTAssertEqual(value.strings, ["foo", "bar"]) + } + do { + // Success from database + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let value = try Value.fetchOne(db, sql: #"SELECT '["foo", "bar"]'"#)! + XCTAssertEqual(value.strings, ["foo", "bar"]) + } + } + do { + // Failure from DatabaseValue + let value = Value.fromDatabaseValue(1.databaseValue) + XCTAssertNil(value) + } + } + + func testDatabaseValueConvertibleImplementationDerivedFromDecodable7() throws { + struct Value: Decodable, DatabaseValueConvertible { + let dictionary: [String: Int] + + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + dictionary = try container.decode([String: Int].self) + } + + var databaseValue: DatabaseValue { + preconditionFailure("not tested") + } + } + + do { + // Success from DatabaseValue + let value = Value.fromDatabaseValue(#"{"foo": 1}"#.databaseValue)! + XCTAssertEqual(value.dictionary, ["foo": 1]) + } + do { + // Success from database + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let value = try Value.fetchOne(db, sql: #"SELECT '{"foo": 1}'"#)! + XCTAssertEqual(value.dictionary, ["foo": 1]) + } + } + do { + // Failure from DatabaseValue + let value = Value.fromDatabaseValue(1.databaseValue) + XCTAssertNil(value) + } + } + + func testDatabaseValueConvertibleImplementationDerivedFromDecodable8() throws { + struct Value: Decodable, DatabaseValueConvertible { + let strings: [String] + + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + strings = try container.decode([String].self) + } + + var databaseValue: DatabaseValue { + preconditionFailure("not tested") + } + } + + do { + // Success from DatabaseValue + let value = Value.fromDatabaseValue(#"["foo", "bar"]"#.databaseValue)! + XCTAssertEqual(value.strings, ["foo", "bar"]) + } + do { + // Success from database + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let value = try Value.fetchOne(db, sql: #"SELECT '["foo", "bar"]'"#)! + XCTAssertEqual(value.strings, ["foo", "bar"]) + } + } + do { + // Failure from DatabaseValue + let value = Value.fromDatabaseValue(1.databaseValue) + XCTAssertNil(value) + } + } + func testCustomDatabaseValueConvertible() throws { struct Value : Decodable, DatabaseValueConvertible { let string: String diff --git a/Tests/GRDBTests/DatabaseValueConvertibleEncodableTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleEncodableTests.swift index 81efa85be..c155d344c 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleEncodableTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleEncodableTests.swift @@ -87,6 +87,124 @@ class DatabaseValueConvertibleEncodableTests: GRDBTestCase { XCTAssertEqual(dbValue.storage.value as! String, "foo") } + func testDatabaseValueConvertibleImplementationDerivedFromEncodable4() throws { + struct Value: Encodable, DatabaseValueConvertible { + let strings: [String] + + static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? { + preconditionFailure("not tested") + } + } + + do { + let dbValue = Value(strings: ["foo", "bar"]).databaseValue + XCTAssertEqual(dbValue.storage.value as! String, #"{"strings":["foo","bar"]}"#) + } + + do { + let dbValue = Value(strings: []).databaseValue + XCTAssertEqual(dbValue.storage.value as! String, #"{"strings":[]}"#) + } + } + + func testDatabaseValueConvertibleImplementationDerivedFromEncodable5() throws { + struct Value: Encodable, DatabaseValueConvertible { + let dictionary: [String: Int] + + func encode(to encoder: Encoder) throws { + try dictionary.encode(to: encoder) + } + + static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? { + preconditionFailure("not tested") + } + } + + do { + let dbValue = Value(dictionary: ["foo": 1]).databaseValue + XCTAssertEqual(dbValue.storage.value as! String, #"{"foo":1}"#) + } + + do { + let dbValue = Value(dictionary: [:]).databaseValue + XCTAssertEqual(dbValue.storage.value as! String, #"{}"#) + } + } + + func testDatabaseValueConvertibleImplementationDerivedFromEncodable6() throws { + struct Value: Encodable, DatabaseValueConvertible { + let strings: [String] + + func encode(to encoder: Encoder) throws { + try strings.encode(to: encoder) + } + + static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? { + preconditionFailure("not tested") + } + } + + do { + let dbValue = Value(strings: ["foo", "bar"]).databaseValue + XCTAssertEqual(dbValue.storage.value as! String, #"["foo","bar"]"#) + } + + do { + let dbValue = Value(strings: []).databaseValue + XCTAssertEqual(dbValue.storage.value as! String, #"[]"#) + } + } + + func testDatabaseValueConvertibleImplementationDerivedFromEncodable7() throws { + struct Value: Encodable, DatabaseValueConvertible { + let dictionary: [String: Int] + + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(dictionary) + } + + static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? { + preconditionFailure("not tested") + } + } + + do { + let dbValue = Value(dictionary: ["foo": 1]).databaseValue + XCTAssertEqual(dbValue.storage.value as! String, #"{"foo":1}"#) + } + + do { + let dbValue = Value(dictionary: [:]).databaseValue + XCTAssertEqual(dbValue.storage.value as! String, #"{}"#) + } + } + + func testDatabaseValueConvertibleImplementationDerivedFromEncodable8() throws { + struct Value: Encodable, DatabaseValueConvertible { + let strings: [String] + + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(strings) + } + + static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? { + preconditionFailure("not tested") + } + } + + do { + let dbValue = Value(strings: ["foo", "bar"]).databaseValue + XCTAssertEqual(dbValue.storage.value as! String, #"["foo","bar"]"#) + } + + do { + let dbValue = Value(strings: []).databaseValue + XCTAssertEqual(dbValue.storage.value as! String, #"[]"#) + } + } + func testEncodableRawRepresentable() { // Test that the rawValue is encoded with DatabaseValueConvertible, not with Encodable struct Value : RawRepresentable, Encodable, DatabaseValueConvertible { diff --git a/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift index 5c7341aea..8c1765873 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift @@ -31,7 +31,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 UNION ALL SELECT 2" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchCursor(db, sql: sql)) try test(Fetched.fetchCursor(statement)) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql))) @@ -39,7 +39,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql: sql, adapter: adapter)) try test(Fetched.fetchCursor(statement, adapter: adapter)) @@ -85,7 +85,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Fetched.fetchCursor(db, sql: sql), sql: sql) - try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchCursor(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchCursor(db), sql: sql) } @@ -93,7 +93,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchCursor(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchCursor(db), sql: sql) } @@ -117,7 +117,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchCursor(db, sql: sql), sql: sql) - try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchCursor(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchCursor(db), sql: sql) } @@ -125,7 +125,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchCursor(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchCursor(db), sql: sql) } @@ -140,7 +140,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 UNION ALL SELECT 2" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchAll(db, sql: sql)) try test(Fetched.fetchAll(statement)) try test(Fetched.fetchAll(db, SQLRequest(sql: sql))) @@ -148,7 +148,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql: sql, adapter: adapter)) try test(Fetched.fetchAll(statement, adapter: adapter)) @@ -186,7 +186,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Fetched.fetchAll(db, sql: sql), sql: sql) - try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchAll(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchAll(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchAll(db), sql: sql) } @@ -194,7 +194,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchAll(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchAll(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchAll(db), sql: sql) } @@ -218,7 +218,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchAll(db, sql: sql), sql: sql) - try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchAll(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchAll(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchAll(db), sql: sql) } @@ -226,7 +226,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchAll(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchAll(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchAll(db), sql: sql) } @@ -241,7 +241,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 UNION ALL SELECT 2" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchSet(db, sql: sql)) try test(Fetched.fetchSet(statement)) try test(Fetched.fetchSet(db, SQLRequest(sql: sql))) @@ -249,7 +249,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchSet(db, sql: sql, adapter: adapter)) try test(Fetched.fetchSet(statement, adapter: adapter)) @@ -287,7 +287,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Fetched.fetchSet(db, sql: sql), sql: sql) - try test(Fetched.fetchSet(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchSet(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchSet(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchSet(db), sql: sql) } @@ -295,7 +295,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchSet(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchSet(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchSet(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchSet(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchSet(db), sql: sql) } @@ -319,7 +319,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchSet(db, sql: sql), sql: sql) - try test(Fetched.fetchSet(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchSet(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchSet(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchSet(db), sql: sql) } @@ -327,7 +327,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchSet(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchSet(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchSet(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchSet(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchSet(db), sql: sql) } @@ -343,7 +343,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 WHERE 0" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchOne(db, sql: sql)) try test(Fetched.fetchOne(statement)) try test(Fetched.fetchOne(db, SQLRequest(sql: sql))) @@ -351,7 +351,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 WHERE 0" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) @@ -365,7 +365,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchOne(db, sql: sql)) try test(Fetched.fetchOne(statement)) try test(Fetched.fetchOne(db, SQLRequest(sql: sql))) @@ -373,7 +373,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) @@ -387,7 +387,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchOne(db, sql: sql)) try test(Fetched.fetchOne(statement)) try test(Fetched.fetchOne(db, SQLRequest(sql: sql))) @@ -395,7 +395,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) @@ -434,7 +434,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Fetched.fetchOne(db, sql: sql), sql: sql) - try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchOne(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchOne(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchOne(db), sql: sql) } @@ -442,7 +442,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchOne(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchOne(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db), sql: sql) } @@ -466,7 +466,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchOne(db, sql: sql), sql: sql) - try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchOne(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchOne(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchOne(db), sql: sql) } @@ -474,7 +474,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchOne(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchOne(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db), sql: sql) } @@ -494,7 +494,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 UNION ALL SELECT NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Optional.fetchCursor(db, sql: sql)) try test(Optional.fetchCursor(statement)) try test(Optional.fetchCursor(db, SQLRequest(sql: sql))) @@ -502,7 +502,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql: sql, adapter: adapter)) try test(Optional.fetchCursor(statement, adapter: adapter)) @@ -548,7 +548,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Optional.fetchCursor(db, sql: sql), sql: sql) - try test(Optional.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Optional.fetchCursor(db.makeStatement(sql: sql)), sql: sql) try test(Optional.fetchCursor(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchCursor(db), sql: sql) } @@ -556,7 +556,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql: sql, adapter: adapter), sql: sql) - try test(Optional.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.fetchCursor(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Optional.fetchCursor(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchCursor(db), sql: sql) } @@ -580,7 +580,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchCursor(db, sql: sql), sql: sql) - try test(Optional.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Optional.fetchCursor(db.makeStatement(sql: sql)), sql: sql) try test(Optional.fetchCursor(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchCursor(db), sql: sql) } @@ -588,7 +588,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql: sql, adapter: adapter), sql: sql) - try test(Optional.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.fetchCursor(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Optional.fetchCursor(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchCursor(db), sql: sql) } @@ -605,7 +605,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 UNION ALL SELECT NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Optional.fetchAll(db, sql: sql)) try test(Optional.fetchAll(statement)) try test(Optional.fetchAll(db, SQLRequest(sql: sql))) @@ -613,7 +613,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql: sql, adapter: adapter)) try test(Optional.fetchAll(statement, adapter: adapter)) @@ -651,7 +651,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Optional.fetchAll(db, sql: sql), sql: sql) - try test(Optional.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Optional.fetchAll(db.makeStatement(sql: sql)), sql: sql) try test(Optional.fetchAll(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchAll(db), sql: sql) } @@ -659,7 +659,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql: sql, adapter: adapter), sql: sql) - try test(Optional.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.fetchAll(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Optional.fetchAll(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchAll(db), sql: sql) } @@ -683,7 +683,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchAll(db, sql: sql), sql: sql) - try test(Optional.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Optional.fetchAll(db.makeStatement(sql: sql)), sql: sql) try test(Optional.fetchAll(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchAll(db), sql: sql) } @@ -691,7 +691,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql: sql, adapter: adapter), sql: sql) - try test(Optional.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.fetchAll(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Optional.fetchAll(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchAll(db), sql: sql) } @@ -706,7 +706,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 UNION ALL SELECT NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Optional.fetchSet(db, sql: sql)) try test(Optional.fetchSet(statement)) try test(Optional.fetchSet(db, SQLRequest(sql: sql))) @@ -714,7 +714,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchSet(db, sql: sql, adapter: adapter)) try test(Optional.fetchSet(statement, adapter: adapter)) @@ -752,7 +752,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Optional.fetchSet(db, sql: sql), sql: sql) - try test(Optional.fetchSet(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Optional.fetchSet(db.makeStatement(sql: sql)), sql: sql) try test(Optional.fetchSet(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchSet(db), sql: sql) } @@ -760,7 +760,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchSet(db, sql: sql, adapter: adapter), sql: sql) - try test(Optional.fetchSet(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.fetchSet(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Optional.fetchSet(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchSet(db), sql: sql) } @@ -784,7 +784,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchSet(db, sql: sql), sql: sql) - try test(Optional.fetchSet(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Optional.fetchSet(db.makeStatement(sql: sql)), sql: sql) try test(Optional.fetchSet(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchSet(db), sql: sql) } @@ -792,7 +792,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchSet(db, sql: sql, adapter: adapter), sql: sql) - try test(Optional.fetchSet(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.fetchSet(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Optional.fetchSet(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchSet(db), sql: sql) } diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 117b965a6..54b77c3d4 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -193,6 +193,48 @@ class DatabaseWriterTests : GRDBTestCase { try XCTAssertNil(Row.fetchOne(db, sql: "SELECT * FROM sqlite_master")) } } + + func testVacuumInto() throws { + guard #available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) else { + throw XCTSkip("VACUUM INTO is not available") + } + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3027000 else { + throw XCTSkip("VACUUM INTO is not available") + } + + func testVacuumInto(writer: DatabaseWriter) throws { + var migrator = DatabaseMigrator() + migrator.registerMigration("init") { db in + try db.execute(sql: """ + CREATE TABLE t1 (id INTEGER PRIMARY KEY AUTOINCREMENT, b, c); + INSERT INTO t1 (b, c) VALUES (1, 1); + INSERT INTO t1 (b, c) VALUES (2, 2); + """) + } + + try migrator.migrate(writer) + + try writer.read { db in + try XCTAssertTrue(db.tableExists("t1")) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT count(*) from t1"), 2) + } + + let intoPath = NSTemporaryDirectory().appending(ProcessInfo.processInfo.globallyUniqueString).appending("-vacuum-into-db.sqlite") + try writer.vacuum(into: intoPath) + + // open newly created file and ensure table was copied, and + // encrypted like the original. + let newWriter = try DatabaseQueue(path: intoPath, configuration: writer.configuration) + try newWriter.read { db in + try XCTAssertTrue(db.tableExists("t1")) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT count(*) from t1"), 2) + } + } + + try testVacuumInto(writer: makeDatabaseQueue()) + try testVacuumInto(writer: makeDatabasePool()) + } // See https://github.com/groue/GRDB.swift/issues/424 func testIssue424() throws { @@ -204,7 +246,7 @@ class DatabaseWriterTests : GRDBTestCase { """) } try dbQueue.read { db in - _ = try Row.fetchCursor(db.cachedSelectStatement(sql: "SELECT * FROM t")).next() + _ = try Row.fetchCursor(db.cachedStatement(sql: "SELECT * FROM t")).next() } try dbQueue.erase() } @@ -219,7 +261,7 @@ class DatabaseWriterTests : GRDBTestCase { INSERT INTO t VALUES (1); PRAGMA query_only = 1; """) - _ = try Row.fetchCursor(db.cachedSelectStatement(sql: "SELECT * FROM t")).next() + _ = try Row.fetchCursor(db.cachedStatement(sql: "SELECT * FROM t")).next() } try DatabaseQueue().backup(to: dbQueue) } diff --git a/Tests/GRDBTests/FTS4TableBuilderTests.swift b/Tests/GRDBTests/FTS4TableBuilderTests.swift index 4379e8d71..2717dbc12 100644 --- a/Tests/GRDBTests/FTS4TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS4TableBuilderTests.swift @@ -194,6 +194,23 @@ class FTS4TableBuilderTests: GRDBTestCase { } } + func testFTS4SynchronizationIfNotExists() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.writeWithoutTransaction { db in + try db.create(table: "documents") { t in + t.column("id", .integer).primaryKey() + t.column("content", .text) + } + assertDidExecute(sql: "CREATE TABLE \"documents\" (\"id\" INTEGER PRIMARY KEY, \"content\" TEXT)") + try db.create(virtualTable: "ft_documents", ifNotExists: true, using: FTS4()) { t in + t.synchronize(withTable: "documents") + t.column("content") + } + assertDidExecute(sql: "CREATE VIRTUAL TABLE IF NOT EXISTS \"ft_documents\" USING fts4(content, content=\"documents\")") + assertDidExecute(sql: "CREATE TRIGGER IF NOT EXISTS \"__ft_documents_bu\" BEFORE UPDATE ON \"documents\" BEGIN\n DELETE FROM \"ft_documents\" WHERE docid=old.\"id\";\nEND") + } + } + func testFTS4SynchronizationCleanup() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/FTS5TableBuilderTests.swift b/Tests/GRDBTests/FTS5TableBuilderTests.swift index e03c0cf8d..457dddb0b 100644 --- a/Tests/GRDBTests/FTS5TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS5TableBuilderTests.swift @@ -252,6 +252,30 @@ class FTS5TableBuilderTests: GRDBTestCase { } } + func testFTS5SynchronizationIfNotExists() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.writeWithoutTransaction { db in + try db.create(table: "documents") { t in + t.column("id", .integer).primaryKey() + t.column("content", .text) + } + assertDidExecute(sql: "CREATE TABLE \"documents\" (\"id\" INTEGER PRIMARY KEY, \"content\" TEXT)") + try db.create(virtualTable: "ft_documents", ifNotExists: true, using: FTS5()) { t in + t.synchronize(withTable: "documents") + t.column("content") + } + + assertDidExecute(sql: """ + CREATE VIRTUAL TABLE IF NOT EXISTS "ft_documents" USING fts5(content, content='documents', content_rowid='id') + """) + assertDidExecute(sql: """ + CREATE TRIGGER IF NOT EXISTS "__ft_documents_ai" AFTER INSERT ON "documents" BEGIN + INSERT INTO "ft_documents"("rowid", "content") VALUES (new."id", new."content"); + END + """) + } + } + func testFTS5SynchronizationCleanup() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/FetchableRecordTests.swift b/Tests/GRDBTests/FetchableRecordTests.swift index 3d665585b..7397e7b8b 100644 --- a/Tests/GRDBTests/FetchableRecordTests.swift +++ b/Tests/GRDBTests/FetchableRecordTests.swift @@ -36,7 +36,7 @@ class FetchableRecordTests: GRDBTestCase { } do { let sql = "SELECT 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 'Barbara', 'Gourde'" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchCursor(db, sql: sql)) try test(Fetched.fetchCursor(statement)) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql))) @@ -44,7 +44,7 @@ class FetchableRecordTests: GRDBTestCase { } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql: sql, adapter: adapter)) try test(Fetched.fetchCursor(statement, adapter: adapter)) @@ -94,7 +94,7 @@ class FetchableRecordTests: GRDBTestCase { do { let sql = "SELECT throw(), NULL" try test(Fetched.fetchCursor(db, sql: sql), sql: sql) - try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchCursor(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchCursor(db), sql: sql) } @@ -102,7 +102,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT 0, throw(), NULL" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchCursor(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchCursor(db), sql: sql) } @@ -126,7 +126,7 @@ class FetchableRecordTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchCursor(db, sql: sql), sql: sql) - try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchCursor(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchCursor(db), sql: sql) } @@ -134,7 +134,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchCursor(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchCursor(db), sql: sql) } @@ -150,7 +150,7 @@ class FetchableRecordTests: GRDBTestCase { } do { let sql = "SELECT 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 'Barbara', 'Gourde'" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchAll(db, sql: sql)) try test(Fetched.fetchAll(statement)) try test(Fetched.fetchAll(db, SQLRequest(sql: sql))) @@ -158,7 +158,7 @@ class FetchableRecordTests: GRDBTestCase { } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql: sql, adapter: adapter)) try test(Fetched.fetchAll(statement, adapter: adapter)) @@ -199,7 +199,7 @@ class FetchableRecordTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Fetched.fetchAll(db, sql: sql), sql: sql) - try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchAll(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchAll(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchAll(db), sql: sql) } @@ -207,7 +207,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchAll(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchAll(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchAll(db), sql: sql) } @@ -231,7 +231,7 @@ class FetchableRecordTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchAll(db, sql: sql), sql: sql) - try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchAll(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchAll(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchAll(db), sql: sql) } @@ -239,7 +239,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchAll(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchAll(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchAll(db), sql: sql) } @@ -255,7 +255,7 @@ class FetchableRecordTests: GRDBTestCase { } do { let sql = "SELECT 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 'Barbara', 'Gourde'" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchSet(db, sql: sql)) try test(Fetched.fetchSet(statement)) try test(Fetched.fetchSet(db, SQLRequest(sql: sql))) @@ -263,7 +263,7 @@ class FetchableRecordTests: GRDBTestCase { } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchSet(db, sql: sql, adapter: adapter)) try test(Fetched.fetchSet(statement, adapter: adapter)) @@ -304,7 +304,7 @@ class FetchableRecordTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Fetched.fetchSet(db, sql: sql), sql: sql) - try test(Fetched.fetchSet(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchSet(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchSet(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchSet(db), sql: sql) } @@ -312,7 +312,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchSet(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchSet(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchSet(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchSet(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchSet(db), sql: sql) } @@ -336,7 +336,7 @@ class FetchableRecordTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchSet(db, sql: sql), sql: sql) - try test(Fetched.fetchSet(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchSet(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchSet(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchSet(db), sql: sql) } @@ -344,7 +344,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchSet(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchSet(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchSet(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchSet(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchSet(db), sql: sql) } @@ -360,7 +360,7 @@ class FetchableRecordTests: GRDBTestCase { } do { let sql = "SELECT 1 WHERE 0" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchOne(db, sql: sql)) try test(Fetched.fetchOne(statement)) try test(Fetched.fetchOne(db, SQLRequest(sql: sql))) @@ -368,7 +368,7 @@ class FetchableRecordTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 WHERE 0" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) @@ -383,7 +383,7 @@ class FetchableRecordTests: GRDBTestCase { } do { let sql = "SELECT 'Arthur' AS firstName, 'Martin' AS lastName" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchOne(db, sql: sql)) try test(Fetched.fetchOne(statement)) try test(Fetched.fetchOne(db, SQLRequest(sql: sql))) @@ -391,7 +391,7 @@ class FetchableRecordTests: GRDBTestCase { } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) @@ -433,7 +433,7 @@ class FetchableRecordTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Fetched.fetchOne(db, sql: sql), sql: sql) - try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchOne(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchOne(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchOne(db), sql: sql) } @@ -441,7 +441,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchOne(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchOne(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db), sql: sql) } @@ -465,7 +465,7 @@ class FetchableRecordTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchOne(db, sql: sql), sql: sql) - try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchOne(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchOne(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchOne(db), sql: sql) } @@ -473,7 +473,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchOne(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchOne(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db), sql: sql) } diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 891646075..56dcebe8a 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -226,7 +226,7 @@ class GRDBTestCase: XCTestCase { extension FetchRequest { /// Turn request into a statement - func makeStatement(_ db: Database) throws -> SelectStatement { + func makeStatement(_ db: Database) throws -> Statement { try makePreparedRequest(db, forSingleResult: false).statement } diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 76ce64b46..51df91e5d 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -746,4 +746,34 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } + + // MARK: Select ID + + func test_static_selectID() throws { + guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + throw XCTSkip("Identifiable not available") + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalNonOptionalPrimaryKeySingle(id: "theUUID") + try record.insert(db) + let ids = try MinimalSingle.selectID().fetchAll(db) + XCTAssertEqual(ids, ["theUUID"]) + } + } + + func test_request_selectID() throws { + guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + throw XCTSkip("Identifiable not available") + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalNonOptionalPrimaryKeySingle(id: "theUUID") + try record.insert(db) + let ids = try MinimalSingle.all().selectID().fetchAll(db) + XCTAssertEqual(ids, ["theUUID"]) + } + } } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 1b620050e..270c71ca3 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -780,4 +780,34 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } + + // MARK: Select ID + + func test_static_selectID() throws { + guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + throw XCTSkip("Identifiable not available") + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalRowID() + try record.insert(db) + let ids = try MinimalRowID.selectID().fetchAll(db) + XCTAssertEqual(ids, [1]) + } + } + + func test_request_selectID() throws { + guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + throw XCTSkip("Identifiable not available") + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalRowID() + try record.insert(db) + let ids = try MinimalRowID.all().selectID().fetchAll(db) + XCTAssertEqual(ids, [1]) + } + } } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 47b3645d1..cae1f356c 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -818,4 +818,36 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } + + // MARK: Select ID + + func test_static_selectID() throws { + guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + throw XCTSkip("Identifiable not available") + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalSingle() + record.UUID = "theUUID" + try record.insert(db) + let ids = try MinimalSingle.selectID().fetchAll(db) + XCTAssertEqual(ids, ["theUUID"]) + } + } + + func test_request_selectID() throws { + guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + throw XCTSkip("Identifiable not available") + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalSingle() + record.UUID = "theUUID" + try record.insert(db) + let ids = try MinimalSingle.all().selectID().fetchAll(db) + XCTAssertEqual(ids, ["theUUID"]) + } + } } diff --git a/Tests/GRDBTests/RowFetchTests.swift b/Tests/GRDBTests/RowFetchTests.swift index 6cb9017bc..c419f5f3a 100644 --- a/Tests/GRDBTests/RowFetchTests.swift +++ b/Tests/GRDBTests/RowFetchTests.swift @@ -21,7 +21,7 @@ class RowFetchTests: GRDBTestCase { } do { let sql = "SELECT 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 'Barbara', 'Gourde'" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Row.fetchCursor(db, sql: sql)) try test(Row.fetchCursor(statement)) try test(Row.fetchCursor(db, SQLRequest(sql: sql))) @@ -29,7 +29,7 @@ class RowFetchTests: GRDBTestCase { } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchCursor(db, sql: sql, adapter: adapter)) try test(Row.fetchCursor(statement, adapter: adapter)) @@ -75,7 +75,7 @@ class RowFetchTests: GRDBTestCase { do { let sql = "SELECT throw(), NULL" try test(Row.fetchCursor(db, sql: sql), sql: sql) - try test(Row.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Row.fetchCursor(db.makeStatement(sql: sql)), sql: sql) try test(Row.fetchCursor(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchCursor(db), sql: sql) } @@ -83,7 +83,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT 0, throw(), NULL" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchCursor(db, sql: sql, adapter: adapter), sql: sql) - try test(Row.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Row.fetchCursor(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Row.fetchCursor(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchCursor(db), sql: sql) } @@ -107,7 +107,7 @@ class RowFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Row.fetchCursor(db, sql: sql), sql: sql) - try test(Row.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Row.fetchCursor(db.makeStatement(sql: sql)), sql: sql) try test(Row.fetchCursor(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchCursor(db), sql: sql) } @@ -115,7 +115,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchCursor(db, sql: sql, adapter: adapter), sql: sql) - try test(Row.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Row.fetchCursor(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Row.fetchCursor(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchCursor(db), sql: sql) } @@ -131,7 +131,7 @@ class RowFetchTests: GRDBTestCase { } do { let sql = "SELECT 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 'Barbara', 'Gourde'" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Row.fetchAll(db, sql: sql)) try test(Row.fetchAll(statement)) try test(Row.fetchAll(db, SQLRequest(sql: sql))) @@ -139,7 +139,7 @@ class RowFetchTests: GRDBTestCase { } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchAll(db, sql: sql, adapter: adapter)) try test(Row.fetchAll(statement, adapter: adapter)) @@ -177,7 +177,7 @@ class RowFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Row.fetchAll(db, sql: sql), sql: sql) - try test(Row.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Row.fetchAll(db.makeStatement(sql: sql)), sql: sql) try test(Row.fetchAll(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchAll(db), sql: sql) } @@ -185,7 +185,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchAll(db, sql: sql, adapter: adapter), sql: sql) - try test(Row.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Row.fetchAll(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Row.fetchAll(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchAll(db), sql: sql) } @@ -209,7 +209,7 @@ class RowFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Row.fetchAll(db, sql: sql), sql: sql) - try test(Row.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Row.fetchAll(db.makeStatement(sql: sql)), sql: sql) try test(Row.fetchAll(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchAll(db), sql: sql) } @@ -217,7 +217,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchAll(db, sql: sql, adapter: adapter), sql: sql) - try test(Row.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Row.fetchAll(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Row.fetchAll(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchAll(db), sql: sql) } @@ -233,7 +233,7 @@ class RowFetchTests: GRDBTestCase { } do { let sql = "SELECT 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 'Barbara', 'Gourde'" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Row.fetchSet(db, sql: sql)) try test(Row.fetchSet(statement)) try test(Row.fetchSet(db, SQLRequest(sql: sql))) @@ -241,7 +241,7 @@ class RowFetchTests: GRDBTestCase { } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchSet(db, sql: sql, adapter: adapter)) try test(Row.fetchSet(statement, adapter: adapter)) @@ -279,7 +279,7 @@ class RowFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Row.fetchSet(db, sql: sql), sql: sql) - try test(Row.fetchSet(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Row.fetchSet(db.makeStatement(sql: sql)), sql: sql) try test(Row.fetchSet(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchSet(db), sql: sql) } @@ -287,7 +287,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchSet(db, sql: sql, adapter: adapter), sql: sql) - try test(Row.fetchSet(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Row.fetchSet(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Row.fetchSet(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchSet(db), sql: sql) } @@ -311,7 +311,7 @@ class RowFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Row.fetchSet(db, sql: sql), sql: sql) - try test(Row.fetchSet(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Row.fetchSet(db.makeStatement(sql: sql)), sql: sql) try test(Row.fetchSet(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchSet(db), sql: sql) } @@ -319,7 +319,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchSet(db, sql: sql, adapter: adapter), sql: sql) - try test(Row.fetchSet(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Row.fetchSet(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Row.fetchSet(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchSet(db), sql: sql) } @@ -335,7 +335,7 @@ class RowFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 WHERE 0" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Row.fetchOne(db, sql: sql)) try test(Row.fetchOne(statement)) try test(Row.fetchOne(db, SQLRequest(sql: sql))) @@ -343,7 +343,7 @@ class RowFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 WHERE 0" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql: sql, adapter: adapter)) try test(Row.fetchOne(statement, adapter: adapter)) @@ -358,7 +358,7 @@ class RowFetchTests: GRDBTestCase { } do { let sql = "SELECT 'Arthur' AS firstName, 'Martin' AS lastName" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Row.fetchOne(db, sql: sql)) try test(Row.fetchOne(statement)) try test(Row.fetchOne(db, SQLRequest(sql: sql))) @@ -366,7 +366,7 @@ class RowFetchTests: GRDBTestCase { } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql: sql, adapter: adapter)) try test(Row.fetchOne(statement, adapter: adapter)) @@ -405,7 +405,7 @@ class RowFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Row.fetchOne(db, sql: sql), sql: sql) - try test(Row.fetchOne(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Row.fetchOne(db.makeStatement(sql: sql)), sql: sql) try test(Row.fetchOne(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchOne(db), sql: sql) } @@ -413,7 +413,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql: sql, adapter: adapter), sql: sql) - try test(Row.fetchOne(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Row.fetchOne(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Row.fetchOne(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db), sql: sql) } @@ -437,7 +437,7 @@ class RowFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Row.fetchOne(db, sql: sql), sql: sql) - try test(Row.fetchOne(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Row.fetchOne(db.makeStatement(sql: sql)), sql: sql) try test(Row.fetchOne(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchOne(db), sql: sql) } @@ -445,7 +445,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql: sql, adapter: adapter), sql: sql) - try test(Row.fetchOne(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Row.fetchOne(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Row.fetchOne(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db), sql: sql) } diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index 90c8a9752..b6471ff35 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -25,7 +25,7 @@ class SelectStatementTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let sql = "SELECT 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 'Barbara', 'Gourde'" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let cursor = try statement.makeCursor() // Check that StatementCursor gives access to the raw SQLite API @@ -62,15 +62,15 @@ class SelectStatementTests : GRDBTestCase { // error. What we care about is that there is an error. } } - try test(db.makeSelectStatement(sql: "SELECT throw(), NULL").makeCursor()) - try test(db.makeSelectStatement(sql: "SELECT 0, throw(), NULL").makeCursor()) + try test(db.makeStatement(sql: "SELECT throw(), NULL").makeCursor()) + try test(db.makeStatement(sql: "SELECT 0, throw(), NULL").makeCursor()) } } func testArrayStatementArguments() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < ?") + let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < ?") let ages = [20, 30, 40, 50] let counts = try ages.map { try Int.fetchOne(statement, arguments: [$0])! } XCTAssertEqual(counts, [1,2,2,3]) @@ -80,7 +80,7 @@ class SelectStatementTests : GRDBTestCase { func testStatementArgumentsSetterWithArray() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < ?") + let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < ?") let ages = [20, 30, 40, 50] let counts = try ages.map { (age: Int) -> Int in statement.arguments = [age] @@ -93,7 +93,7 @@ class SelectStatementTests : GRDBTestCase { func testDictionaryStatementArguments() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < :age") + let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < :age") let ageDicts: [[String: DatabaseValueConvertible?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]] let counts = try ageDicts.map { dic -> Int in // Make sure we don't trigger a failible initializer @@ -107,7 +107,7 @@ class SelectStatementTests : GRDBTestCase { func testStatementArgumentsSetterWithDictionary() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < :age") + let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < :age") let ageDicts: [[String: DatabaseValueConvertible?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]] let counts = try ageDicts.map { ageDict -> Int in statement.arguments = StatementArguments(ageDict) @@ -121,7 +121,7 @@ class SelectStatementTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - _ = try db.makeSelectStatement(sql: "SELECT * FROM blah") + _ = try db.makeStatement(sql: "SELECT * FROM blah") XCTFail() } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) @@ -145,11 +145,11 @@ class SelectStatementTests : GRDBTestCase { let sql = "SELECT bomb()" needsThrow = false - XCTAssertEqual(try String.fetchAll(db.cachedSelectStatement(sql: sql)), ["success"]) + XCTAssertEqual(try String.fetchAll(db.cachedStatement(sql: sql)), ["success"]) do { needsThrow = true - _ = try String.fetchAll(db.cachedSelectStatement(sql: sql)) + _ = try String.fetchAll(db.cachedStatement(sql: sql)) XCTFail() } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) @@ -159,7 +159,121 @@ class SelectStatementTests : GRDBTestCase { } needsThrow = false - XCTAssertEqual(try String.fetchAll(db.cachedSelectStatement(sql: sql)), ["success"]) + XCTAssertEqual(try String.fetchAll(db.cachedStatement(sql: sql)), ["success"]) + } + } + + func testConsumeMultipleStatements() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.writeWithoutTransaction { db in + do { + // SQL, no argument + let statements = try db.allStatements(sql: """ + SELECT age FROM persons ORDER BY age; + SELECT age FROM persons ORDER BY age DESC; + """) + let ages = try Array(statements.flatMap { try Int.fetchCursor($0) }) + XCTAssertEqual(ages, [13, 26, 41, 41, 26, 13]) + } + do { + // Literal, no argument + let statements = try db.allStatements(literal: """ + SELECT age FROM persons ORDER BY age; + SELECT age FROM persons ORDER BY age DESC; + """) + let ages = try Array(statements.flatMap { try Int.fetchCursor($0) }) + XCTAssertEqual(ages, [13, 26, 41, 41, 26, 13]) + } + + do { + // SQL, missing arguments + let statements = try db.allStatements(sql: """ + SELECT count(*) FROM persons WHERE age > ?; + SELECT count(*) FROM persons WHERE age < ?; + """) + let counts = try Array(statements.map { try + Int.fetchOne($0, arguments: [30])! + }) + XCTAssertEqual(counts, [1, 2]) + } + do { + // Literal, missing arguments + let statements = try db.allStatements(literal: """ + SELECT count(*) FROM persons WHERE age > ?; + SELECT count(*) FROM persons WHERE age < ?; + """) + let counts = try Array(statements.map { try + Int.fetchOne($0, arguments: [30])! + }) + XCTAssertEqual(counts, [1, 2]) + } + + do { + // SQL, matching arguments + let statements = try db.allStatements(sql: """ + SELECT name FROM persons WHERE name = ?; + SELECT name FROM persons WHERE age > ? ORDER BY name; + """, arguments: ["Arthur", 20]) + let names = try Array(statements.map { try String.fetchAll($0) }) + XCTAssertEqual(names, [["Arthur"], ["Arthur", "Barbara"]]) + } + do { + // Literal, matching arguments + let statements = try db.allStatements(literal: """ + SELECT name FROM persons WHERE name = \("Arthur"); + SELECT name FROM persons WHERE age > \(20) ORDER BY name; + """) + let names = try Array(statements.map { try String.fetchAll($0) }) + XCTAssertEqual(names, [["Arthur"], ["Arthur", "Barbara"]]) + } + + do { + // SQL, too few arguments + let statements = try db.allStatements(sql: """ + SELECT name FROM persons WHERE name = ?; + SELECT name FROM persons WHERE age > ? ORDER BY name; + """, arguments: ["Arthur"]) + _ = try Array(statements.map { try String.fetchAll($0) }) + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { + // OK + } + do { + // Literal, too few arguments + let statements = try db.allStatements(literal: """ + SELECT name FROM persons WHERE name = \("Arthur"); + SELECT name FROM persons WHERE age > ? ORDER BY name; + """) + _ = try Array(statements.map { try String.fetchAll($0) }) + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { + // OK + } + + do { + // SQL, too many arguments + let statements = try db.allStatements(sql: """ + SELECT name FROM persons WHERE name = ?; + SELECT name FROM persons WHERE age > ? ORDER BY name; + """, arguments: ["Arthur", 20, 55]) + _ = try Array(statements.map { try String.fetchAll($0) }) + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { + // OK + } + + do { + // Mix statement kinds + let statements = try db.allStatements(literal: """ + CREATE TABLE t(a); + INSERT INTO t VALUES (0); + SELECT a FROM t ORDER BY a; + INSERT INTO t VALUES (1); + SELECT a FROM t ORDER BY a; + """) + let values = try Array(statements.map { try Int.fetchAll($0) }) + XCTAssertEqual(values, [[], [], [0], [], [0, 1]]) + } } } @@ -217,16 +331,16 @@ class SelectStatementTests : GRDBTestCase { try db.execute(sql: "CREATE TRIGGER table5trigger AFTER INSERT ON table5 BEGIN INSERT INTO table1 (id3, id4, a, b) VALUES (NULL, NULL, 0, 0); END") let statements = try [ - db.makeSelectStatement(sql: "SELECT * FROM table1"), - db.makeSelectStatement(sql: "SELECT id, id3, a FROM table1"), - db.makeSelectStatement(sql: "SELECT table1.id, table1.a, table2.a FROM table1 JOIN table2 ON table1.id = table2.id"), + db.makeStatement(sql: "SELECT * FROM table1"), + db.makeStatement(sql: "SELECT id, id3, a FROM table1"), + db.makeStatement(sql: "SELECT table1.id, table1.a, table2.a FROM table1 JOIN table2 ON table1.id = table2.id"), // This last request triggers its observer or not, depending on the SQLite version. // Before SQLite 3.19.0, its region is doubtful, and every database change is deemed impactful. // Starting SQLite 3.19.0, it knows that only table1 is involved. // // See doubtfulCountFunction below - db.makeSelectStatement(sql: "SELECT COUNT(*) FROM table1"), + db.makeStatement(sql: "SELECT COUNT(*) FROM table1"), ] let doubtfulCountFunction = (sqlite3_libversion_number() < 3019000) diff --git a/Tests/GRDBTests/StatementArguments+FoundationTests.swift b/Tests/GRDBTests/StatementArguments+FoundationTests.swift index eb9e4007a..812f625c8 100644 --- a/Tests/GRDBTests/StatementArguments+FoundationTests.swift +++ b/Tests/GRDBTests/StatementArguments+FoundationTests.swift @@ -25,7 +25,7 @@ class StatementArgumentsFoundationTests: GRDBTestCase { try dbQueue.inTransaction { db in - let statement = try db.makeUpdateStatement(sql: "INSERT INTO persons (name, age) VALUES (?, ?)") + let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (?, ?)") let persons: [[Any]] = [ ["Arthur", 41], ["Barbara", 38], @@ -63,7 +63,7 @@ class StatementArgumentsFoundationTests: GRDBTestCase { try dbQueue.inTransaction { db in - let statement = try db.makeUpdateStatement(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)") + let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)") let persons: [[AnyHashable: Any]] = [ ["name": "Arthur", "age": 41], ["name": "Barbara", "age": 38], diff --git a/Tests/GRDBTests/StatementArgumentsTests.swift b/Tests/GRDBTests/StatementArgumentsTests.swift index 6e4f2d144..aa00fcf47 100644 --- a/Tests/GRDBTests/StatementArgumentsTests.swift +++ b/Tests/GRDBTests/StatementArgumentsTests.swift @@ -20,7 +20,7 @@ class StatementArgumentsTests: GRDBTestCase { func testPositionalStatementArgumentsValidation() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let statement = try db.makeUpdateStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)") + let statement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)") do { // Correct number of arguments @@ -83,11 +83,11 @@ class StatementArgumentsTests: GRDBTestCase { let age = 42 let arguments = StatementArguments([name, age] as [DatabaseValueConvertible?]) - let updateStatement = try db.makeUpdateStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)") + let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)") updateStatement.arguments = arguments try updateStatement.execute() - let selectStatement = try db.makeSelectStatement(sql: "SELECT * FROM persons WHERE firstName = ? AND age = ?") + let selectStatement = try db.makeStatement(sql: "SELECT * FROM persons WHERE firstName = ? AND age = ?") selectStatement.arguments = arguments let row = try Row.fetchOne(selectStatement)! @@ -103,11 +103,11 @@ class StatementArgumentsTests: GRDBTestCase { let age = 42 let arguments = StatementArguments([name, age] as [DatabaseValueConvertible?]) - let updateStatement = try db.makeUpdateStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)") + let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)") try updateStatement.setArguments(arguments) try updateStatement.execute() - let selectStatement = try db.makeSelectStatement(sql: "SELECT * FROM persons WHERE firstName = ? AND age = ?") + let selectStatement = try db.makeStatement(sql: "SELECT * FROM persons WHERE firstName = ? AND age = ?") try selectStatement.setArguments(arguments) let row = try Row.fetchOne(selectStatement)! @@ -141,11 +141,11 @@ class StatementArgumentsTests: GRDBTestCase { let age = 42 let arguments = StatementArguments([name, age] as [DatabaseValueConvertible?]) - let updateStatement = try db.makeUpdateStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)") + let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)") updateStatement.setUncheckedArguments(arguments) try updateStatement.execute() - let selectStatement = try db.makeSelectStatement(sql: "SELECT * FROM persons WHERE firstName = ? AND age = ?") + let selectStatement = try db.makeStatement(sql: "SELECT * FROM persons WHERE firstName = ? AND age = ?") selectStatement.setUncheckedArguments(arguments) let row = try Row.fetchOne(selectStatement)! @@ -157,7 +157,7 @@ class StatementArgumentsTests: GRDBTestCase { func testNamedStatementArgumentsValidation() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let statement = try db.makeUpdateStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:firstName, :age)") + let statement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:firstName, :age)") do { // Correct number of arguments @@ -234,11 +234,11 @@ class StatementArgumentsTests: GRDBTestCase { let age = 42 let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) - let updateStatement = try db.makeUpdateStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:name, :age)") + let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:name, :age)") updateStatement.arguments = arguments try updateStatement.execute() - let selectStatement = try db.makeSelectStatement(sql: "SELECT * FROM persons WHERE firstName = :name AND age = :age") + let selectStatement = try db.makeStatement(sql: "SELECT * FROM persons WHERE firstName = :name AND age = :age") selectStatement.arguments = arguments let row = try Row.fetchOne(selectStatement)! @@ -254,11 +254,11 @@ class StatementArgumentsTests: GRDBTestCase { let age = 42 let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) - let updateStatement = try db.makeUpdateStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:name, :age)") + let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:name, :age)") try updateStatement.setArguments(arguments) try updateStatement.execute() - let selectStatement = try db.makeSelectStatement(sql: "SELECT * FROM persons WHERE firstName = :name AND age = :age") + let selectStatement = try db.makeStatement(sql: "SELECT * FROM persons WHERE firstName = :name AND age = :age") try selectStatement.setArguments(arguments) let row = try Row.fetchOne(selectStatement)! @@ -292,11 +292,11 @@ class StatementArgumentsTests: GRDBTestCase { let age = 42 let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) - let updateStatement = try db.makeUpdateStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:name, :age)") + let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:name, :age)") updateStatement.setUncheckedArguments(arguments) try updateStatement.execute() - let selectStatement = try db.makeSelectStatement(sql: "SELECT * FROM persons WHERE firstName = :name AND age = :age") + let selectStatement = try db.makeStatement(sql: "SELECT * FROM persons WHERE firstName = :name AND age = :age") selectStatement.setUncheckedArguments(arguments) let row = try Row.fetchOne(selectStatement)! @@ -308,7 +308,7 @@ class StatementArgumentsTests: GRDBTestCase { func testReusedNamedStatementArgumentsValidation() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let statement = try db.makeUpdateStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)") + let statement = try db.makeStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)") do { try statement.execute(arguments: ["name": "foo", "age": 1]) @@ -394,11 +394,11 @@ class StatementArgumentsTests: GRDBTestCase { let age = 42 let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) - let updateStatement = try db.makeUpdateStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)") + let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)") updateStatement.arguments = arguments try updateStatement.execute() - let selectStatement = try db.makeSelectStatement(sql: "SELECT * FROM persons WHERE firstName = :name AND lastName = :name AND age = :age") + let selectStatement = try db.makeStatement(sql: "SELECT * FROM persons WHERE firstName = :name AND lastName = :name AND age = :age") selectStatement.arguments = arguments let row = try Row.fetchOne(selectStatement)! @@ -414,11 +414,11 @@ class StatementArgumentsTests: GRDBTestCase { let age = 42 let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) - let updateStatement = try db.makeUpdateStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)") + let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)") try updateStatement.setArguments(arguments) try updateStatement.execute() - let selectStatement = try db.makeSelectStatement(sql: "SELECT * FROM persons WHERE firstName = :name AND lastName = :name AND age = :age") + let selectStatement = try db.makeStatement(sql: "SELECT * FROM persons WHERE firstName = :name AND lastName = :name AND age = :age") try selectStatement.setArguments(arguments) let row = try Row.fetchOne(selectStatement)! @@ -452,11 +452,11 @@ class StatementArgumentsTests: GRDBTestCase { let age = 42 let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) - let updateStatement = try db.makeUpdateStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)") + let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)") updateStatement.setUncheckedArguments(arguments) try updateStatement.execute() - let selectStatement = try db.makeSelectStatement(sql: "SELECT * FROM persons WHERE firstName = :name AND lastName = :name AND age = :age") + let selectStatement = try db.makeStatement(sql: "SELECT * FROM persons WHERE firstName = :name AND lastName = :name AND age = :age") selectStatement.setUncheckedArguments(arguments) let row = try Row.fetchOne(selectStatement)! diff --git a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift index 05e1e586c..f0dbc1a75 100644 --- a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift +++ b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift @@ -121,7 +121,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 UNION ALL SELECT 2" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchCursor(db, sql: sql)) try test(Fetched.fetchCursor(statement)) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql))) @@ -129,7 +129,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql: sql, adapter: adapter)) try test(Fetched.fetchCursor(statement, adapter: adapter)) @@ -176,7 +176,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Fetched.fetchCursor(db, sql: sql), sql: sql) - try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchCursor(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchCursor(db), sql: sql) } @@ -184,7 +184,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchCursor(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchCursor(db), sql: sql) } @@ -208,7 +208,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchCursor(db, sql: sql), sql: sql) - try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchCursor(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchCursor(db), sql: sql) } @@ -216,7 +216,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchCursor(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchCursor(db), sql: sql) } @@ -232,7 +232,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 UNION ALL SELECT 2" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchAll(db, sql: sql)) try test(Fetched.fetchAll(statement)) try test(Fetched.fetchAll(db, SQLRequest(sql: sql))) @@ -240,7 +240,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql: sql, adapter: adapter)) try test(Fetched.fetchAll(statement, adapter: adapter)) @@ -279,7 +279,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Fetched.fetchAll(db, sql: sql), sql: sql) - try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchAll(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchAll(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchAll(db), sql: sql) } @@ -287,7 +287,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchAll(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchAll(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchAll(db), sql: sql) } @@ -311,7 +311,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchAll(db, sql: sql), sql: sql) - try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchAll(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchAll(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchAll(db), sql: sql) } @@ -319,7 +319,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchAll(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchAll(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchAll(db), sql: sql) } @@ -335,7 +335,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 UNION ALL SELECT 2" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchSet(db, sql: sql)) try test(Fetched.fetchSet(statement)) try test(Fetched.fetchSet(db, SQLRequest(sql: sql))) @@ -343,7 +343,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchSet(db, sql: sql, adapter: adapter)) try test(Fetched.fetchSet(statement, adapter: adapter)) @@ -382,7 +382,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Fetched.fetchSet(db, sql: sql), sql: sql) - try test(Fetched.fetchSet(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchSet(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchSet(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchSet(db), sql: sql) } @@ -390,7 +390,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchSet(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchSet(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchSet(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchSet(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchSet(db), sql: sql) } @@ -414,7 +414,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchSet(db, sql: sql), sql: sql) - try test(Fetched.fetchSet(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchSet(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchSet(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchSet(db), sql: sql) } @@ -422,7 +422,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchSet(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchSet(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchSet(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchSet(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchSet(db), sql: sql) } @@ -438,7 +438,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 WHERE 0" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchOne(db, sql: sql)) try test(Fetched.fetchOne(statement)) try test(Fetched.fetchOne(db, SQLRequest(sql: sql))) @@ -446,7 +446,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 WHERE 0" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) @@ -460,7 +460,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchOne(db, sql: sql)) try test(Fetched.fetchOne(statement)) try test(Fetched.fetchOne(db, SQLRequest(sql: sql))) @@ -468,7 +468,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) @@ -482,7 +482,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Fetched.fetchOne(db, sql: sql)) try test(Fetched.fetchOne(statement)) try test(Fetched.fetchOne(db, SQLRequest(sql: sql))) @@ -490,7 +490,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) @@ -530,7 +530,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Fetched.fetchOne(db, sql: sql), sql: sql) - try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchOne(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchOne(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchOne(db), sql: sql) } @@ -538,7 +538,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchOne(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchOne(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db), sql: sql) } @@ -562,7 +562,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchOne(db, sql: sql), sql: sql) - try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Fetched.fetchOne(db.makeStatement(sql: sql)), sql: sql) try test(Fetched.fetchOne(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchOne(db), sql: sql) } @@ -570,7 +570,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql: sql, adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Fetched.fetchOne(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Fetched.fetchOne(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db), sql: sql) } @@ -592,7 +592,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 UNION ALL SELECT NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Optional.fetchCursor(db, sql: sql)) try test(Optional.fetchCursor(statement)) try test(Optional.fetchCursor(db, SQLRequest(sql: sql))) @@ -600,7 +600,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql: sql, adapter: adapter)) try test(Optional.fetchCursor(statement, adapter: adapter)) @@ -638,7 +638,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchCursor(db, sql: sql), sql: sql) - try test(Optional.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Optional.fetchCursor(db.makeStatement(sql: sql)), sql: sql) try test(Optional.fetchCursor(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchCursor(db), sql: sql) } @@ -646,7 +646,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql: sql, adapter: adapter), sql: sql) - try test(Optional.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.fetchCursor(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Optional.fetchCursor(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchCursor(db), sql: sql) } @@ -664,7 +664,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 UNION ALL SELECT NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Optional.fetchAll(db, sql: sql)) try test(Optional.fetchAll(statement)) try test(Optional.fetchAll(db, SQLRequest(sql: sql))) @@ -672,7 +672,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql: sql, adapter: adapter)) try test(Optional.fetchAll(statement, adapter: adapter)) @@ -711,7 +711,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Optional.fetchAll(db, sql: sql), sql: sql) - try test(Optional.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Optional.fetchAll(db.makeStatement(sql: sql)), sql: sql) try test(Optional.fetchAll(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchAll(db), sql: sql) } @@ -719,7 +719,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql: sql, adapter: adapter), sql: sql) - try test(Optional.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.fetchAll(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Optional.fetchAll(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchAll(db), sql: sql) } @@ -743,7 +743,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchAll(db, sql: sql), sql: sql) - try test(Optional.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Optional.fetchAll(db.makeStatement(sql: sql)), sql: sql) try test(Optional.fetchAll(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchAll(db), sql: sql) } @@ -751,7 +751,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql: sql, adapter: adapter), sql: sql) - try test(Optional.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.fetchAll(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Optional.fetchAll(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchAll(db), sql: sql) } @@ -767,7 +767,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 1 UNION ALL SELECT NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) try test(Optional.fetchSet(db, sql: sql)) try test(Optional.fetchSet(statement)) try test(Optional.fetchSet(db, SQLRequest(sql: sql))) @@ -775,7 +775,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" - let statement = try db.makeSelectStatement(sql: sql) + let statement = try db.makeStatement(sql: sql) let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchSet(db, sql: sql, adapter: adapter)) try test(Optional.fetchSet(statement, adapter: adapter)) @@ -814,7 +814,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT throw()" try test(Optional.fetchSet(db, sql: sql), sql: sql) - try test(Optional.fetchSet(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Optional.fetchSet(db.makeStatement(sql: sql)), sql: sql) try test(Optional.fetchSet(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchSet(db), sql: sql) } @@ -822,7 +822,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchSet(db, sql: sql, adapter: adapter), sql: sql) - try test(Optional.fetchSet(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.fetchSet(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Optional.fetchSet(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchSet(db), sql: sql) } @@ -846,7 +846,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchSet(db, sql: sql), sql: sql) - try test(Optional.fetchSet(db.makeSelectStatement(sql: sql)), sql: sql) + try test(Optional.fetchSet(db.makeStatement(sql: sql)), sql: sql) try test(Optional.fetchSet(db, SQLRequest(sql: sql)), sql: sql) try test(SQLRequest(sql: sql).fetchSet(db), sql: sql) } @@ -854,7 +854,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchSet(db, sql: sql, adapter: adapter), sql: sql) - try test(Optional.fetchSet(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.fetchSet(db.makeStatement(sql: sql), adapter: adapter), sql: sql) try test(Optional.fetchSet(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql: sql, adapter: adapter).fetchSet(db), sql: sql) } diff --git a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift similarity index 97% rename from Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift rename to Tests/GRDBTests/TableRecordDeleteTests.swift index c817aa5cf..d1b5a2965 100644 --- a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -1,31 +1,28 @@ import XCTest import GRDB -private struct Hacker : MutablePersistableRecord { +private struct Hacker : TableRecord { static let databaseTableName = "hackers" - func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } var id: Int64? // Optional } @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) extension Hacker: Identifiable { } -private struct Person : MutablePersistableRecord { +private struct Person : TableRecord { static let databaseTableName = "persons" - func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } var id: Int64 // Non-optional } @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) extension Person: Identifiable { } -private struct Citizenship : MutablePersistableRecord { +private struct Citizenship : TableRecord { static let databaseTableName = "citizenships" - func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } } -class MutablePersistableRecordDeleteTests: GRDBTestCase { +class TableRecordDeleteTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in diff --git a/Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift b/Tests/GRDBTests/TableRecordUpdateTests.swift similarity index 90% rename from Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift rename to Tests/GRDBTests/TableRecordUpdateTests.swift index 68c4253d9..4154bdf30 100644 --- a/Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift +++ b/Tests/GRDBTests/TableRecordUpdateTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -private struct Player: Codable, PersistableRecord, FetchableRecord { +private struct Player: Codable, TableRecord, FetchableRecord { var id: Int64 var name: String var score: Int @@ -30,7 +30,7 @@ private extension QueryInterfaceRequest where RowDecoder == Player { } } -class MutablePersistableRecordUpdateTests: GRDBTestCase { +class TableRecordUpdateTests: GRDBTestCase { func testRequestUpdateAll() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -282,10 +282,12 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { func testUpdateAllReturnsNumberOfUpdatedRows() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) - try Player(id: 1, name: "Arthur", score: 0, bonus: 2).insert(db) - try Player(id: 2, name: "Barbara", score: 0, bonus: 1).insert(db) - try Player(id: 3, name: "Craig", score: 0, bonus: 0).insert(db) - try Player(id: 4, name: "Diane", score: 0, bonus: 3).insert(db) + try db.execute(sql: """ + INSERT INTO player (id, name, score, bonus) VALUES (1, 'Arthur', 0, 2); + INSERT INTO player (id, name, score, bonus) VALUES (2, 'Barbara', 0, 1); + INSERT INTO player (id, name, score, bonus) VALUES (3, 'Craig', 0, 0); + INSERT INTO player (id, name, score, bonus) VALUES (4, 'Diane', 0, 3); + """) let assignment = Columns.score += 1 @@ -305,10 +307,12 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { func testQueryInterfaceExtension() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) - try Player(id: 1, name: "Arthur", score: 0, bonus: 0).insert(db) - try Player(id: 2, name: "Barbara", score: 0, bonus: 0).insert(db) - try Player(id: 3, name: "Craig", score: 0, bonus: 0).insert(db) - try Player(id: 4, name: "Diane", score: 0, bonus: 0).insert(db) + try db.execute(sql: """ + INSERT INTO player (id, name, score, bonus) VALUES (1, 'Arthur', 0, 0); + INSERT INTO player (id, name, score, bonus) VALUES (2, 'Barbara', 0, 0); + INSERT INTO player (id, name, score, bonus) VALUES (3, 'Craig', 0, 0); + INSERT INTO player (id, name, score, bonus) VALUES (4, 'Diane', 0, 0); + """) try Player.all().incrementScore(db) try XCTAssertEqual(Player.filter(Columns.score == 1).fetchCount(db), 4) @@ -380,6 +384,38 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { } } + func testConflictPolicyIgnoreWithTable() throws { + struct IgnorePlayer: PersistableRecord { + static let databaseTableName = "player" + static let persistenceConflictPolicy = PersistenceConflictPolicy(insert: .abort, update: .ignore) + func encode(to container: inout PersistenceContainer) { } + } + let table = Table("player") + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try table.updateAll(db, Column("score").set(to: 0)) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + + try table.updateAll(db, [Column("score").set(to: 0)]) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + + try table.all().updateAll(db, Column("score").set(to: 0)) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + + try table.all().updateAll(db, [Column("score").set(to: 0)]) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + } + } + func testConflictPolicyCustom() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) diff --git a/Tests/GRDBTests/TableTests.swift b/Tests/GRDBTests/TableTests.swift new file mode 100644 index 000000000..86f9761bc --- /dev/null +++ b/Tests/GRDBTests/TableTests.swift @@ -0,0 +1,863 @@ +import XCTest +import GRDB + +class TableTests: GRDBTestCase { + func test_Table_nameRoundTrip() { + let table = Table("Player") + XCTAssertEqual(table.tableName, "Player") + } + + func test_Table_defaults_to_Row() { + // This test passes if it compiles + func f(_: Table) { } + let table = Table("Player") + f(table) + } + + func test_Table_accepts_any_type() { + // This test passes if it compiles + struct S { } + class C { } + _ = Table("ignored") + _ = Table("ignored") + } + + func test_request_derivation() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + + do { + let t = Table("player") + try assertEqualSQL(db, t.all(), """ + SELECT * FROM "player" + """) + try assertEqualSQL(db, t.none(), """ + SELECT * FROM "player" WHERE 0 + """) + try assertEqualSQL(db, t.select(Column("id"), Column("name")), """ + SELECT "id", "name" FROM "player" + """) + try assertEqualSQL(db, t.select([Column("id"), Column("name")]), """ + SELECT "id", "name" FROM "player" + """) + try assertEqualSQL(db, t.select(sql: "id, ?", arguments: ["O'Brien"]), """ + SELECT id, 'O''Brien' FROM "player" + """) + try assertEqualSQL(db, t.select(literal: "id, \("O'Brien")"), """ + SELECT id, 'O''Brien' FROM "player" + """) + try XCTAssertEqual(t.select(Column("id"), as: Int64.self).fetchOne(db), 1) + try XCTAssertEqual(t.select(Column("id")).fetchOne(db), 1) + try XCTAssertEqual(t.select([Column("name")], as: String.self).fetchOne(db), "Alice") + try XCTAssertEqual(t.select([Column("name")]).fetchOne(db), "Alice") + try XCTAssertEqual(t.select(sql: "id", as: Int64.self).fetchOne(db), 1) + try XCTAssertEqual(t.select(sql: "id").fetchOne(db), 1) + try XCTAssertEqual(t.select(literal: "name", as: String.self).fetchOne(db), "Alice") + try XCTAssertEqual(t.select(literal: "name").fetchOne(db), "Alice") + try assertEqualSQL(db, t.annotated(with: Column.rowID), """ + SELECT *, "rowid" FROM "player" + """) + try assertEqualSQL(db, t.annotated(with: [Column.rowID]), """ + SELECT *, "rowid" FROM "player" + """) + try assertEqualSQL(db, t.filter(Column("id") > 10), """ + SELECT * FROM "player" WHERE "id" > 10 + """) + try assertEqualSQL(db, t.filter(key: 1), """ + SELECT * FROM "player" WHERE "id" = 1 + """) + try assertEqualSQL(db, t.filter(keys: [1, 2, 3]), """ + SELECT * FROM "player" WHERE "id" IN (1, 2, 3) + """) + try assertEqualSQL(db, t.filter(key: ["id": 1]), """ + SELECT * FROM "player" WHERE "id" = 1 + """) + try assertEqualSQL(db, t.filter(keys: [["id": 1], ["id": 2]]), """ + SELECT * FROM "player" WHERE ("id" = 1) OR ("id" = 2) + """) + try assertEqualSQL(db, t.filter(sql: "name = ?", arguments: ["O'Brien"]), """ + SELECT * FROM "player" WHERE name = 'O''Brien' + """) + try assertEqualSQL(db, t.filter(literal: "name = \("O'Brien")"), """ + SELECT * FROM "player" WHERE name = 'O''Brien' + """) + try assertEqualSQL(db, t.order(Column("id"), Column("name").desc), """ + SELECT * FROM "player" ORDER BY "id", "name" DESC + """) + try assertEqualSQL(db, t.order([Column("id"), Column("name").desc]), """ + SELECT * FROM "player" ORDER BY "id", "name" DESC + """) + try assertEqualSQL(db, t.orderByPrimaryKey(), """ + SELECT * FROM "player" ORDER BY "id" + """) + try assertEqualSQL(db, t.order(sql: "IFNULL(name, ?)", arguments: ["O'Brien"]), """ + SELECT * FROM "player" ORDER BY IFNULL(name, 'O''Brien') + """) + try assertEqualSQL(db, t.order(literal: "IFNULL(name, \("O'Brien"))"), """ + SELECT * FROM "player" ORDER BY IFNULL(name, 'O''Brien') + """) + try assertEqualSQL(db, t.limit(1), """ + SELECT * FROM "player" LIMIT 1 + """) + try assertEqualSQL(db, t.limit(1, offset: 3), """ + SELECT * FROM "player" LIMIT 1 OFFSET 3 + """) + try assertEqualSQL(db, t.aliased(TableAlias(name: "p")), """ + SELECT "p".* FROM "player" "p" + """) + try assertEqualSQL(db, t.with(CommonTableExpression(named: "cte", literal: "SELECT \("O'Brien")")), """ + WITH "cte" AS (SELECT 'O''Brien') SELECT * FROM "player" + """) + } + + if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + struct Player: Identifiable { var id: Int64 } + let t = Table("player") + + try assertEqualSQL(db, t.filter(id: 1), """ + SELECT * FROM "player" WHERE "id" = 1 + """) + try assertEqualSQL(db, t.filter(ids: [1, 2, 3]), """ + SELECT * FROM "player" WHERE "id" IN (1, 2, 3) + """) + try XCTAssertEqual(t.selectID().fetchOne(db), 1) + } + + if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + struct Player: Identifiable { var id: Int64? } + let t = Table("player") + + try assertEqualSQL(db, t.filter(id: 1), """ + SELECT * FROM "player" WHERE "id" = 1 + """) + try assertEqualSQL(db, t.filter(ids: [1, 2, 3]), """ + SELECT * FROM "player" WHERE "id" IN (1, 2, 3) + """) + try XCTAssertEqual(t.selectID().fetchOne(db), 1) + } + } + } + + func test_fetchCount() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + let t = Table("player") + try XCTAssertEqual(t.fetchCount(db), 0) + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + try XCTAssertEqual(t.fetchCount(db), 1) + } + } + + func test_fetch_FetchableRecord() throws { + struct Player: FetchableRecord, Decodable, Hashable { + var id: Int64 + var name: String + } + + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + + let t = Table("player") + try XCTAssertEqual(t.fetchCursor(db).next(), Player(id: 1, name: "Alice")) + try XCTAssertEqual(t.fetchAll(db), [Player(id: 1, name: "Alice")]) + try XCTAssertEqual(t.fetchSet(db), [Player(id: 1, name: "Alice")]) + try XCTAssertEqual(t.fetchOne(db), Player(id: 1, name: "Alice")) + } + } + + func test_fetch_Row() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + + let t = Table("player") + try XCTAssertEqual(t.fetchCursor(db).map { $0.copy() }.next(), ["id": 1, "name": "Alice"]) + try XCTAssertEqual(t.fetchAll(db), [["id": 1, "name": "Alice"]]) + try XCTAssertEqual(t.fetchSet(db), [["id": 1, "name": "Alice"]]) + try XCTAssertEqual(t.fetchOne(db), ["id": 1, "name": "Alice"]) + } + } + + func test_fetch_DatabaseValueConvertible() throws { + struct Value: DatabaseValueConvertible, Hashable { + var rawValue: Int64 + var databaseValue: DatabaseValue { rawValue.databaseValue } + static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Value? { + Int64.fromDatabaseValue(dbValue).map(Value.init) + } + } + + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + + let t = Table("player") + try XCTAssertEqual(t.fetchCursor(db).next(), Value(rawValue: 1)) + try XCTAssertEqual(t.fetchAll(db), [Value(rawValue: 1)]) + try XCTAssertEqual(t.fetchSet(db), [Value(rawValue: 1)]) + + do { + try db.execute(sql: "DELETE FROM player") + try XCTAssertEqual(t.fetchOne(db), nil) + } + + do { + try db.execute(sql: "DELETE FROM player") + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + try XCTAssertEqual(t.fetchOne(db), Value(rawValue: 1)) + } + } + } + + func test_fetch_optional_DatabaseValueConvertible() throws { + struct Value: DatabaseValueConvertible, Hashable { + var rawValue: String + var databaseValue: DatabaseValue { rawValue.databaseValue } + static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Value? { + String.fromDatabaseValue(dbValue).map(Value.init) + } + } + + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES ('Alice')") + try db.execute(sql: "INSERT INTO player VALUES (NULL)") + + let t = Table("player") + try XCTAssertEqual(t.fetchCursor(db).next(), Value(rawValue: "Alice")) + try XCTAssertEqual(t.fetchAll(db), [Value(rawValue: "Alice"), nil]) + try XCTAssertEqual(t.fetchSet(db), [Value(rawValue: "Alice"), nil]) + + do { + try db.execute(sql: "DELETE FROM player") + try XCTAssertEqual(t.fetchOne(db), nil) + } + + do { + try db.execute(sql: "DELETE FROM player") + try db.execute(sql: "INSERT INTO player VALUES ('Alice')") + try XCTAssertEqual(t.fetchOne(db), Value(rawValue: "Alice")) + } + + do { + try db.execute(sql: "DELETE FROM player") + try db.execute(sql: "INSERT INTO player VALUES (NULL)") + try XCTAssertEqual(t.fetchOne(db), nil) + } + } + } + + func test_fetch_StatementColumnConvertible() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + + let t = Table("player") + try XCTAssertEqual(t.fetchCursor(db).next(), 1) + try XCTAssertEqual(t.fetchAll(db), [1]) + try XCTAssertEqual(t.fetchSet(db), [1]) + + do { + try db.execute(sql: "DELETE FROM player") + try XCTAssertEqual(t.fetchOne(db), nil) + } + + do { + try db.execute(sql: "DELETE FROM player") + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + try XCTAssertEqual(t.fetchOne(db), 1) + } + } + } + + func test_fetch_optional_StatementColumnConvertible() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES ('Alice')") + try db.execute(sql: "INSERT INTO player VALUES (NULL)") + + let t = Table("player") + try XCTAssertEqual(t.fetchCursor(db).next(), "Alice") + try XCTAssertEqual(t.fetchAll(db), ["Alice", nil]) + try XCTAssertEqual(t.fetchSet(db), ["Alice", nil]) + + do { + try db.execute(sql: "DELETE FROM player") + try XCTAssertEqual(t.fetchOne(db), nil) + } + + do { + try db.execute(sql: "DELETE FROM player") + try db.execute(sql: "INSERT INTO player VALUES ('Alice')") + try XCTAssertEqual(t.fetchOne(db), "Alice") + } + + do { + try db.execute(sql: "DELETE FROM player") + try db.execute(sql: "INSERT INTO player VALUES (NULL)") + try XCTAssertEqual(t.fetchOne(db), nil) + } + } + } + + func test_association_belongsTo_Table() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + let player = Table("player") + let association = player.belongsTo(Table("team")) + try assertEqualSQL(db, player.including(optional: association), """ + SELECT "player".*, "team".* \ + FROM "player" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, player.including(required: association), """ + SELECT "player".*, "team".* \ + FROM "player" \ + JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, player.joining(optional: association), """ + SELECT "player".* \ + FROM "player" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, player.joining(required: association), """ + SELECT "player".* \ + FROM "player" \ + JOIN "team" ON "team"."id" = "player"."teamID" + """) + } + } + + func test_association_belongsTo_TableRecord() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + struct Team: TableRecord { } + let player = Table("player") + let association = player.belongsTo(Team.self) + try assertEqualSQL(db, player.including(optional: association), """ + SELECT "player".*, "team".* \ + FROM "player" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, player.including(required: association), """ + SELECT "player".*, "team".* \ + FROM "player" \ + JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, player.joining(optional: association), """ + SELECT "player".* \ + FROM "player" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, player.joining(required: association), """ + SELECT "player".* \ + FROM "player" \ + JOIN "team" ON "team"."id" = "player"."teamID" + """) + } + } + + func test_association_hasOne_Table() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + let team = Table("team") + let association = team.hasOne(Table("player")) + try assertEqualSQL(db, team.including(optional: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.including(required: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(optional: association), """ + SELECT "team".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(required: association), """ + SELECT "team".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + } + } + + func test_association_hasOne_TableRecord() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + struct Player: TableRecord { } + let team = Table("team") + let association = team.hasOne(Player.self) + try assertEqualSQL(db, team.including(optional: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.including(required: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(optional: association), """ + SELECT "team".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(required: association), """ + SELECT "team".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + } + } + + func test_association_hasMany_Table() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + let team = Table("team") + let association = team.hasMany(Table("player")) + try assertEqualSQL(db, team.including(optional: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.including(required: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(optional: association), """ + SELECT "team".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(required: association), """ + SELECT "team".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + _ = team.including(all: association) // TODO: test + } + } + + func test_association_hasMany_TableRecord() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + struct Player: TableRecord { } + let team = Table("team") + let association = team.hasMany(Player.self) + try assertEqualSQL(db, team.including(optional: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.including(required: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(optional: association), """ + SELECT "team".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(required: association), """ + SELECT "team".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + _ = team.including(all: association) // TODO: test + } + } + + func test_association_to_CommonTableExpression() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + let player = Table("player") + let cte = CommonTableExpression(named: "teamBis", request: Table("team").all()) + let association = player.association(to: cte, on: { $0["teamID"] == $1["id"] }) + try assertEqualSQL(db, player.with(cte).including(optional: association), """ + WITH "teamBis" AS (SELECT * FROM "team") \ + SELECT "player".*, "teamBis".* \ + FROM "player" \ + LEFT JOIN "teamBis" ON "player"."teamID" = "teamBis"."id" + """) + try assertEqualSQL(db, player.with(cte).including(required: association), """ + WITH "teamBis" AS (SELECT * FROM "team") \ + SELECT "player".*, "teamBis".* \ + FROM "player" \ + JOIN "teamBis" ON "player"."teamID" = "teamBis"."id" + """) + try assertEqualSQL(db, player.with(cte).joining(optional: association), """ + WITH "teamBis" AS (SELECT * FROM "team") \ + SELECT "player".* \ + FROM "player" \ + LEFT JOIN "teamBis" ON "player"."teamID" = "teamBis"."id" + """) + try assertEqualSQL(db, player.with(cte).joining(required: association), """ + WITH "teamBis" AS (SELECT * FROM "team") \ + SELECT "player".* \ + FROM "player" \ + JOIN "teamBis" ON "player"."teamID" = "teamBis"."id" + """) + } + } + + func test_association_hasOneThrough() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + try db.create(table: "award") { t in + t.autoIncrementedPrimaryKey("id") + t.column("playerID", .integer).references("player") + } + + let team = Table("team") + let player = Table("player") + let award = Table("award") + let association = award.hasOne( + Row.self, + through: award.belongsTo(player), + using: player.belongsTo(team)) + try assertEqualSQL(db, award.including(optional: association), """ + SELECT "award".*, "team".* \ + FROM "award" \ + LEFT JOIN "player" ON "player"."id" = "award"."playerID" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, award.including(required: association), """ + SELECT "award".*, "team".* \ + FROM "award" \ + JOIN "player" ON "player"."id" = "award"."playerID" \ + JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, award.joining(optional: association), """ + SELECT "award".* \ + FROM "award" \ + LEFT JOIN "player" ON "player"."id" = "award"."playerID" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, award.joining(required: association), """ + SELECT "award".* \ + FROM "award" \ + JOIN "player" ON "player"."id" = "award"."playerID" \ + JOIN "team" ON "team"."id" = "player"."teamID" + """) + } + } + + func test_association_hasManyThrough() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + try db.create(table: "award") { t in + t.autoIncrementedPrimaryKey("id") + t.column("playerID", .integer).references("player") + } + + let team = Table("team") + let player = Table("player") + let award = Table("award") + let association = team.hasMany( + Row.self, + through: team.hasMany(player), + using: player.hasMany(award)) + try assertEqualSQL(db, team.including(optional: association), """ + SELECT "team".*, "award".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" \ + LEFT JOIN "award" ON "award"."playerID" = "player"."id" + """) + try assertEqualSQL(db, team.including(required: association), """ + SELECT "team".*, "award".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" \ + JOIN "award" ON "award"."playerID" = "player"."id" + """) + try assertEqualSQL(db, team.joining(optional: association), """ + SELECT "team".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" \ + LEFT JOIN "award" ON "award"."playerID" = "player"."id" + """) + try assertEqualSQL(db, team.joining(required: association), """ + SELECT "team".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" \ + JOIN "award" ON "award"."playerID" = "player"."id" + """) + _ = team.including(all: association) // TODO: test + } + } + + func test_association_aggregates() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + let team = Table("team") + let association = team.hasMany(Table("player")) + try assertEqualSQL(db, team.annotated(with: association.count, association.max(Column("id"))), """ + SELECT "team".*, COUNT(DISTINCT "player"."id") AS "playerCount", MAX("player"."id") AS "maxPlayerId" \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" \ + GROUP BY "team"."id" + """) + try assertEqualSQL(db, team.annotated(with: [association.count, association.max(Column("id"))]), """ + SELECT "team".*, COUNT(DISTINCT "player"."id") AS "playerCount", MAX("player"."id") AS "maxPlayerId" \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" \ + GROUP BY "team"."id" + """) + try assertEqualSQL(db, team.having(association.isEmpty), """ + SELECT "team".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" \ + GROUP BY "team"."id" \ + HAVING COUNT(DISTINCT "player"."id") = 0 + """) + } + } + + func test_delete() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("a").unique() + t.column("b") + t.column("c") + t.uniqueKey(["b", "c"]) + } + try db.create(table: "country") { t in + t.column("code", .text).notNull().primaryKey() + } + try db.create(table: "document") { t in + t.column("a") + } + + // Use Table when we want to make sure the generic type is not used. + + do { + try Table("player").deleteAll(db) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" + """) + + try Table("player").all().deleteAll(db) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" + """) + } + + do { + try Table("player").deleteOne(db, key: 1) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" WHERE "id" = 1 + """) + + try Table("country").deleteOne(db, key: "FR") + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "country" WHERE "code" = 'FR' + """) + + try Table("document").deleteOne(db, key: 1) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "document" WHERE "rowid" = 1 + """) + } + + do { + try Table("player").deleteOne(db, key: ["a": "foo"]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" WHERE "a" = 'foo' + """) + + try Table("player").deleteOne(db, key: ["b": "bar", "c": "baz"]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" WHERE ("b" = 'bar') AND ("c" = 'baz') + """) + } + + do { + try Table("player").deleteAll(db, keys: [1, 2]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" WHERE "id" IN (1, 2) + """) + + try Table("country").deleteAll(db, keys: ["FR", "DE"]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "country" WHERE "code" IN ('FR', 'DE') + """) + + try Table("document").deleteAll(db, keys: [1, 2]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "document" WHERE "rowid" IN (1, 2) + """) + } + + do { + try Table("player").deleteAll(db, keys: [["a": "toto"], ["a": "titi"]]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" WHERE ("a" = 'toto') OR ("a" = 'titi') + """) + + try Table("player").deleteAll(db, keys: [["b": "toto", "c": "titi"], ["b": "tata", "c": "tonton"]]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" WHERE (("b" = 'toto') AND ("c" = 'titi')) OR (("b" = 'tata') AND ("c" = 'tonton')) + """) + } + + if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + // Non-optional ID + struct Country: Identifiable { var id: String } + + try Table("country").deleteOne(db, id: "FR") + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "country" WHERE "code" = 'FR' + """) + + try Table("country").deleteAll(db, ids: ["FR", "DE"]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "country" WHERE "code" IN ('FR', 'DE') + """) + } + + if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + // Optional ID + struct Country: Identifiable { var id: String? } + + try Table("country").deleteOne(db, id: "FR") + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "country" WHERE "code" = 'FR' + """) + + try Table("country").deleteAll(db, ids: ["FR", "DE"]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "country" WHERE "code" IN ('FR', 'DE') + """) + } + } + } + + func test_updateAll() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("score", .integer) + } + let assignment = Column("score").set(to: 0) + + // Use Table when we want to make sure the generic type is not used. + + do { + try Table("player").updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 + """) + } + do { + try Table("player").updateAll(db, [assignment]) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 + """) + } + do { + try Table("player").updateAll(db, onConflict: .ignore, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + } + } + } +} diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index c6e89389a..f7c5ae16b 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -617,6 +617,38 @@ class TransactionObserverTests: GRDBTestCase { } } + func testInsertEventWithCursor() throws { + let dbQueue = try makeDatabaseQueue() + try setupArtistDatabase(in: dbQueue) + let observer = Observer() + dbQueue.add(transactionObserver: observer) + + try dbQueue.writeWithoutTransaction { db in + let insertedName = "Gerhard Richter" + let statement = try db.makeStatement(literal: "INSERT INTO artists (name) VALUES (\(insertedName))") + _ = try Row.fetchCursor(statement).next() + let insertedId = db.lastInsertedRowID + + XCTAssertEqual(observer.lastCommittedEvents.count, 1) + let event = observer.lastCommittedEvents.filter { event in + self.match(event: event, kind: .insert, tableName: "artists", rowId: insertedId) + }.first + XCTAssertTrue(event != nil) + + #if SQLITE_ENABLE_PREUPDATE_HOOK + XCTAssertEqual(observer.lastCommittedPreUpdateEvents.count, 1) + let preUpdateEvent = observer.lastCommittedPreUpdateEvents.filter { event in + self.match(preUpdateEvent: event, kind: .insert, tableName: "artists", initialRowID: nil, finalRowID: insertedId, initialValues: nil, + finalValues: [ + insertedId.databaseValue, + insertedName.databaseValue + ]) + }.first + XCTAssertTrue(preUpdateEvent != nil) + #endif + } + } + func testUpdateEvent() throws { let dbQueue = try makeDatabaseQueue() try setupArtistDatabase(in: dbQueue) diff --git a/Tests/GRDBTests/TruncateOptimizationTests.swift b/Tests/GRDBTests/TruncateOptimizationTests.swift index 0a1261331..a3e8b152f 100644 --- a/Tests/GRDBTests/TruncateOptimizationTests.swift +++ b/Tests/GRDBTests/TruncateOptimizationTests.swift @@ -94,7 +94,7 @@ class TruncateOptimizationTests: GRDBTestCase { try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") - let deleteStatement = try db.makeUpdateStatement(sql: "DELETE FROM t") + let deleteStatement = try db.makeStatement(sql: "DELETE FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") @@ -140,7 +140,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP TABLE t") // compile... + let dropStatement = try db.makeStatement(sql: "DROP TABLE t") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.tableExists("t")) } @@ -153,7 +153,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP TABLE t") // compile... + let dropStatement = try db.makeStatement(sql: "DROP TABLE t") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.tableExists("t")) } @@ -188,7 +188,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE TEMPORARY TABLE t(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP TABLE t") // compile... + let dropStatement = try db.makeStatement(sql: "DROP TABLE t") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.tableExists("t")) } @@ -201,7 +201,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE TEMPORARY TABLE t(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP TABLE t") // compile... + let dropStatement = try db.makeStatement(sql: "DROP TABLE t") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.tableExists("t")) } @@ -236,7 +236,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP TABLE t") // compile... + let dropStatement = try db.makeStatement(sql: "DROP TABLE t") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.tableExists("t")) } @@ -249,7 +249,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP TABLE t") // compile... + let dropStatement = try db.makeStatement(sql: "DROP TABLE t") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.tableExists("t")) } @@ -287,7 +287,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE VIEW v AS SELECT * FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.viewExists("v")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP VIEW v") // compile... + let dropStatement = try db.makeStatement(sql: "DROP VIEW v") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.viewExists("v")) } @@ -301,7 +301,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE VIEW v AS SELECT * FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.viewExists("v")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP VIEW v") // compile... + let dropStatement = try db.makeStatement(sql: "DROP VIEW v") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.viewExists("v")) } @@ -339,7 +339,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.viewExists("v")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP VIEW v") // compile... + let dropStatement = try db.makeStatement(sql: "DROP VIEW v") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.viewExists("v")) } @@ -353,7 +353,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.viewExists("v")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP VIEW v") // compile... + let dropStatement = try db.makeStatement(sql: "DROP VIEW v") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.viewExists("v")) } @@ -389,7 +389,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE INDEX i ON t(a)") try db.execute(sql: "INSERT INTO t VALUES (1)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) - let dropStatement = try db.makeUpdateStatement(sql: "DROP INDEX i") // compile... + let dropStatement = try db.makeStatement(sql: "DROP INDEX i") // compile... try dropStatement.execute() // ... then execute try XCTAssertTrue(db.indexes(on: "t").isEmpty) } @@ -403,7 +403,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE INDEX i ON t(a)") try db.execute(sql: "INSERT INTO t VALUES (1)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) - let dropStatement = try db.makeUpdateStatement(sql: "DROP INDEX i") // compile... + let dropStatement = try db.makeStatement(sql: "DROP INDEX i") // compile... try dropStatement.execute() // ... then execute try XCTAssertTrue(db.indexes(on: "t").isEmpty) } @@ -439,7 +439,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE INDEX i ON t(a)") try db.execute(sql: "INSERT INTO t VALUES (1)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) - let dropStatement = try db.makeUpdateStatement(sql: "DROP INDEX i") // compile... + let dropStatement = try db.makeStatement(sql: "DROP INDEX i") // compile... try dropStatement.execute() // ... then execute try XCTAssertTrue(db.indexes(on: "t").isEmpty) } @@ -453,7 +453,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE INDEX i ON t(a)") try db.execute(sql: "INSERT INTO t VALUES (1)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) - let dropStatement = try db.makeUpdateStatement(sql: "DROP INDEX i") // compile... + let dropStatement = try db.makeStatement(sql: "DROP INDEX i") // compile... try dropStatement.execute() // ... then execute try XCTAssertTrue(db.indexes(on: "t").isEmpty) } @@ -488,7 +488,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP TRIGGER r") // compile... + let dropStatement = try db.makeStatement(sql: "DROP TRIGGER r") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.triggerExists("r")) } @@ -501,7 +501,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP TRIGGER r") // compile... + let dropStatement = try db.makeStatement(sql: "DROP TRIGGER r") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.triggerExists("r")) } @@ -536,7 +536,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP TRIGGER r") // compile... + let dropStatement = try db.makeStatement(sql: "DROP TRIGGER r") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.triggerExists("r")) } @@ -549,7 +549,7 @@ class TruncateOptimizationTests: GRDBTestCase { try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) - let dropStatement = try db.makeUpdateStatement(sql: "DROP TRIGGER r") // compile... + let dropStatement = try db.makeStatement(sql: "DROP TRIGGER r") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.triggerExists("r")) } diff --git a/Tests/GRDBTests/UpdateStatementTests.swift b/Tests/GRDBTests/UpdateStatementTests.swift index e7963ed58..401977207 100644 --- a/Tests/GRDBTests/UpdateStatementTests.swift +++ b/Tests/GRDBTests/UpdateStatementTests.swift @@ -20,10 +20,10 @@ class UpdateStatementTests : GRDBTestCase { func testTrailingSemicolonAndWhiteSpaceIsAcceptedAndOptional() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in - try db.makeUpdateStatement(sql: "INSERT INTO persons (name) VALUES ('Arthur');").execute() - try db.makeUpdateStatement(sql: "INSERT INTO persons (name) VALUES ('Barbara')\n \t").execute() - try db.makeUpdateStatement(sql: "INSERT INTO persons (name) VALUES ('Craig'); ; ;").execute() - try db.makeUpdateStatement(sql: "INSERT INTO persons (name) VALUES ('Daniel');\n \t").execute() + try db.makeStatement(sql: "INSERT INTO persons (name) VALUES ('Arthur');").execute() + try db.makeStatement(sql: "INSERT INTO persons (name) VALUES ('Barbara')\n \t").execute() + try db.makeStatement(sql: "INSERT INTO persons (name) VALUES ('Craig'); ; ;").execute() + try db.makeStatement(sql: "INSERT INTO persons (name) VALUES ('Daniel');\n \t").execute() return .commit } try dbQueue.inDatabase { db in @@ -35,8 +35,8 @@ class UpdateStatementTests : GRDBTestCase { func testStatementSQL() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - try XCTAssertEqual(db.makeUpdateStatement(sql: "INSERT INTO persons (name, age) VALUES ('Arthur', ?)").sql, "INSERT INTO persons (name, age) VALUES ('Arthur', ?)") - try XCTAssertEqual(db.makeUpdateStatement(sql: " INSERT INTO persons (name, age) VALUES ('Arthur', ?) ; ").sql, "INSERT INTO persons (name, age) VALUES ('Arthur', ?)") + try XCTAssertEqual(db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES ('Arthur', ?)").sql, "INSERT INTO persons (name, age) VALUES ('Arthur', ?)") + try XCTAssertEqual(db.makeStatement(sql: " INSERT INTO persons (name, age) VALUES ('Arthur', ?) ; ").sql, "INSERT INTO persons (name, age) VALUES ('Arthur', ?)") } } @@ -45,7 +45,7 @@ class UpdateStatementTests : GRDBTestCase { try dbQueue.inTransaction { db in - let statement = try db.makeUpdateStatement(sql: "INSERT INTO persons (name, age) VALUES (?, ?)") + let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (?, ?)") let persons: [[DatabaseValueConvertible?]] = [ ["Arthur", 41], ["Barbara", nil], @@ -72,7 +72,7 @@ class UpdateStatementTests : GRDBTestCase { try dbQueue.inTransaction { db in - let statement = try db.makeUpdateStatement(sql: "INSERT INTO persons (name, age) VALUES (?, ?)") + let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (?, ?)") let persons: [[DatabaseValueConvertible?]] = [ ["Arthur", 41], ["Barbara", nil], @@ -100,7 +100,7 @@ class UpdateStatementTests : GRDBTestCase { try dbQueue.inTransaction { db in - let statement = try db.makeUpdateStatement(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)") + let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)") let persons: [[String: DatabaseValueConvertible?]] = [ ["name": "Arthur", "age": 41], ["name": "Barbara", "age": nil], @@ -127,7 +127,7 @@ class UpdateStatementTests : GRDBTestCase { try dbQueue.inTransaction { db in - let statement = try db.makeUpdateStatement(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)") + let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)") let persons: [[String: DatabaseValueConvertible?]] = [ ["name": "Arthur", "age": 41], ["name": "Barbara", "age": nil], @@ -156,7 +156,7 @@ class UpdateStatementTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "SELECT 1") - let statement = try db.makeUpdateStatement(sql: "SELECT 1") + let statement = try db.makeStatement(sql: "SELECT 1") try statement.execute() } } @@ -170,7 +170,7 @@ class UpdateStatementTests : GRDBTestCase { return index }) try db.execute(sql: "SELECT seq() UNION ALL SELECT seq() UNION ALL SELECT seq()") - let statement = try db.makeUpdateStatement(sql: "SELECT seq() UNION ALL SELECT seq() UNION ALL SELECT seq()") + let statement = try db.makeStatement(sql: "SELECT seq() UNION ALL SELECT seq() UNION ALL SELECT seq()") try statement.execute() } XCTAssertEqual(index, 3 + 3) @@ -290,6 +290,18 @@ class UpdateStatementTests : GRDBTestCase { func testExecuteMultipleStatementWithTooManyArguments() throws { let dbQueue = try makeDatabaseQueue() + try dbQueue.inTransaction { db in + do { + try db.execute(sql: "", arguments: [1]) + XCTFail() + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_MISUSE) + XCTAssertEqual(error.message!, "wrong number of statement arguments: 1") + XCTAssertEqual(error.description, "SQLite error 21: wrong number of statement arguments: 1") + } + return .rollback + } + try dbQueue.inTransaction { db in do { try db.execute(sql: """ @@ -302,6 +314,37 @@ class UpdateStatementTests : GRDBTestCase { XCTAssertEqual(error.message!, "wrong number of statement arguments: 3") XCTAssertEqual(error.description, "SQLite error 21: wrong number of statement arguments: 3") } + + // Both statements were run + let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")! + XCTAssertEqual(count, 2) + + return .rollback + } + } + + func testExecuteMultipleStatementWithTooFewArguments() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inTransaction { db in + do { + try db.execute(sql: """ + INSERT INTO persons (name, age) VALUES ('Arthur', ?); + INSERT INTO persons (name, age) VALUES ('Arthur', ?); + """, arguments: [41]) + XCTFail() + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_MISUSE) + XCTAssertEqual(error.message!, "wrong number of statement arguments: 0") + XCTAssertEqual(error.description, """ + SQLite error 21: wrong number of statement arguments: 0 \ + - while executing `INSERT INTO persons (name, age) VALUES ('Arthur', ?)` + """) + } + + // First statement did run + let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")! + XCTAssertEqual(count, 1) + return .rollback } } @@ -310,7 +353,7 @@ class UpdateStatementTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - _ = try db.makeUpdateStatement(sql: "UPDATE blah SET id = 12") + _ = try db.makeStatement(sql: "UPDATE blah SET id = 12") XCTFail() } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) @@ -325,13 +368,20 @@ class UpdateStatementTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - _ = try db.makeUpdateStatement(sql: "UPDATE persons SET age = 1; UPDATE persons SET age = 2;") + _ = try db.makeStatement(sql: "UPDATE persons SET age = 1; UPDATE persons SET age = 2;") XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_MISUSE) - XCTAssertEqual(error.message!, "Multiple statements found. To execute multiple statements, use Database.execute(sql:) instead.") + XCTAssertEqual(error.message!, """ + Multiple statements found. To execute multiple statements, \ + use Database.execute(sql:) or Database.allStatements(sql:) instead. + """) XCTAssertEqual(error.sql!, "UPDATE persons SET age = 1; UPDATE persons SET age = 2;") - XCTAssertEqual(error.description, "SQLite error 21: Multiple statements found. To execute multiple statements, use Database.execute(sql:) instead. - while executing `UPDATE persons SET age = 1; UPDATE persons SET age = 2;`") + XCTAssertEqual(error.description, """ + SQLite error 21: Multiple statements found. To execute multiple statements, \ + use Database.execute(sql:) or Database.allStatements(sql:) instead. \ + - while executing `UPDATE persons SET age = 1; UPDATE persons SET age = 2;` + """) } } } @@ -340,13 +390,20 @@ class UpdateStatementTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - _ = try db.makeUpdateStatement(sql: "UPDATE persons SET age = 1;x") + _ = try db.makeStatement(sql: "UPDATE persons SET age = 1;x") XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_MISUSE) - XCTAssertEqual(error.message!, "Multiple statements found. To execute multiple statements, use Database.execute(sql:) instead.") + XCTAssertEqual(error.message!, """ + Multiple statements found. To execute multiple statements, \ + use Database.execute(sql:) or Database.allStatements(sql:) instead. + """) XCTAssertEqual(error.sql!, "UPDATE persons SET age = 1;x") - XCTAssertEqual(error.description, "SQLite error 21: Multiple statements found. To execute multiple statements, use Database.execute(sql:) instead. - while executing `UPDATE persons SET age = 1;x`") + XCTAssertEqual(error.description, """ + SQLite error 21: Multiple statements found. To execute multiple statements, \ + use Database.execute(sql:) or Database.allStatements(sql:) instead. \ + - while executing `UPDATE persons SET age = 1;x` + """) } } } diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index 22c4dc918..41f98be64 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -14,7 +14,7 @@ class ValueObservationPrintTests: GRDBTestCase { private func region(sql: String, in dbReader: DatabaseReader) throws -> String { try dbReader.read { db in try db - .makeSelectStatement(sql: sql) + .makeStatement(sql: sql) .databaseRegion .description } diff --git a/Tests/Performance/GRDBPerformance/Generation.swift b/Tests/Performance/GRDBPerformance/Generation.swift index 128bce917..a9d61d5c2 100644 --- a/Tests/Performance/GRDBPerformance/Generation.swift +++ b/Tests/Performance/GRDBPerformance/Generation.swift @@ -18,7 +18,7 @@ func generateSQLiteDatabaseIfMissing(at url: URL, insertedRowCount: Int) throws } try db.execute(sql: "CREATE TABLE item (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)") - let statement = try! db.makeUpdateStatement(sql: "INSERT INTO item (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (?,?,?,?,?,?,?,?,?,?)") + let statement = try! db.makeStatement(sql: "INSERT INTO item (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (?,?,?,?,?,?,?,?,?,?)") for i in 0.. UpdateStatement { - try db.makeUpdateStatement(literal: """ + static func optimizedInsertStatement(_ db: Database) throws -> Statement { + try db.makeStatement(literal: """ INSERT INTO \(self) ( \(CodingKeys.i0), \(CodingKeys.i1), @@ -33,7 +33,7 @@ private struct Item: Codable, FetchableRecord, PersistableRecord { """) } - func insert(with statement: UpdateStatement) throws { + func insert(with statement: Statement) throws { statement.setUncheckedArguments([ i0, i1, diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift index e3454b23b..8fa998997 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift @@ -211,7 +211,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { } func _insertPositionalValues(_ db: Database) throws { - let statement = try db.makeUpdateStatement(sql: "INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (?,?,?,?,?,?,?,?,?,?)") + let statement = try db.makeStatement(sql: "INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (?,?,?,?,?,?,?,?,?,?)") for i in 0..