diff --git a/CHANGELOG.md b/CHANGELOG.md index 783f6a3ce..7c9f40222 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. +#### 6.x Releases + +- `6.0.0` Betas - [6.0.0-beta](#600-beta) + #### 5.x Releases - `5.26.x` Releases - [5.26.0](#5260) @@ -93,6 +97,61 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## 6.0.0-beta + +Released August 21, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.26.0...v6.0.0-beta) + +### New + +Upgrading your app can bring improvements: check [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) for some suggestions. + +- :star: Support for [`UPSERT`](https://www.sqlite.org/lang_UPSERT.html): `player.upsert(db)`, etc. See [Persistence Methods](README.md#persistence-methods). + +- :star: Support for the [`RETURNING` clause](https://www.sqlite.org/lang_returning.html): `player.insertAndFetch(db)`, `Player.deleteAndFetchAll(db)`, etc. See [Persistence Methods and the `RETURNING` clause](README.md#persistence-methods-and-the-returning-clause). + +- :star: [Persistence Callbacks](README.md#persistence-callbacks) allow record types to customize persistence methods: `didInsert`, `willSave`, etc. + +- :star: Better support for unexpected database values. Where GRDB 5 would crash during encoding and decoding database values, GRDB 6 has learned to throw errors instead. Record protocols throw decoding and encoding errors, and value requests throw errors on invalid inputs. + +- Request protocols and cursors now define primary associated types, enabled by [SE-0346](https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md). + +- All persistence methods now accept an explicit conflict policy: `player.insert(db, onConflict: .replace)`, etc. + +- You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`. + +- `ValueObservation.map` now accepts a throwing closure argument. + +### Documentation Updates + +- :star: **[Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)**: suggestions for improving your applications, and guidance for handling the breaking changes. +- The [Persistence Methods](README.md#persistence-methods) chapter introduces the `upsert` method. +- The [Persistence Methods and the `RETURNING` clause](README.md#persistence-methods-and-the-returning-clause) chapter introduces persistence methods that fetch inserted, updated and deleted values. +- The [Persistence Callbacks](README.md#persistence-callbacks) chapter introduces the callback invoked from persistence methods, such as `didInsert`, `willSave`, etc. +- The [DatabaseRegionObservation](README.md#databaseregionobservation) chapter was updated for the new `DatabaseRegionObservation.start` method. +- The [Transaction Hook](README.md#transaction-hook) chapter describes the new `Database.afterNextTransaction(onCommit:onRollback:)` method. +- The [Value Queries](README.md#value-queries) chapter explains how to distinguish a request that returns no value from a request that fetches a NULL value. + +### Breaking Changes + +- Removed deprecated methods +- :star: Bumped requirements: + - Swift 5.7+ and Xcode 14+ are required. + - iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ / SQLite 3.19.3+ are required. +- :star: Record protocols were refactored: + - The `FetchableRecord.init(row:)` initializer can now throw errors. + - The `EncodableRecord.encode(to:)` method can now throw errors. + - Record types can no longer override persistence methods. You use [Persistence Callbacks](README.md#persistence-callbacks) instead. +- Various breaking changes: + - The in-memory `DatabaseQueue()` initializer can now throw errors. + - The `selectID()` method is replaced with `selectPrimaryKey(as:)`. + - `Cursor.isEmpty` is now a throwing property, instead of a method. + - The `Record.copy()` method was removed, without replacement. + - The `DerivableRequest.limit(_:offset_:)` method was removed, without replacement. + - `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable. + - The `DatabaseRegionObservation.extent` property was removed. + - The `statement` property of database cursors was replaced with read-only properties such as `sql` or `columnNames`. + - The `Database.afterNextTransactionCommit(_:)` method was renamed `Database.afterNextTransaction(onCommit:onRollback:)`, and is now able to report rollbacks as well as commits. + ## 5.26.0 Released July 9, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.25.0...v5.26.0) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 5dd37e5ff..f42bd7ced 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -712,9 +712,9 @@ struct Author: TableRecord { } ``` -> :point_up: **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns. +> **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns. > -> :warning: **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either. +> **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either. Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another. @@ -1210,7 +1210,7 @@ In the description of the [joining methods] above, we have seen that you need to In this chapter, we take the reversed perspective. We list various shapes of decoded record types. When you find the type you want, you'll know the joining method you need. -> :point_up: **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level apis described in [Decoding a Joined Request with FetchableRecord]. +> **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level apis described in [Decoding a Joined Request with FetchableRecord]. - [`including(required:)`] @@ -1435,7 +1435,7 @@ struct BookInfo: FetchableRecord, Decodable { let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request) ``` -> :warning: **Warning**: you can not currently chain a required association behind an optional association: +> **Warning**: you can not currently chain a required association behind an optional association: > > ```swift > // Not implemented @@ -1751,7 +1751,7 @@ Associations support more refinements: .fetchAll(db) ``` -> :warning: **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc. +> **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc. ## Table Aliases @@ -1823,7 +1823,7 @@ let request = Book.aliased(bookAlias) .filter(sql: "b.publishDate >= a.deathDate") ``` -> :point_up: **Note**: avoid reusing table aliases between several tables or requests, because you will get a fatal error: +> **Note**: avoid reusing table aliases between several tables or requests, because you will get a fatal error: > > ```swift > // Fatal error: A TableAlias most not be used to refer to multiple tables @@ -1832,7 +1832,7 @@ let request = Book.aliased(bookAlias) > let people = Person.aliased(alias)... > ``` > -> :point_up: **Note**: you can't use the `including(all:)` method and use table aliases to filter the associated records on other records: +> **Note**: you can't use the `including(all:)` method and use table aliases to filter the associated records on other records: > > ```swift > // NOT IMPLEMENTED: loading all authors along with their posthumous books @@ -1899,7 +1899,7 @@ For example, we can start by defining base requests as extensions to the [Deriva ```swift // Author requests -extension DerivableRequest where RowDecoder == Author { +extension DerivableRequest { /// Filters authors by country func filter(country: String) -> Self { filter(Column("country") == country) @@ -1907,7 +1907,7 @@ extension DerivableRequest where RowDecoder == Author { } // Book requests -extension DerivableRequest where RowDecoder == Book { +extension DerivableRequest { /// Filters books by author country func filter(authorCountry: String) -> Self { joining(required: Book.author.filter(country: country)) @@ -2165,8 +2165,8 @@ struct BookInfo: FetchableRecord { var country: Country? var coverImage: CoverImage? - init(row: Row) { - book = Book(row: row) + init(row: Row) throws { + book = try Book(row: row) author = row["author"] country = row["country"] coverImage = row["coverImage"] @@ -2200,8 +2200,8 @@ struct AuthorInfo: FetchableRecord { var author: Author var books: [Book] - init(row: Row) { - author = Author(row: row) + init(row: Row) throws { + author = try Author(row: row) books = row["books"] } } @@ -2843,7 +2843,7 @@ let request = Book.all().filter(country: "ES") Those methods are defined on extensions to the `DerivableRequest` protocol: ```swift -extension DerivableRequest where RowDecoder == Author { +extension DerivableRequest { func filter(country: String) -> Self { filter(Column("country") == country) } @@ -2853,7 +2853,7 @@ extension DerivableRequest where RowDecoder == Author { } } -extension DerivableRequest where RowDecoder == Book { +extension DerivableRequest { func filter(country: String) -> Self { joining(required: Book.author.filter(country: country)) } diff --git a/Documentation/CommonTableExpressions.md b/Documentation/CommonTableExpressions.md index 75f17bdc2..6a025315f 100644 --- a/Documentation/CommonTableExpressions.md +++ b/Documentation/CommonTableExpressions.md @@ -16,7 +16,7 @@ In this guide, you will learn how to: - [Fetch Values From Common Table Expressions] - Join CTEs with [Associations to Common Table Expressions] -> :point_up: **Note**: most code examples will be trivial, and not very "useful". This is because the goal of this guide is to stay focused on the GRDB support for CTEs. Rich setup would just be distracting. So bring your own good ideas with you! +> **Note**: most code examples will be trivial, and not very "useful". This is because the goal of this guide is to stay focused on the GRDB support for CTEs. Rich setup would just be distracting. So bring your own good ideas with you! ## Define Common Table Expressions @@ -82,7 +82,7 @@ let counterCTE = CommonTableExpression( """) ``` -> :point_up: **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs. +> **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs. ## Embed Common Table Expressions in Requests @@ -126,13 +126,13 @@ let request = Player .filter(Column("name") == playerNameCTE.all()) ``` -> :point_up: **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request. +> **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request. > -> :point_up: **Note**: the `with(_:)` method can be called at any time, as all request methods: `Player.with(...).filter(...).with(...)`. +> **Note**: the `with(_:)` method can be called at any time, as all request methods: `Player.with(...).filter(...).with(...)`. > -> :point_up: **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it. +> **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it. > -> :point_up: **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM `, not to be mismatched with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests: +> **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM `, not to be mismatched with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests: > > ```swift > cte.all().select(...).filter(...).group(...).order(...) @@ -234,7 +234,7 @@ Parent.including(optional: childAssociation) Parent.including(required: childAssociation) ``` -> :point_up: **Note**: common table expressions currently only define "to-one" associations, so the `including(all:)` joining method is unavailable. +> **Note**: common table expressions currently only define "to-one" associations, so the `including(all:)` joining method is unavailable. CTE associations are generally built with the `association(to:on:)` method, which needs: diff --git a/Documentation/Concurrency.md b/Documentation/Concurrency.md index dbf0cf4a2..2d0b9c02d 100644 --- a/Documentation/Concurrency.md +++ b/Documentation/Concurrency.md @@ -506,7 +506,7 @@ try snapshot2.read { db in } ``` -> :point_up: **Note**: snapshots currently serialize all database accesses. In the future, snapshots may allow concurrent reads. +> **Note**: snapshots currently serialize all database accesses. In the future, snapshots may allow concurrent reads. [^1]: This immutable view of the database is called [snapshot isolation](https://www.sqlite.org/isolation.html). diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.pbxproj index cc0e5702c..8e7841eab 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.pbxproj +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.pbxproj @@ -26,7 +26,6 @@ 567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; }; 56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */; }; 56F8A13527359A5A0011ACBE /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56F8A13427359A5A0011ACBE /* GRDB */; }; - 78E2F9E6261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78E2F9E5261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -37,13 +36,6 @@ remoteGlobalIDString = 567C3E152520B6DE0011F6E9; remoteInfo = GRDBAsyncDemo; }; - 78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 567C3E152520B6DE0011F6E9; - remoteInfo = GRDBAsyncDemo; - }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -82,9 +74,6 @@ 567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = ""; }; 56F8A12E27359A350011ACBE /* GRDB.swift */ = {isa = PBXFileReference; lastKnownFileType = folder; name = GRDB.swift; path = ../../..; sourceTree = ""; }; - 78E2F9E3261EEC22005D1F7F /* GRDBAsyncDemoUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBAsyncDemoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 78E2F9E5261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBAsyncDemoUITests.swift; sourceTree = ""; }; - 78E2F9E7261EEC22005D1F7F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -104,13 +93,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 78E2F9E0261EEC22005D1F7F /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ @@ -140,7 +122,6 @@ children = ( 567C3E182520B6DE0011F6E9 /* GRDBAsyncDemo */, 56026C9925B8A7D000D1DF3F /* GRDBAsyncDemoTests */, - 78E2F9E4261EEC22005D1F7F /* GRDBAsyncDemoUITests */, 567C3E172520B6DE0011F6E9 /* Products */, 567C3E4D2520B70E0011F6E9 /* Frameworks */, 56F8A12E27359A350011ACBE /* GRDB.swift */, @@ -152,7 +133,6 @@ children = ( 567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */, 56026C9825B8A7D000D1DF3F /* GRDBAsyncDemoTests.xctest */, - 78E2F9E3261EEC22005D1F7F /* GRDBAsyncDemoUITests.xctest */, ); name = Products; sourceTree = ""; @@ -200,15 +180,6 @@ path = Views; sourceTree = ""; }; - 78E2F9E4261EEC22005D1F7F /* GRDBAsyncDemoUITests */ = { - isa = PBXGroup; - children = ( - 78E2F9E5261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift */, - 78E2F9E7261EEC22005D1F7F /* Info.plist */, - ); - path = GRDBAsyncDemoUITests; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -253,24 +224,6 @@ productReference = 567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */; productType = "com.apple.product-type.application"; }; - 78E2F9E2261EEC22005D1F7F /* GRDBAsyncDemoUITests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoUITests" */; - buildPhases = ( - 78E2F9DF261EEC22005D1F7F /* Sources */, - 78E2F9E0261EEC22005D1F7F /* Frameworks */, - 78E2F9E1261EEC22005D1F7F /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */, - ); - name = GRDBAsyncDemoUITests; - productName = GRDBAsyncDemoUITests; - productReference = 78E2F9E3261EEC22005D1F7F /* GRDBAsyncDemoUITests.xctest */; - productType = "com.apple.product-type.bundle.ui-testing"; - }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -287,10 +240,6 @@ 567C3E152520B6DE0011F6E9 = { CreatedOnToolsVersion = 12.0; }; - 78E2F9E2261EEC22005D1F7F = { - CreatedOnToolsVersion = 12.5; - TestTargetID = 567C3E152520B6DE0011F6E9; - }; }; }; buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBAsyncDemo" */; @@ -311,7 +260,6 @@ targets = ( 567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */, 56026C9725B8A7D000D1DF3F /* GRDBAsyncDemoTests */, - 78E2F9E2261EEC22005D1F7F /* GRDBAsyncDemoUITests */, ); }; /* End PBXProject section */ @@ -335,13 +283,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 78E2F9E1261EEC22005D1F7F /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -372,14 +313,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 78E2F9DF261EEC22005D1F7F /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 78E2F9E6261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ @@ -392,11 +325,6 @@ isa = PBXTargetDependency; productRef = 56F8A13027359A540011ACBE /* GRDB */; }; - 78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */; - targetProxy = 78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */; - }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ @@ -617,44 +545,6 @@ }; name = Release; }; - 78E2F9EA261EEC22005D1F7F /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = ""; - INFOPLIST_FILE = GRDBAsyncDemoUITests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBAsyncDemoUITests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_TARGET_NAME = GRDBAsyncDemo; - }; - name = Debug; - }; - 78E2F9EB261EEC22005D1F7F /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = ""; - INFOPLIST_FILE = GRDBAsyncDemoUITests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBAsyncDemoUITests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_TARGET_NAME = GRDBAsyncDemo; - }; - name = Release; - }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -685,15 +575,6 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoUITests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 78E2F9EA261EEC22005D1F7F /* Debug */, - 78E2F9EB261EEC22005D1F7F /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; /* End XCConfigurationList section */ /* Begin XCRemoteSwiftPackageReference section */ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme index b229953c3..42aed0aa2 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme @@ -1,6 +1,6 @@ - - - - struct AppDatabase { /// Creates an `AppDatabase`, and make sure the database schema is ready. - init(_ dbWriter: DatabaseWriter) throws { + init(_ dbWriter: any DatabaseWriter) throws { self.dbWriter = dbWriter try migrator.migrate(dbWriter) } @@ -18,7 +18,7 @@ struct AppDatabase { /// can use a fast in-memory `DatabaseQueue`. /// /// See - private let dbWriter: DatabaseWriter + private let dbWriter: any DatabaseWriter /// The DatabaseMigrator that defines the database schema. /// diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift index e5336a831..b9a2cc1f7 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift @@ -59,7 +59,7 @@ extension AppDatabase { static func empty() -> AppDatabase { // Connect to an in-memory database // See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections - let dbQueue = DatabaseQueue() + let dbQueue = try! DatabaseQueue() return try! AppDatabase(dbQueue) } diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift index 9bd337573..8513cd480 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift @@ -60,8 +60,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { } /// Updates a player id after it has been inserted in the database. - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -71,7 +71,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { /// /// See /// See -extension DerivableRequest where RowDecoder == Player { +extension DerivableRequest { /// A request of players ordered by name. /// /// For example: diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift index 64fb529f6..29de329fe 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift @@ -5,7 +5,7 @@ import GRDB class AppDatabaseTests: XCTestCase { func test_database_schema() throws { // Given an empty database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() // When we instantiate an AppDatabase _ = try AppDatabase(dbQueue) @@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase { func test_savePlayer_inserts() async throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) // When we save a new player @@ -29,12 +29,13 @@ class AppDatabaseTests: XCTestCase { try await appDatabase.savePlayer(&player) // Then the player exists in the database - try XCTAssertTrue(dbQueue.read(player.exists)) + let playerExists = try await dbQueue.read { [player] in try player.exists($0) } + XCTAssertTrue(playerExists) } func test_savePlayer_updates() async throws { // Given a players database that contains a player - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) var player = try await dbQueue.write { db in try Player(id: nil, name: "Arthur", score: 100).inserted(db) @@ -54,14 +55,14 @@ class AppDatabaseTests: XCTestCase { func test_deletePlayers() async throws { // Given a players database that contains four players - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) let playerIds: [Int64] = try await dbQueue.write { db in _ = try Player(id: nil, name: "Arthur", score: 100).inserted(db) _ = try Player(id: nil, name: "Barbara", score: 200).inserted(db) _ = try Player(id: nil, name: "Craig", score: 150).inserted(db) _ = try Player(id: nil, name: "David", score: 120).inserted(db) - return try Player.selectID().fetchAll(db) + return try Player.selectPrimaryKey().fetchAll(db) } // When we delete two players @@ -76,12 +77,13 @@ class AppDatabaseTests: XCTestCase { } // Then the database still contains two players - try XCTAssertEqual(dbQueue.read(Player.fetchCount), 2) + let count = try await dbQueue.read { try Player.fetchCount($0) } + XCTAssertEqual(count, 2) } func test_deleteAllPlayers() async throws { // Given a players database that contains players - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) try await dbQueue.write { db in _ = try Player(id: nil, name: "Arthur", score: 100).inserted(db) @@ -94,24 +96,26 @@ class AppDatabaseTests: XCTestCase { try await appDatabase.deleteAllPlayers() // Then the database does not contain any player - try XCTAssertEqual(dbQueue.read(Player.fetchCount), 0) + let count = try await dbQueue.read { try Player.fetchCount($0) } + XCTAssertEqual(count, 0) } func test_refreshPlayers_populates_an_empty_database() async throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) // When we refresh players try await appDatabase.refreshPlayers() // Then the database is not empty - try XCTAssert(dbQueue.read(Player.fetchCount) > 0) + let count = try await dbQueue.read { try Player.fetchCount($0) } + XCTAssert(count > 0) } func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) // When we create random players @@ -123,7 +127,7 @@ class AppDatabaseTests: XCTestCase { func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws { // Given a players database that contains one player - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) var player = Player(id: nil, name: "Arthur", score: 100) try dbQueue.write { db in diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerRequestTests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerRequestTests.swift index 79e233686..914a24173 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerRequestTests.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerRequestTests.swift @@ -5,7 +5,7 @@ import GRDB class PlayerRequestTests: XCTestCase { func test_PlayerRequest_byName_fetches_well_ordered_players() throws { // Given a players database that contains two players - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 1000) @@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase { func test_PlayerRequest_byScore_fetches_well_ordered_players() throws { // Given a players database that contains two players - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 1000) diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerTests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerTests.swift index 224575ec7..3b9df1506 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerTests.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerTests.swift @@ -8,7 +8,7 @@ class PlayerTests: XCTestCase { func testInsert() throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) // When we insert a player @@ -23,7 +23,7 @@ class PlayerTests: XCTestCase { func testRoundtrip() throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) // When we insert a player and fetch the player with the same id @@ -42,7 +42,7 @@ class PlayerTests: XCTestCase { func testOrderedByScore() throws { // Given a players database that contains players with distinct scores - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) @@ -64,7 +64,7 @@ class PlayerTests: XCTestCase { func testOrderedByScoreSortsIdenticalScoresByName() throws { // Given a players database that contains players with common scores - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) @@ -86,7 +86,7 @@ class PlayerTests: XCTestCase { func testOrderedByName() throws { // Given a players database that contains players with distinct names - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoUITests/GRDBAsyncDemoUITests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoUITests/GRDBAsyncDemoUITests.swift deleted file mode 100644 index 772ef694b..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoUITests/GRDBAsyncDemoUITests.swift +++ /dev/null @@ -1,81 +0,0 @@ -// -// GRDBAsyncDemoUITests.swift -// GRDBAsyncDemoUITests -// -// Created by Peter Steinberger on 08.04.21. -// - -import XCTest - -class GRDBAsyncDemoUITests: XCTestCase { - - override func setUpWithError() throws { - // In UI tests it is usually best to stop immediately when a failure occurs. - continueAfterFailure = false - } - - override func tearDownWithError() throws { - } - - func runApp() -> XCUIApplication { - // UI tests must launch the application that they test. - let app = XCUIApplication() - // We enforce a fresh database to ensure 8 random players. - app.launchArguments = ["-reset", "-fixedTestData"] - app.launch() - return app - } - - // This test, introduced in 481f6e93, tests the @Query fix added in - // 68874412. The fix expresses itself when a view defines an @Query - // property that is replaced in the view initializer, as in 481f6e93. - // - // It happens that I did not find that this particular view setup was suited - // for a demo app. The demo has to find a delicate balance, not too trivial, - // but without gratuitous complexity. - // - // I simplified the demo app in a5ffc52d, and we no longer have any view - // that defines an @Query property which is replaced in the view - // initializer. This means that this test no longer checks against - // 68874412 regressions! - // - // Whenever the @Query property wrapper ships with GRDB itself, make sure - // we test for those regressions! - func testInitialSortingIsByScore() throws { - let app = runApp() - - let getFirstCell = { () -> XCUIElement in - app.tables.element(boundBy: 0).cells.element(boundBy: 0) - } - - // Given default sorting, Henriette must be on top - XCTAssertEqual(getFirstCell().label, "Craig, 8 points") - - // Reverse sorting will bring Arthur on top (sort by name) - app.buttons["Score"].tap() - XCTAssertEqual(getFirstCell().label, "Arthur, 5 points") - } - - func testListAndAddPlayer() throws { - let app = runApp() - - // Ensure we have 8 players visible - XCTAssert(app.tables.cells.count == 8) - - // add a player - app.buttons["New Player"].tap() - - let playerNameField = app.textFields["Player Name"] - playerNameField.tap() - playerNameField.typeText("Tim Apple") - - app.buttons["Save"].tap() - - // This is suboptimal, but we need to wait for the animation to finish - // A better way could be to disable animations globally, - // and/or a hook to detect when the async fetch completes. - sleep(2) - - XCTAssert(app.tables.cells.count == 9) - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoUITests/Info.plist b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoUITests/Info.plist deleted file mode 100644 index 64d65ca49..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoUITests/Info.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - $(PRODUCT_BUNDLE_PACKAGE_TYPE) - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - - diff --git a/Documentation/DemoApps/GRDBAsyncDemo/README.md b/Documentation/DemoApps/GRDBAsyncDemo/README.md index fbbaa7d4d..8dbed0e83 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/README.md +++ b/Documentation/DemoApps/GRDBAsyncDemo/README.md @@ -7,7 +7,7 @@ Async/Await + SwiftUI Demo Application **Requirements**: iOS 15.0+ / Xcode 13.1+ -> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration. +> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration. The topics covered in this demo are: diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj index dec7b276c..ccdf36191 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj @@ -26,7 +26,6 @@ 567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; }; 56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */; }; 56F8A1202735989D0011ACBE /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56F8A11F2735989D0011ACBE /* GRDB */; }; - 78E2F9E6261EEC22005D1F7F /* GRDBCombineDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -37,13 +36,6 @@ remoteGlobalIDString = 567C3E152520B6DE0011F6E9; remoteInfo = GRDBCombineDemo; }; - 78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 567C3E152520B6DE0011F6E9; - remoteInfo = GRDBCombineDemo; - }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -82,9 +74,6 @@ 567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = ""; }; 56F8A11C2735988F0011ACBE /* GRDB.swift */ = {isa = PBXFileReference; lastKnownFileType = folder; name = GRDB.swift; path = ../../..; sourceTree = ""; }; - 78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCombineDemoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoUITests.swift; sourceTree = ""; }; - 78E2F9E7261EEC22005D1F7F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -104,13 +93,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 78E2F9E0261EEC22005D1F7F /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ @@ -140,7 +122,6 @@ children = ( 567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */, 56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */, - 78E2F9E4261EEC22005D1F7F /* GRDBCombineDemoUITests */, 567C3E172520B6DE0011F6E9 /* Products */, 567C3E4D2520B70E0011F6E9 /* Frameworks */, 56F8A11C2735988F0011ACBE /* GRDB.swift */, @@ -152,7 +133,6 @@ children = ( 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */, 56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */, - 78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */, ); name = Products; sourceTree = ""; @@ -200,15 +180,6 @@ path = Views; sourceTree = ""; }; - 78E2F9E4261EEC22005D1F7F /* GRDBCombineDemoUITests */ = { - isa = PBXGroup; - children = ( - 78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */, - 78E2F9E7261EEC22005D1F7F /* Info.plist */, - ); - path = GRDBCombineDemoUITests; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -253,24 +224,6 @@ productReference = 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */; productType = "com.apple.product-type.application"; }; - 78E2F9E2261EEC22005D1F7F /* GRDBCombineDemoUITests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoUITests" */; - buildPhases = ( - 78E2F9DF261EEC22005D1F7F /* Sources */, - 78E2F9E0261EEC22005D1F7F /* Frameworks */, - 78E2F9E1261EEC22005D1F7F /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */, - ); - name = GRDBCombineDemoUITests; - productName = GRDBCombineDemoUITests; - productReference = 78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */; - productType = "com.apple.product-type.bundle.ui-testing"; - }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -287,10 +240,6 @@ 567C3E152520B6DE0011F6E9 = { CreatedOnToolsVersion = 12.0; }; - 78E2F9E2261EEC22005D1F7F = { - CreatedOnToolsVersion = 12.5; - TestTargetID = 567C3E152520B6DE0011F6E9; - }; }; }; buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */; @@ -311,7 +260,6 @@ targets = ( 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */, 56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */, - 78E2F9E2261EEC22005D1F7F /* GRDBCombineDemoUITests */, ); }; /* End PBXProject section */ @@ -335,13 +283,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 78E2F9E1261EEC22005D1F7F /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -372,14 +313,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 78E2F9DF261EEC22005D1F7F /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 78E2F9E6261EEC22005D1F7F /* GRDBCombineDemoUITests.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ @@ -392,11 +325,6 @@ isa = PBXTargetDependency; productRef = 56F8A11D273598960011ACBE /* GRDB */; }; - 78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */; - targetProxy = 78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */; - }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ @@ -615,44 +543,6 @@ }; name = Release; }; - 78E2F9EA261EEC22005D1F7F /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = ""; - INFOPLIST_FILE = GRDBCombineDemoUITests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBCombineDemoUITests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_TARGET_NAME = GRDBCombineDemo; - }; - name = Debug; - }; - 78E2F9EB261EEC22005D1F7F /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = ""; - INFOPLIST_FILE = GRDBCombineDemoUITests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBCombineDemoUITests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_TARGET_NAME = GRDBCombineDemo; - }; - name = Release; - }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -683,15 +573,6 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoUITests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 78E2F9EA261EEC22005D1F7F /* Debug */, - 78E2F9EB261EEC22005D1F7F /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; /* End XCConfigurationList section */ /* Begin XCRemoteSwiftPackageReference section */ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme index 5a7922e7c..6eadb0a3a 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme @@ -1,6 +1,6 @@ - - - - struct AppDatabase { /// Creates an `AppDatabase`, and make sure the database schema is ready. - init(_ dbWriter: DatabaseWriter) throws { + init(_ dbWriter: any DatabaseWriter) throws { self.dbWriter = dbWriter try migrator.migrate(dbWriter) } @@ -19,7 +19,7 @@ struct AppDatabase { /// can use a fast in-memory `DatabaseQueue`. /// /// See - private let dbWriter: DatabaseWriter + private let dbWriter: any DatabaseWriter /// The DatabaseMigrator that defines the database schema. /// diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift index e5336a831..b9a2cc1f7 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift @@ -59,7 +59,7 @@ extension AppDatabase { static func empty() -> AppDatabase { // Connect to an in-memory database // See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections - let dbQueue = DatabaseQueue() + let dbQueue = try! DatabaseQueue() return try! AppDatabase(dbQueue) } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift index 9bd337573..8513cd480 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift @@ -60,8 +60,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { } /// Updates a player id after it has been inserted in the database. - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -71,7 +71,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { /// /// See /// See -extension DerivableRequest where RowDecoder == Player { +extension DerivableRequest { /// A request of players ordered by name. /// /// For example: diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift index 78d21fb12..b1f82c589 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift @@ -5,7 +5,7 @@ import GRDB class AppDatabaseTests: XCTestCase { func test_database_schema() throws { // Given an empty database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() // When we instantiate an AppDatabase _ = try AppDatabase(dbQueue) @@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase { func test_savePlayer_inserts() throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) // When we save a new player @@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase { func test_savePlayer_updates() throws { // Given a players database that contains a player - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) var player = Player(id: nil, name: "Arthur", score: 100) try dbQueue.write { db in @@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase { func test_deletePlayers() throws { // Given a players database that contains four players - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 200) @@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase { func test_deleteAllPlayers() throws { // Given a players database that contains players - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 200) @@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase { func test_refreshPlayers_populates_an_empty_database() throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) // When we refresh players @@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase { func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) // When we create random players @@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase { func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws { // Given a players database that contains one player - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) var player = Player(id: nil, name: "Arthur", score: 100) try dbQueue.write { db in diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerRequestTests.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerRequestTests.swift index e0e7f23f6..403d325ae 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerRequestTests.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerRequestTests.swift @@ -5,7 +5,7 @@ import GRDB class PlayerRequestTests: XCTestCase { func test_PlayerRequest_byName_fetches_well_ordered_players() throws { // Given a players database that contains two players - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 1000) @@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase { func test_PlayerRequest_byScore_fetches_well_ordered_players() throws { // Given a players database that contains two players - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 1000) diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift index 44b25d383..bb732c60f 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift @@ -8,7 +8,7 @@ class PlayerTests: XCTestCase { func testInsert() throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) // When we insert a player @@ -23,7 +23,7 @@ class PlayerTests: XCTestCase { func testRoundtrip() throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) // When we insert a player and fetch the player with the same id @@ -42,7 +42,7 @@ class PlayerTests: XCTestCase { func testOrderedByScore() throws { // Given a players database that contains players with distinct scores - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) @@ -64,7 +64,7 @@ class PlayerTests: XCTestCase { func testOrderedByScoreSortsIdenticalScoresByName() throws { // Given a players database that contains players with common scores - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) @@ -86,7 +86,7 @@ class PlayerTests: XCTestCase { func testOrderedByName() throws { // Given a players database that contains players with distinct names - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoUITests/GRDBCombineDemoUITests.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoUITests/GRDBCombineDemoUITests.swift deleted file mode 100644 index 0a6f29dd8..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoUITests/GRDBCombineDemoUITests.swift +++ /dev/null @@ -1,81 +0,0 @@ -// -// GRDBCombineDemoUITests.swift -// GRDBCombineDemoUITests -// -// Created by Peter Steinberger on 08.04.21. -// - -import XCTest - -class GRDBCombineDemoUITests: XCTestCase { - - override func setUpWithError() throws { - // In UI tests it is usually best to stop immediately when a failure occurs. - continueAfterFailure = false - } - - override func tearDownWithError() throws { - } - - func runApp() -> XCUIApplication { - // UI tests must launch the application that they test. - let app = XCUIApplication() - // We enforce a fresh database to ensure 8 random players. - app.launchArguments = ["-reset", "-fixedTestData"] - app.launch() - return app - } - - // This test, introduced in 481f6e93, tests the @Query fix added in - // 68874412. The fix expresses itself when a view defines an @Query - // property that is replaced in the view initializer, as in 481f6e93. - // - // It happens that I did not find that this particular view setup was suited - // for a demo app. The demo has to find a delicate balance, not too trivial, - // but without gratuitous complexity. - // - // I simplified the demo app in a5ffc52d, and we no longer have any view - // that defines an @Query property which is replaced in the view - // initializer. This means that this test no longer checks against - // 68874412 regressions! - // - // Whenever the @Query property wrapper ships with GRDB itself, make sure - // we test for those regressions! - func testInitialSortingIsByScore() throws { - let app = runApp() - - let getFirstCell = { () -> XCUIElement in - app.tables.element(boundBy: 0).cells.element(boundBy: 0) - } - - // Given default sorting, Henriette must be on top - XCTAssertEqual(getFirstCell().label, "Craig, 8 points") - - // Reverse sorting will bring Arthur on top (sort by name) - app.buttons["Score"].tap() - XCTAssertEqual(getFirstCell().label, "Arthur, 5 points") - } - - func testListAndAddPlayer() throws { - let app = runApp() - - // Ensure we have 8 players visible - XCTAssert(app.tables.cells.count == 8) - - // add a player - app.buttons["New Player"].tap() - - let playerNameField = app.textFields["Player Name"] - playerNameField.tap() - playerNameField.typeText("Tim Apple") - - app.buttons["Save"].tap() - - // This is suboptimal, but we need to wait for the animation to finish - // A better way could be to disable animations globally, - // and/or a hook to detect when the async fetch completes. - sleep(2) - - XCTAssert(app.tables.cells.count == 9) - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoUITests/Info.plist b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoUITests/Info.plist deleted file mode 100644 index 64d65ca49..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoUITests/Info.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - $(PRODUCT_BUNDLE_PACKAGE_TYPE) - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - - diff --git a/Documentation/DemoApps/GRDBCombineDemo/README.md b/Documentation/DemoApps/GRDBCombineDemo/README.md index fa10904b6..79703b61a 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/README.md +++ b/Documentation/DemoApps/GRDBCombineDemo/README.md @@ -7,7 +7,7 @@ Combine + SwiftUI Demo Application **Requirements**: iOS 15.0+ / Xcode 12+ -> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration. +> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration. The topics covered in this demo are: diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index b200f2aea..ef1b5f89e 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -16,7 +16,7 @@ 56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 568E5FC31E926430002582E0 /* Interface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC11E926430002582E0 /* Interface.storyboard */; }; 568E5FC51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC41E926430002582E0 /* Assets.xcassets */; }; - 568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + 568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 568E5FD11E926430002582E0 /* InterfaceController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E5FD01E926430002582E0 /* InterfaceController.swift */; }; 568E5FD31E926430002582E0 /* ExtensionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E5FD21E926430002582E0 /* ExtensionDelegate.swift */; }; 568E5FD51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FD41E926430002582E0 /* Assets.xcassets */; }; @@ -127,15 +127,15 @@ /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ - 568E5FDD1E926430002582E0 /* Embed App Extensions */ = { + 568E5FDD1E926430002582E0 /* Embed Foundation Extensions */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 13; files = ( - 568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed App Extensions */, + 568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed Foundation Extensions */, ); - name = "Embed App Extensions"; + name = "Embed Foundation Extensions"; runOnlyForDeploymentPostprocessing = 0; }; 568E5FE11E926430002582E0 /* Embed Watch Content */ = { @@ -366,7 +366,7 @@ buildConfigurationList = 568E5FDE1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS" */; buildPhases = ( 568E5FBD1E926430002582E0 /* Resources */, - 568E5FDD1E926430002582E0 /* Embed App Extensions */, + 568E5FDD1E926430002582E0 /* Embed Foundation Extensions */, ); buildRules = ( ); @@ -425,7 +425,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 1230; - LastUpgradeCheck = 1200; + LastUpgradeCheck = 1400; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { 56185BEF25B80B8900B9C30F = { diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme index 237e9f7b3..bd03393c0 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme @@ -1,6 +1,6 @@ final class AppDatabase { /// Creates an `AppDatabase`, and make sure the database schema is ready. - init(_ dbWriter: DatabaseWriter) throws { + init(_ dbWriter: any DatabaseWriter) throws { self.dbWriter = dbWriter try migrator.migrate(dbWriter) } @@ -17,7 +17,7 @@ final class AppDatabase { /// in-memory `DatabaseQueue`. /// /// See - private let dbWriter: DatabaseWriter + private let dbWriter: any DatabaseWriter /// The DatabaseMigrator that defines the database schema. /// diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift index b905e6138..7c82fe2cf 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift @@ -59,8 +59,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { } /// Updates a player id after it has been inserted in the database. - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -70,7 +70,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { /// /// See /// See -extension DerivableRequest where RowDecoder == Player { +extension DerivableRequest { /// A request of players ordered by name. /// /// For example: diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift index 01217cbe8..92a9a28e6 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift @@ -144,7 +144,7 @@ class PlayerListViewController: UITableViewController { scheduling: .immediate, onError: { error in fatalError("Unexpected error: \(error)") }, onChange: { [weak self] players in - guard let self = self else { return } + guard let self else { return } self.configureTitle(from: players) self.configureDataSource(from: players) }) diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift index 58e7abe66..9815727ac 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift @@ -5,7 +5,7 @@ import GRDB class AppDatabaseTests: XCTestCase { func test_database_schema() throws { // Given an empty database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() // When we instantiate an AppDatabase _ = try AppDatabase(dbQueue) @@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase { func test_savePlayer_inserts() throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) // When we save a new player @@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase { func test_savePlayer_updates() throws { // Given a players database that contains a player - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) var player = Player(id: nil, name: "Arthur", score: 100) try dbQueue.write { db in @@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase { func test_deletePlayers() throws { // Given a players database that contains four players - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 200) @@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase { func test_deleteAllPlayers() throws { // Given a players database that contains players - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 200) @@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase { func test_refreshPlayers_populates_an_empty_database() throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) // When we refresh players @@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase { func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) // When we create random players @@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase { func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws { // Given a players database that contains one player - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() let appDatabase = try AppDatabase(dbQueue) var player = Player(id: nil, name: "Arthur", score: 100) try dbQueue.write { db in diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift index a05e04f78..506f5dfbc 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift @@ -8,7 +8,7 @@ class PlayerTests: XCTestCase { func testInsert() throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) // When we insert a player @@ -23,7 +23,7 @@ class PlayerTests: XCTestCase { func testRoundtrip() throws { // Given an empty players database - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) // When we insert a player and fetch the player with the same id @@ -42,7 +42,7 @@ class PlayerTests: XCTestCase { func testOrderedByScore() throws { // Given a players database that contains players with distinct scores - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) @@ -64,7 +64,7 @@ class PlayerTests: XCTestCase { func testOrderedByScoreSortsIdenticalScoresByName() throws { // Given a players database that contains players with common scores - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) @@ -86,7 +86,7 @@ class PlayerTests: XCTestCase { func testOrderedByName() throws { // Given a players database that contains players with distinct names - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) diff --git a/Documentation/DemoApps/GRDBDemoiOS/README.md b/Documentation/DemoApps/GRDBDemoiOS/README.md index 409fbc79b..36452da36 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/README.md +++ b/Documentation/DemoApps/GRDBDemoiOS/README.md @@ -7,7 +7,7 @@ UIKit Demo Application **Requirements**: iOS 15.0+ / Xcode 12+ -> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration. +> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration. The topics covered in this demo are: diff --git a/Documentation/FTS5Tokenizers.md b/Documentation/FTS5Tokenizers.md index 14e827be1..29c9d7572 100644 --- a/Documentation/FTS5Tokenizers.md +++ b/Documentation/FTS5Tokenizers.md @@ -186,7 +186,7 @@ A FTS5WrapperTokenizer lets the hard tokenization job to another tokenizer, the ```swift protocol FTS5WrapperTokenizer : FTS5CustomTokenizer { - var wrappedTokenizer: FTS5Tokenizer { get } + var wrappedTokenizer: any FTS5Tokenizer { get } func accept( token: String, flags: FTS5TokenFlags, @@ -207,7 +207,7 @@ The `wrappedTokenizer` property is the mandatory wrapped tokenizer. You instanti ```swift final class MyTokenizer : FTS5WrapperTokenizer { - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer init(db: Database, arguments: [String]) throws { // Wrap the unicode61 tokenizer @@ -255,7 +255,7 @@ For example, your custom tokenizer can wrap [unicode61](https://www.sqlite.org/f ```swift final class MyTokenizer : FTS5WrapperTokenizer { static let name = "custom" - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer init(db: Database, arguments: [String]) throws { if arguments.isEmpty { @@ -309,7 +309,7 @@ We'll also take care of the SQLite advice: ```swift final class SynonymsTokenizer : FTS5WrapperTokenizer { static let name = "synonyms" - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer let synonyms: [Set] = [["first", "1st"]] init(db: Database, arguments: [String]) throws { @@ -361,7 +361,7 @@ The tokenizer wrapping is provided by the [FTS5WrapperTokenizer](#fts5wrappertok ```swift final class LatinAsciiTokenizer : FTS5WrapperTokenizer { static let name = "latinascii" - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer init(db: Database, arguments: [String]) throws { wrappedTokenizer = try db.makeTokenizer(.unicode61()) @@ -375,8 +375,6 @@ final class LatinAsciiTokenizer : FTS5WrapperTokenizer { } ``` -> :point_up: **Note**: String.applyingTransform is not available before macOS 10.11. Use the Core Foundation function [CFStringTransform](https://developer.apple.com/reference/corefoundation/1542411-cfstringtransform) instead. - Remember to register LatinAsciiTokenizer before using it: ```swift diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 48652ad86..53eeb3771 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -87,7 +87,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do - See [FST3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences. -> :point_up: **Note**: In case you were still wondering, it is recommended to read the SQLite documentation: [FTS3 & FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html). +> **Note**: In case you were still wondering, it is recommended to read the SQLite documentation: [FTS3 & FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html). ## Create FTS3 and FTS4 Virtual Tables @@ -304,7 +304,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html): +FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -344,9 +344,9 @@ The version of SQLite that ships with iOS, macOS, tvOS and watchOS does not alwa end ``` - > :warning: **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version. + > **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version. - > :point_up: **Note**: there used to be a GRDBPlus CocoaPod with pre-enabled FTS5 support. This CocoaPod is deprecated: please switch to the above technique. + > **Note**: there used to be a GRDBPlus CocoaPod with pre-enabled FTS5 support. This CocoaPod is deprecated: please switch to the above technique. 2. Use the GRDB.swift/SQLCipher CocoaPod subspec (see [encryption](../README.md#encryption)): @@ -587,7 +587,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html): +FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -683,7 +683,7 @@ try db.drop(table: "book_ft") try db.dropFTS4SynchronizationTriggers(forTable: "book_ft") ``` -> :warning: **Warning**: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers **twice**: once with the name of the deleted full-text table, and once with the name of the content table: +> **Warning**: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers **twice**: once with the name of the deleted full-text table, and once with the name of the content table: > > ```swift > // Drop full-text table diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md new file mode 100644 index 000000000..d8b812f12 --- /dev/null +++ b/Documentation/GRDB6MigrationGuide.md @@ -0,0 +1,353 @@ +Migrating From GRDB 5 to GRDB 6 +=============================== + +**This guide aims at helping you upgrading your applications from GRDB 5 to GRDB 6.** + +- [Preparing the Migration to GRDB 6](#preparing-the-migration-to-grdb-6) +- [New requirements](#new-requirements) +- [Primary Associated Types](#primary-associated-types) +- [Record Changes](#record-changes) +- [Other Changes](#other-changes) + + +## Preparing the Migration to GRDB 6 + +If you haven't made it yet, upgrade to the [latest GRDB 5 release](https://github.com/groue/GRDB.swift/tags) first, and fix any deprecation warning prior to the GRDB 6 upgrade. + +You can then upgrade to GRDB 6. Due to the breaking changes, it is possible that your application code no longer compiles. Follow the fix-its that suggest simple syntactic changes. Other modifications that you need to apply are described below. + +## New requirements + +GRDB requirements have been bumped: + +- **Swift 5.7+** (was Swift 5.3+) +- **Xcode 14.0+** (was Xcode 12.0+) +- iOS 11.0+ (unchanged) +- **macOS 10.13+** (was macOS 10.10+) +- **tvOS 11.0+** (was tvOS 11.0+) +- **watchOS 4.0+** (was watchOS 2.0+) +- **SQLite 3.19.3+** (was SQLite 3.8.5+) + +## Primary Associated Types + +Request protocols now come with a primary associated type, enabled by [SE-0346](https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md). This is a great opportunity to simplify your extensions: + +```diff +-extension DerivableRequest where RowDecoder == Book { ++extension DerivableRequest { + /// Order books by title, in a localized case-insensitive fashion + func orderByTitle() -> Self { + order(Column("title").collating(.localizedCaseInsensitiveCompare)) + } + } +``` + +Your extensions to `QueryInterfaceRequest` can be streamlined as well, thanks to [SE-0361](https://github.com/apple/swift-evolution/blob/main/proposals/0361-bound-generic-extensions.md): + +```diff +-extension QueryInterfaceRequest where RowDecoder == Player { ++extension QueryInterfaceRequest { + func selectID() -> QueryInterfaceRequest { + selectPrimaryKey() + } + } +``` + +The `Cursor` protocol has also gained a primary associated type (the type of its elements). + +## Record Changes + +The record protocols have been refactored. We tried to keep the amount of modifications to your existing code as small as possible, but some changes could not be avoided. + +- **The `FetchableRecord.init(row:)` initializer can now throw errors.** + + ```diff + -let player = Player(row: row) + +let player = try Player(row: row) + ``` + + Decodable records that derive their `FetchableRecord` implementation from the standard `Decodable` protocol now throw errors when they find unexpected database values (they used to crash in GRDB 5). + + If you subclass the `Record` type, you have to update your override of `init(row:)`: + + ```diff + class Player: Record { + - required init(row: Row) { + + required init(row: Row) throws { + self.id = row["id"] + self.name = row["name"] + - super.init(row: row) + + try super.init(row: row) + } + } + ``` + + In record types that do not derive their `FetchableRecord.init(row:)` implementation from the standard `Decodable` protocol, you are responsible for throwing decoding errors, as in the sample code below: + +
+ Handling untrusted input + + For example: + + ```swift + struct LogEntry: FetchableRecord { + var date: Date + + init(row: Row) throws { + let dbValue: DatabaseValue = row["date"] + if dbValue.isNull { + // Handle NULL + throw ... + } else if let date = Date.fromDatabaseValue(dbValue) { + self.date = date + } else { + // Handle invalid date + throw ... + } + } + } + ``` + +
+ +- **The `EncodableRecord.encode(to:)` method can now throw errors.** + + Encodable records that derive their `EncodableRecord` implementation from the standard `Encodable` protocol now throw errors when they can't be encoded into database values (they used to crash in GRDB 5). + + If you subclass the `Record` type, you have to update your override of `encode(to:)`: + + ```diff + class Player: Record { + - override func encode(to container: inout PersistenceContainer) { + + override func encode(to container: inout PersistenceContainer) throws { + container["id"] = id + container["name"] = name + } + } + ``` + + This change has an impact on a few other apis, that can now throw errors as well: + + ```diff + -let dictionary = player.databaseDictionary + -let changes = newPlayer.databaseChanges(from: oldPlayer) + -let changes = player.databaseChanges // Record class only + +let dictionary = try player.databaseDictionary + +let changes = try newPlayer.databaseChanges(from: oldPlayer) + +let changes = try player.databaseChanges // Record class only + ``` + +- **The signature of the `didInsert` method has changed**. + + You have to update all the `didInsert` methods in your application: + + ```diff + struct Player: MutablePersistableRecord { + var id: Int64? + + // Update auto-incremented id upon successful insertion + - mutating func didInsert(with rowID: Int64, for column: String?) { + - id = rowID + + mutating func didInsert(_ inserted: InsertionSuccess) { + + id = inserted.rowID + } + } + ``` + + If you subclass the `Record` class, you have to call `super` at some point of your implementation: + + ```diff + class Player: Record { + var id: Int64? + + // Update auto-incremented id upon successful insertion + - override func didInsert(with rowID: Int64, for column: String?) { + - id = rowID + + override func didInsert(_ inserted: InsertionSuccess) { + + super.didInsert(inserted) + + id = inserted.rowID + } + } + ``` + +- **PersistableRecord types now customize persistence methods with "persistence callbacks"**. + + It is no longer possible to override persistence methods such as `insert` or `update`. Customizing the persistence methods is now possible with callbacks such as `willSave`, `willInsert`, or `didDelete` (see [Persistence Callbacks](../README.md#persistence-callbacks) for the full list of callbacks). + + For example, let's consider a record that performs some validation before insertion and updates. In GRDB 5, this would look like: + + ```swift + // GRDB 5 + struct Link: PersistableRecord { + var url: URL + + func insert(_ db: Database) throws { + try validate() + try performInsert(db) + } + + func update(_ db: Database, columns: Set) throws { + try validate() + try performUpdate(db, columns: columns) + } + + func validate() throws { + if url.host == nil { + throw ValidationError("url must be absolute.") + } + } + } + ``` + + With GRDB 6, record validation can be implemented with the `willSave` callback: + + ```swift + // GRDB 6 + struct Link: PersistableRecord { + var url: URL + + func willSave(_ db: Database) throws { + if url.host == nil { + throw ValidationError("url must be absolute.") + } + } + } + + try link.insert(db) // Calls the willSave callback + try link.update(db) // Calls the willSave callback + try link.save(db) // Calls the willSave callback + try link.upsert(db) // Calls the willSave callback + ``` + + If you subclass the `Record` class, you have to call `super` at some point of your implementation: + + ```swift + // GRDB 6 + class Link: Record { + var url: URL + + override func willSave(_ db: Database) throws { + try super.willSave(db) + if url.host == nil { + throw ValidationError("url must be absolute.") + } + } + } + ``` + +- **Handling of the `IGNORE` conflict policy** + + The SQLite [IGNORE](https://www.sqlite.org/lang_conflict.html) conflict policy has SQLite skip insertions and updates that violate a schema constraint, without reporting any error. You can skip this paragraph if you do not use this policy. + + GRDB 6 has slightly changed the handling of the `IGNORE` policy. + + The `didInsert` callback is now always called on `INSERT OR IGNORE` insertions. In GRDB 5, `didInsert` was not called for record types that specify the `.ignore` conflict policy on inserts: + + ```swift + // Given a record with ignore conflict policy for inserts... + struct Player: TableRecord, FetchableRecord { + static let persistenceConflictPolicy = PersistenceConflictPolicy(insert: .ignore) + } + + // GRDB 5: Does not call didInsert + // GRDB 6: Calls didInsert + try player.insert(db) + ``` + + Since `INSERT OR IGNORE` may silently fail, the `didInsert` method will be called with some random rowid in case of failed insert. You can detect failed insertions with the new method `insertAndFetch`: + + ```swift + // How to detect failed `INSERT OR IGNORE`: + // INSERT OR IGNORE INTO player ... RETURNING * + if let insertedPlayer = try player.insertAndFetch(db) { + // Succesful insertion + } else { + // Ignored failure + } + ``` + +## Other Changes + +- The initializer of in-memory databases can now throw errors: + + ```diff + -let dbQueue = DatabaseQueue() + +let dbQueue = try DatabaseQueue() + ``` + +- The `selectID()` method is removed. You can provide your own implementation, based on the new `selectPrimaryKey(as:)` method: + + ```swift + extension QueryInterfaceRequest { + func selectID() -> QueryInterfaceRequest { + selectPrimaryKey() + } + } + ``` + +- `Cursor.isEmpty` is now a throwing property, instead of a method: + + ```diff + -if try cursor.isEmpty() { ... } + +if try cursor.isEmpty { ... } + ``` + +- The `Record.copy()` method was removed, without replacement. + +- The `DerivableRequest.limit(_:offset_:)` method was removed, without replacement. + + You can still limit `QueryInterfaceRequest`, but associations can no longer be limited: + + ```swift + // Still OK: a limited request of authors + let request = Author.limit(10) + + // Still OK: a limited request of books + let request = author.request(for: Author.books).limit(10) + + // No longer possible: including a limited association + let request = Author.including(all: Author.books.limit(10)) + ``` + +- `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable. + + ```swift + let observation = DatabaseRegionObservation.tracking(Player.all()) + + // GRDB 5 + do { + let observer = try observation.start(in: dbQueue) { db in + print("Players were modified") + } + } catch { + // handle error + } + + // GRDB 6 + let cancellable = observation.start( + in: dbQueue, + onError: { error in /* handle error */ }, + onChange: { db in + print("Players were modified") + }) + ``` + + The `DatabaseRegionObservation.extent` property was removed. You now control the duration of the observation with the cancellable returned from the `start` method. + +- Database cursors no longer have a `statement` property. When you want information about the database statement used by a cursor, use dedicated cursor properties. For example: + + ```diff + -let sql = cursor.statement.sql + -let columns = cursor.statement.columnNames + +let sql = cursor.sql + +let columns = cursor.columnNames + ``` + +- The transaction hook `Database.afterNextTransactionCommit(_:)` was renamed `Database.afterNextTransaction(onCommit:onRollback:)`, and is now able to report rollbacks as well as commits. + + ```diff + -db.afterNextTransactionCommit { db in + +db.afterNextTransaction { db in + print("Succesful commit") + } + ``` diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 406cbce75..8c2942efe 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -109,29 +109,33 @@ struct Book: Codable, Identifiable { var authorId: Int64 var title: String } +``` +We add database powers to our types with [record protocols]. Since our records use auto-incremented ids, we provide an implementation of the `didInsert` method: + +```swift // Add Database access extension Author: FetchableRecord, MutablePersistableRecord { // Update auto-incremented id upon successful insertion - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } extension Book: FetchableRecord, MutablePersistableRecord { // Update auto-incremented id upon successful insertion - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } ``` -That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`. See [record protocols] for more information. +That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`. > :bulb: **Tip**: When a column of a database table can't be NULL, store it in a non-optional property of your record type. On the other side, when the database may contain NULL, define an optional property. > -> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(with:for:)` method: +> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(_:)` method: > > ```swift > try dbQueue.write { db in @@ -234,7 +238,7 @@ Let's look at three examples: > :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface. -**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#customizing-the-persistence-methods) before they enter the database. +**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#persistence-callbacks) before they enter the database. ## Singleton Records @@ -299,8 +303,8 @@ When you find yourself build similar requests over and over in your application, To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc: ```swift -// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~ -extension DerivableRequest where RowDecoder == Author { +// Author requests +extension DerivableRequest { /// Order authors by name, in a localized case-insensitive fashion func orderByName() -> Self { let name = Author.Columns.name @@ -342,8 +346,8 @@ try dbQueue.read { db in Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(authorCountry:)` for books, below, uses the `filter(country:)` for authors: ```swift -// Book requests ~~~~~~~~~~~~~~~~~~~~~~~~ -extension DerivableRequest where RowDecoder == Book { +// Book requests +extension DerivableRequest { /// Filters books by kind func filter(kind: Book.Kind) -> Self { filter(Book.Columns.kind == kind) @@ -368,16 +372,16 @@ try dbQueue.read { db in Extensions to the `DerivableRequest` protocol can not change the type of requests. This has to be expressed in an extension to `QueryInterfaceRequest`. For example: ```swift -// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~ -extension QueryInterfaceRequest where RowDecoder == Author { +// Author requests +extension QueryInterfaceRequest { // Selects author ids - func id() -> QueryInterfaceRequest { - select(Author.Columns.id) + func selectId() -> QueryInterfaceRequest { + selectPrimaryKey(as: Int64.self) } } // IDs of French authors -let ids: [Int64] = try Author.all().filter(country: "France").id().fetchAll(db) +let ids: [Int64] = try Author.all().filter(country: "France").selectId().fetchAll(db) ``` ## Compose Records @@ -424,7 +428,7 @@ As in the sample code above, requests which feed from several associated records Unlike the primitive persistable record types `Author` and `Book`, those records can not write in the database. They are simple data types, passive views on the database content. Remember, only [Persistable Record Types are Responsible for Their Tables]. -> :question: **Note**: The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they? +> **Note**: The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they? > > That is because other ORMs perform lazy loading: > @@ -747,7 +751,7 @@ When a new screen is added to your application, and you want to make sure it dis In other words: since GRDB is an unmanaged ORM, some amount of management must be imported into your application in order to make it fully thread-safe. -> :question: **Note**: Wrapping several fetches in a single `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony: +> **Note**: Wrapping several fetches in a single `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony: > > ```ruby > # Ruby's Active Record diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index a7d94127a..234c3a1e5 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -77,7 +77,7 @@ try dbQueue.read { db in } ``` -See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.26/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Structs/DatabaseMigrator.html) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option @@ -89,7 +89,7 @@ var migrator = DatabaseMigrator() migrator.eraseDatabaseOnSchemaChange = true ``` -> :warning: **Warning**: This option can destroy your precious users' data! +> **Warning**: This option can destroy your precious users' data! Setting `eraseDatabaseOnSchemaChange` is useful during application development, as you are still designing migrations, and the schema changes often. @@ -153,9 +153,9 @@ The detailed sequence of operations is described below, some of them are perform 12. GRDB: If foreign keys constraints were originally enabled, reenable them now. -> :point_up: **Note**: Take care to follow the procedure above precisely, in the same order, or you might corrupt triggers, views, and foreign key constraints. Have a second look at [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes) if necessary. +> **Note**: Take care to follow the procedure above precisely, in the same order, or you might corrupt triggers, views, and foreign key constraints. Have a second look at [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes) if necessary. > -> :point_up: **Note**: By default, all migrations perform, at step 10, a full check of all foreign keys in your database. When your database is big, those checks may have a noticeable impact on migration performances. See [Foreign Key Checks] for a discussion of your ways to avoid this toll. +> **Note**: By default, all migrations perform, at step 10, a full check of all foreign keys in your database. When your database is big, those checks may have a noticeable impact on migration performances. See [Foreign Key Checks] for a discussion of your ways to avoid this toll. ## Foreign Key Checks @@ -274,9 +274,12 @@ The `asyncMigrate(_:completion:)` method: ```swift // Completes in a protected dispatch queue that can write in the database -migrator.asyncMigrate(dbQueue, completion: { db, error in - if let error = error { +migrator.asyncMigrate(dbQueue, completion: { result in + switch result { + case .failure: // Some error occurred during migrations + case let .success(db): + // Migrations succeeded } }) ``` diff --git a/Documentation/Playgrounds/Associations.playground/Contents.swift b/Documentation/Playgrounds/Associations.playground/Contents.swift index fd3fad7b9..61040d563 100644 --- a/Documentation/Playgrounds/Associations.playground/Contents.swift +++ b/Documentation/Playgrounds/Associations.playground/Contents.swift @@ -14,7 +14,7 @@ var configuration = Configuration() configuration.prepareDatabase { db in db.trace { print("SQL> \($0)") } } -let dbQueue = DatabaseQueue(configuration: configuration) +let dbQueue = try DatabaseQueue(configuration: configuration) //: Use a migrator to define the database schema @@ -44,8 +44,8 @@ struct Author: Codable, FetchableRecord, MutablePersistableRecord { var id: Int64? var name: String - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -54,8 +54,8 @@ struct Book: Codable, FetchableRecord, MutablePersistableRecord { var authorId: Int64 var title: String - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } diff --git a/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift b/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift deleted file mode 100644 index f3b03b89e..000000000 --- a/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift +++ /dev/null @@ -1,469 +0,0 @@ -//: # Customized Decoding of Database Rows -//: -//: To run this playground: -//: -//: - Open GRDB.xcworkspace -//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX -//: - Build: menu Product > Build -//: - Select the playground in the Playgrounds Group -//: - Run the playground - -import GRDB - -//: This playground demonstrates how one can implement **customized decoding of -//: database rows**. -//: -//: Customized row decoding allows you to go beyond the built-in support for -//: requests of raw rows, values, or types that adopt the -//: FetchableRecord protocol. -//: -//: For example: -//: -//: - Your application needs polymorphic row decoding: it decodes some class or -//: another, depending on the values contained in a database row. -//: -//: - Your application needs to decode rows with a context: each decoded value -//: should be initialized with some extra value that does not come from -//: the database. -//: -//: - Your application needs a record type that supports untrusted databases, -//: and may fail at decoding database rows (throw an error when a row contains -//: invalid values). -//: -//: None of those use cases can be handled by the built-in `FetchableRecord` -//: protocol and its `init(row:)` initializer. They need *customized -//: row decoding*. -//: -//: ## An Example: Polymorphic Decoding -//: -//: In this playground, we will provide some sample code that performs -//: polymorphic row decoding. Given a base class, `Base`, and two subclasses -//: `Foo` and `Bar`, we'd like to fetch Foo or Bar instances, depending on the -//: value found in the `type` column of the `base` database table. -//: -//: From this sample code, we hope that you will be able to derive your own -//: customized decoding. -//: -//: Everything starts from our class hierarchy: - -class Base { - var description: String { "Base" } - init() { } -} - -class Foo: Base { - var name: String - override var description: String { "Foo: \(name)" } - init(name: String) { - self.name = name - super.init() - } -} - -class Bar: Base { - var score: Int - override var description: String { "Bar: \(score)" } - init(score: Int) { - self.score = score - super.init() - } -} - -//: We need a database, a table, and a few values so that we can do a real demo: - -// An in-memory database is good enough -let dbQueue = DatabaseQueue() - -try dbQueue.write { db in - // Database table - try db.create(table: "base") { t in - t.column("type", .text).notNull() // Contains "Foo" or "Bar" - t.column("fooName", .text) // Contains a Foo's name - t.column("barScore", .integer) // Contains a Bar's score - } - - // Demo values: two Foo and one Bar - try db.execute( - sql: """ - INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?); - INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?); - INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?); - """, - arguments: [ - "Foo", "Arthur", nil, - "Bar", nil, 100, - "Foo", "Barbara", nil, - ]) -} - -//: We also need a method that decodes database rows into `Foo` or `Bar` -//: instances: let's call it `Base.decode(row:)`: - -extension Base { - static func decode(row: Row) -> Base { - switch row["type"] as String { - case "Foo": - return Foo(name: row["fooName"]) - case "Bar": - return Bar(score: row["barScore"]) - case let type: - fatalError("Unknown Base type: \(type)") - } - } -} - -//: Now we are able to express the kind of request we'd like to write. For -//: example, we could fetch all Base values from the database: -//: -//: try dbQueue.read { db in -//: // An array [Base] that contains Foo and Bar instances -//: let bases = try Base.fetchAll(db) -//: } -//: -//: But so far, we have a compiler error: - -// Compiler error: Type 'Base' has no member 'fetchAll' -//try dbQueue.read { db in -// let bases = try Base.fetchAll(db) -//} - -//: We'll see that this goal can be achieved by declaring a protocol, writing a -//: few extensions that guarantee the most efficient use of GRDB, and have the -//: Base class adopt this protocol. -//: -//: ### Keep It Simple, Stupid! -//: -//: But first, let's see how polymorphic decoding can be done as simply as -//: possible. After all, it is useless to design a full-fledged protocol unless -//: we need to use this protocol several times, or write code that is as -//: streamlined as possible. -//: -//: Can we fetch Foo and Bar values from an SQL request? Sure: - -try dbQueue.read { db in - print("> KISS: Fetch from SQL") - let rows = try Row.fetchAll(db, sql: "SELECT * FROM base") // Fetch database rows - let bases = rows.map { row in // Decode database rows - Base.decode(row: row) - } - for base in bases { // Use fetched values - print(base.description) - } -} - -//: Can we have GRDB generate SQL for us? Sure, we just need to adopt the -//: `TableRecord` protocol: - -extension Base: TableRecord { - static let databaseTableName = "base" -} - -try dbQueue.read { db in - print("> KISS: Fetch from query interface request") - let request = Base.filter(Column("type") == "Foo") // Define a request - let rows = try Row.fetchAll(db, request) // Fetch database rows - let bases = rows.map { row in // Decode database rows - Base.decode(row: row) - } - for base in bases { // Use fetched values - print(base.description) - } -} - -//: As seen above, we can perform polymorphic requests with the standard GRDB, -//: by fetching raw rows and mapping them through a decoding method. -//: -//: The resulting code is not as streamlined as usual GRDB code, but we could -//: already do what we needed without much effort. -//: -//: ### Custom Protocol: MyDatabaseDecoder -//: -//: In the rest of this playground, we will define a **new realm of requests**. -//: -//: GRDB ships with three built-in realms of requests: requests of raw rows, -//: requests of values, and requests of record types that adopt the -//: `FetchableRecord` protocol. -//: -//: We'll define requests of record types that adopt the custom -//: `MyDatabaseDecoder` protocol: - -protocol MyDatabaseDecoder { - associatedtype DecodedType - static func decode(row: Row) -> DecodedType -} - -//: Types that adopt the MyDatabaseDecoder protocol are able, among other -//: things, to perform polymorphic decoding. Our Base class, for example: - -extension Base: MyDatabaseDecoder { - // Already declared above: - // static func decode(row: Row) -> Base { ... } -} - -//: Now let's see how we can define a new realm of requests based on the -//: `MyDatabaseDecoder` protocol. Our goal is to make them just as powerful as -//: ready-made requests of rows, values and FetchableRecord. -//: -//: All we need is a set of *extensions* that define the classic GRDB fetching -//: methods: `fetchOne`, `fetchAll`, and `fetchCursor`. The most fundamental one -//: is `fetchCursor`, because from it we can derive the two others. -//: -//: The first extension is the most low-level one: fetching from SQLite -//: **prepared statement**: -//: -//: try dbQueue.read { db in -//: let statement = try db.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 Prepared Statement - - // Statement, StatementArguments, and RowAdapter are the fundamental - // fetching parameters of GRDB. Make sure to accept them all: - 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: 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: 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() - } -} - -try dbQueue.read { db in - print("> Fetch from prepared statement") - let statement = try db.makeStatement(sql: "SELECT * FROM base") - let bases = try Base.fetchAll(statement) - for base in bases { - print(base.description) - } -} - -//: Now that we can fetch from prepared statements, we can fetch when given a -//: **request**, as defined by the `FetchRequest` protocol. This is the -//: protocol for query interface requests such as `Base.all()`, or -//: `SQLRequest`, etc. -//: -//: try dbQueue.read { db in -//: let request = Base.all() -//: try Base.fetchCursor(db, request) // Cursor of Base -//: try Base.fetchAll(db, request) // [Base] -//: try Base.fetchOne(db, request) // Base? -//: } -extension MyDatabaseDecoder { - // MARK: - Fetch from FetchRequest - - static func fetchCursor(_ db: Database, _ request: R) throws -> MapCursor { - let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false) - return try fetchCursor(preparedRequest.statement, adapter: preparedRequest.adapter) - } - - static func fetchAll(_ db: Database, _ request: R) throws -> [DecodedType] { - let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false) - return try fetchAll(preparedRequest.statement, adapter: preparedRequest.adapter) - } - - static func fetchOne(_ db: Database, _ request: R) throws -> DecodedType? { - // The `forSingleResult: true` argument hints the request that a single - // row will be consumed. Some requests will add a LIMIT SQL clause. - let preparedRequest = try request.makePreparedRequest(db, forSingleResult: true) - return try fetchOne(preparedRequest.statement, adapter: preparedRequest.adapter) - } -} - -try dbQueue.read { db in - print("> Fetch given a request") - let request = Base.all() - let bases = try Base.fetchAll(db, request) - for base in bases { - print(base.description) - } -} - -//: When it's fine to fetch given a request, it's even better when requests can -//: fetch, too: -//: -//: try dbQueue.read { db in -//: let request = Base.all() -//: try request.fetchCursor(db) // Cursor of Base -//: try request.fetchAll(db) // [Base] -//: try request.fetchOne(db) // Base? -//: } -extension FetchRequest where RowDecoder: MyDatabaseDecoder { - // MARK: - FetchRequest fetching methods - - func fetchCursor(_ db: Database) throws -> MapCursor { - try RowDecoder.fetchCursor(db, self) - } - - func fetchAll(_ db: Database) throws -> [RowDecoder.DecodedType] { - try RowDecoder.fetchAll(db, self) - } - - func fetchOne(_ db: Database) throws -> RowDecoder.DecodedType? { - try RowDecoder.fetchOne(db, self) - } -} - -try dbQueue.read { db in - print("> Fetch from request") - let request = Base.all() - let bases = try request.fetchAll(db) - for base in bases { - print(base.description) - } -} - -//: Types that adopt both FetchableRecord and TableRecord are able to fetch -//: right from the base type. Let's allow this as well for MyDatabaseDecoder: -//: -//: try dbQueue.read { db in -//: try Base.fetchCursor(db) // Cursor of Base -//: try Base.fetchAll(db) // [Base] -//: try Base.fetchOne(db) // Base? -//: } -extension MyDatabaseDecoder where Self: TableRecord { - // MARK: - Static fetching methods - - static func fetchCursor(_ db: Database) throws -> MapCursor { - try all().fetchCursor(db) - } - - static func fetchAll(_ db: Database) throws -> [DecodedType] { - try all().fetchAll(db) - } - - static func fetchOne(_ db: Database) throws -> DecodedType? { - try all().fetchOne(db) - } -} - -try dbQueue.read { db in - print("> Fetch from base type") - let bases = try Base.fetchAll(db) - for base in bases { - print(base.description) - } -} - -//: Finally, you can support raw SQL as well: -//: -//: try dbQueue.read { db in -//: try Base.fetchAll(db, -//: sql: "SELECT ... WHERE name = ?", -//: arguments: ["O'Brien"]) // [Base] -//: } -extension MyDatabaseDecoder { - // MARK: - Fetch from SQL - - static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> MapCursor { - try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) - } - - static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [DecodedType] { - try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) - } - - static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DecodedType? { - try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) - } -} - -try dbQueue.read { db in - print("> Fetch from SQL") - let bases = try Base.fetchAll(db, sql: "SELECT * FROM base") - for base in bases { - print(base.description) - } -} - -//: Voilà! Our `MyDatabaseDecoder` protocol is now as able as the built-in -//: `FetchableRecord` protocol. -//: -//: To sum up, you have learned: -//: -//: - how to keep things simple: as long as you can fetch rows, you can decode -//: them the way you want. -//: - how to define a whole new realm of requests based on a custom protocol. -//: This involves writing a few extensions that give your protocol the same -//: fluent interface that is ready-made for the built-in FetchableRecord -//: protocol. This is more work, but you are granted with the full -//: customization freedom. -//: -//: To end this tour, let's quickly look at two other possible customized -//: row decoding strategies. -//: -//: ## An Example: Contextualized Records -//: -//: Your application needs to decode rows with a context: each decoded value -//: should be initialized with some extra value that does not come from -//: the database. -//: -//: In this case, you may define a `ContextFetchableRecord` protocol, and -//: derive all other fetching methods from the most fundamental one, which -//: fetches a cursor from a prepared statement (as we did for the -//: MyDatabaseDecoder protocol, above): - -protocol ContextFetchableRecord { - associatedtype Context - init(row: Row, context: Context) -} - -extension ContextFetchableRecord { - static func fetchCursor( - _ statement: Statement, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil, - context: Context) - throws -> MapCursor - { - // Turn the cursor of raw rows into a cursor of decoded rows - return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map { - self.init(row: $0, context: context) - } - } - - // Define fetchAll, fetchOne, and other extensions... -} - -//: ## An Example: Failable Records -//: -//: Your application needs a record type that supports untrusted databases, -//: and may fail at decoding database rows (throw an error when a row contains -//: invalid values). -//: -//: In this case, you may define a `FailableFetchableRecord` protocol, and -//: derive all other fetching methods from the most fundamental one, which -//: fetches a cursor from a prepared statement (as we did for the -//: MyDatabaseDecoder protocol, above): - -protocol FailableFetchableRecord { - init(row: Row) throws -} - -extension FailableFetchableRecord { - static func fetchCursor( - _ statement: 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 { - try self.init(row: $0) - } - } - - // Define fetchAll, fetchOne, and other extensions... -} diff --git a/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/contents.xcplayground b/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/contents.xcplayground deleted file mode 100644 index ec88aeaa8..000000000 --- a/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/contents.xcplayground +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/Documentation/Playgrounds/MyPlayground.playground/Contents.swift b/Documentation/Playgrounds/MyPlayground.playground/Contents.swift index 0819f2496..d02e45194 100644 --- a/Documentation/Playgrounds/MyPlayground.playground/Contents.swift +++ b/Documentation/Playgrounds/MyPlayground.playground/Contents.swift @@ -6,15 +6,15 @@ var configuration = Configuration() configuration.prepareDatabase { db in db.trace { print("SQL> \($0)") } } -let dbQueue = DatabaseQueue(configuration: configuration) +let dbQueue = try DatabaseQueue(configuration: configuration) struct Player: Codable, FetchableRecord, MutablePersistableRecord { var id: Int64? var name: String var score: Int - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } diff --git a/Documentation/Playgrounds/Tour.playground/Contents.swift b/Documentation/Playgrounds/Tour.playground/Contents.swift index 77be71509..56cec233d 100644 --- a/Documentation/Playgrounds/Tour.playground/Contents.swift +++ b/Documentation/Playgrounds/Tour.playground/Contents.swift @@ -22,7 +22,7 @@ var configuration = Configuration() configuration.prepareDatabase { db in db.trace { print("SQL> \($0)") } } -let dbQueue = DatabaseQueue(configuration: configuration) +let dbQueue = try DatabaseQueue(configuration: configuration) //: Execute SQL queries @@ -92,7 +92,7 @@ extension Place : TableRecord { // Adopt MutablePersistableRecord extension Place : MutablePersistableRecord { - func encode(to container: inout PersistenceContainer) { + func encode(to container: inout PersistenceContainer) throws { container["id"] = id container["title"] = title container["favorite"] = favorite @@ -100,8 +100,8 @@ extension Place : MutablePersistableRecord { container["longitude"] = coordinate.longitude } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } diff --git a/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift b/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift index 509064fec..c57ed07e3 100644 --- a/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift +++ b/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift @@ -11,7 +11,7 @@ import GRDB // Create the database -let dbQueue = DatabaseQueue() // Memory database +let dbQueue = try DatabaseQueue() // Memory database var migrator = DatabaseMigrator() migrator.registerMigration("createPerson") { db in try db.create(table: "person") { t in diff --git a/Documentation/QueryInterfaceOrganization.md b/Documentation/QueryInterfaceOrganization.md index 8e257db2e..bbb04b82d 100644 --- a/Documentation/QueryInterfaceOrganization.md +++ b/Documentation/QueryInterfaceOrganization.md @@ -179,9 +179,9 @@ protocol DatabaseValueConvertible: SQLExpressible { `DerivableRequest` is the protocol for query interface requests and associations that can be refined. It is adopted by [QueryInterfaceRequest] and [Association]. ```swift -protocol DerivableRequest: AggregatingRequest, FilteredRequest, - JoinableRequest, OrderedRequest, - SelectionRequest, TableRequest +protocol DerivableRequest: AggregatingRequest, FilteredRequest, + JoinableRequest, OrderedRequest, + SelectionRequest, TableRequest { func distinct() -> Self func with(_ cte: CommonTableExpression) -> Self @@ -202,7 +202,7 @@ DerivableRequest makes it possible to build reusable code snippets that apply to `FetchRequest` is the protocol for requests that can fetch. It is adopted by [QueryInterfaceRequest] and [SQLRequest]. It conforms to [SQLSubqueryable] and [DatabaseRegionConvertible]. ```swift -protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible { +protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible { /// The type that tells how fetched database rows should be interpreted. associatedtype RowDecoder diff --git a/Documentation/SQLInterpolation.md b/Documentation/SQLInterpolation.md index ea7e1d6da..884c19788 100644 --- a/Documentation/SQLInterpolation.md +++ b/Documentation/SQLInterpolation.md @@ -389,7 +389,7 @@ This chapter lists all kinds of supported interpolations. struct AltPlayer: TableRecord { static let databaseTableName = "player" - static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")] + static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")] } // SELECT player.id, player.name FROM player diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 0000990cb..ab2448fe4 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.26.0' + s.version = '6.0.0-beta' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' @@ -9,11 +9,11 @@ Pod::Spec.new do |s| s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" } s.module_name = 'GRDB' - s.swift_versions = ['5.3', '5.4', '5.5'] + s.swift_versions = ['5.7'] s.ios.deployment_target = '11.0' - s.osx.deployment_target = '10.10' - s.watchos.deployment_target = '2.0' - s.tvos.deployment_target = '9.0' + s.osx.deployment_target = '10.13' + s.watchos.deployment_target = '4.0' + s.tvos.deployment_target = '11.0' s.default_subspec = 'standard' s.subspec 'standard' do |ss| @@ -25,7 +25,7 @@ Pod::Spec.new do |s| s.subspec 'SQLCipher' do |ss| ss.source_files = 'GRDB/**/*.swift', 'Support/SQLCipher_config.h' ss.framework = 'Foundation' - ss.dependency 'SQLCipher', '>= 3.4.0' + ss.dependency 'SQLCipher', '>= 3.4.2' ss.xcconfig = { 'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_HAS_CODEC -D GRDBCIPHER -D SQLITE_ENABLE_FTS5', 'OTHER_CFLAGS' => '$(inherited) -DSQLITE_HAS_CODEC -DGRDBCIPHER -DSQLITE_ENABLE_FTS5', diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index f48bd54f1..1b0b2c892 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -70,8 +70,8 @@ 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; }; 560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; - 560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; - 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; + 560D92471C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */; }; + 560D92481C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */; }; 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 5611620825757583007AAF99 /* JoinAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5611620725757583007AAF99 /* JoinAssociation.swift */; }; @@ -84,6 +84,10 @@ 5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; 5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; + 56158780288D875E00A67323 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615877F288D875E00A67323 /* Optional.swift */; }; + 56158781288D875E00A67323 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615877F288D875E00A67323 /* Optional.swift */; }; + 56158782288D875E00A67323 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615877F288D875E00A67323 /* Optional.swift */; }; + 56158783288D875E00A67323 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615877F288D875E00A67323 /* Optional.swift */; }; 5615B261222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B25A222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */; }; 5615B262222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B25A222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */; }; 5615B26A222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B269222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift */; }; @@ -393,7 +397,7 @@ 565490D91D5AE252005622CB /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; - 565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; + 565490E11D5AE252005622CB /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */; }; 565490E21D5AE252005622CB /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; 565490E41D5AE252005622CB /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; @@ -490,6 +494,10 @@ 566BE71F2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; }; 566BE7202342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; }; 566BE7212342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; }; + 566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE0C288D763C0000DCFB /* Fixits.swift */; }; + 566DDE0E288D763C0000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE0C288D763C0000DCFB /* Fixits.swift */; }; + 566DDE0F288D763C0000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE0C288D763C0000DCFB /* Fixits.swift */; }; + 566DDE10288D763C0000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE0C288D763C0000DCFB /* Fixits.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 */; }; @@ -549,9 +557,6 @@ 567DAF221EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; 567DAF351EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; 567DAF391EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; - 567ECE4F2222E431009245CA /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; }; - 567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; }; - 567ECE512222E431009245CA /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; }; 567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; @@ -684,7 +689,6 @@ 56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */; }; 56A2385A1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382B1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift */; }; 56A2385C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */; }; - 56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; 56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; 56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; 56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; }; @@ -787,6 +791,38 @@ 56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; }; 56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; }; 56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; }; + 56D110BF28AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */; }; + 56D110C028AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */; }; + 56D110C128AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */; }; + 56D110C228AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */; }; + 56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */; }; + 56D110C528AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */; }; + 56D110C628AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */; }; + 56D110C728AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */; }; + 56D110C928AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */; }; + 56D110CA28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */; }; + 56D110CB28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */; }; + 56D110CC28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */; }; + 56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */; }; + 56D110CF28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */; }; + 56D110D028AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */; }; + 56D110D128AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */; }; + 56D110D328AFC81400E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D228AFC81400E64463 /* PersistableRecord.swift */; }; + 56D110D428AFC81400E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D228AFC81400E64463 /* PersistableRecord.swift */; }; + 56D110D528AFC81400E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D228AFC81400E64463 /* PersistableRecord.swift */; }; + 56D110D628AFC81400E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D228AFC81400E64463 /* PersistableRecord.swift */; }; + 56D110D828AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; }; + 56D110D928AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; }; + 56D110DA28AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; }; + 56D110DB28AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; }; + 56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; }; + 56D110DE28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; }; + 56D110DF28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; }; + 56D110E028AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; }; + 56D110FA28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; }; + 56D110FB28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; }; + 56D110FC28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; }; + 56D110FD28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; }; 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; }; 56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */; }; 56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; }; @@ -817,7 +853,6 @@ 56D496701D81309E008276D7 /* RecordPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */; }; 56D496711D81309E008276D7 /* RecordPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382B1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift */; }; 56D496721D81309E008276D7 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */; }; - 56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; 56D496751D81309E008276D7 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; 56D496771D81309E008276D7 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; 56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; }; @@ -931,6 +966,14 @@ 56F61DD5283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; }; 56F61DD6283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; }; 56F61DD7283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; }; + 56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; }; + 56FA0C3128B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; }; + 56FA0C3228B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; }; + 56FA0C3328B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; }; + 56FA0C3928B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; }; + 56FA0C3A28B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; }; + 56FA0C3B28B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; }; + 56FA0C3C28B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; }; 56FBFED92210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; 56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; 56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; @@ -1025,7 +1068,6 @@ AAA4DCD0230F1E0600C74B15 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */; }; AAA4DCD1230F1E0600C74B15 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; }; AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; - AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; }; AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; }; AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; @@ -1035,7 +1077,7 @@ AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; }; AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; }; - AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; + AAA4DCDF230F1E0600C74B15 /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */; }; AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; AAA4DCE3230F1E0600C74B15 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* Map.swift */; }; @@ -1132,7 +1174,6 @@ AAA4DD5A230F262000C74B15 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; AAA4DD5B230F262000C74B15 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; AAA4DD5C230F262000C74B15 /* DatabaseQueueBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */; }; - AAA4DD5D230F262000C74B15 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; AAA4DD5E230F262000C74B15 /* SQLLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */; }; AAA4DD5F230F262000C74B15 /* FTS5PatternTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C01DA521450002DA19 /* FTS5PatternTests.swift */; }; AAA4DD60230F262000C74B15 /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; @@ -1313,11 +1354,12 @@ 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunctionTests.swift; sourceTree = ""; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; - 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; + 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 5611620725757583007AAF99 /* JoinAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinAssociation.swift; sourceTree = ""; }; 5613ED3421A95A5C00DC7A68 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = ""; }; 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = ""; }; + 5615877F288D875E00A67323 /* Optional.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Optional.swift; sourceTree = ""; }; 5615B25A222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLDerivationTests.swift; sourceTree = ""; }; 5615B269222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughRowScopeTests.swift; sourceTree = ""; }; 5615B274222B107900061C1C /* AssociationHasOneThroughFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughFetchableRecordTests.swift; sourceTree = ""; }; @@ -1470,6 +1512,7 @@ 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; 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 = ""; }; + 566DDE0C288D763C0000DCFB /* Fixits.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Fixits.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 = ""; }; @@ -1495,7 +1538,6 @@ 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; - 567ECE4E2222E431009245CA /* GRDB-5.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-5.0.swift"; sourceTree = ""; }; 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 = ""; }; 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = ""; }; @@ -1571,7 +1613,6 @@ 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPrimaryKeyRowIDTests.swift; sourceTree = ""; }; 56A2382B1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPrimaryKeySingleTests.swift; sourceTree = ""; }; 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift; sourceTree = ""; }; - 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordCopyTests.swift; sourceTree = ""; }; 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordEditedTests.swift; sourceTree = ""; }; 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordInitializersTests.swift; sourceTree = ""; }; 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordSubClassTests.swift; sourceTree = ""; }; @@ -1626,6 +1667,14 @@ 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS5+QueryInterface.swift"; sourceTree = ""; }; 56CEB5401EAA359A00BFAF62 /* Column.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Column.swift; sourceTree = ""; }; 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpression.swift; sourceTree = ""; }; + 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Insert.swift"; sourceTree = ""; }; + 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Update.swift"; sourceTree = ""; }; + 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Save.swift"; sourceTree = ""; }; + 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Delete.swift"; sourceTree = ""; }; + 56D110D228AFC81400E64463 /* PersistableRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; + 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Insert.swift"; sourceTree = ""; }; + 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Save.swift"; sourceTree = ""; }; + 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+DAO.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = ""; }; @@ -1657,6 +1706,8 @@ 56F61DD0283D344D00AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDBTests-Bridging-Header.h"; path = "GRDBTests/GRDBTests-Bridging-Header.h"; sourceTree = ""; }; 56F61DD3283D344E00AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = ""; }; 56F61DD4283D344E00AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; + 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Upsert.swift"; sourceTree = ""; }; + 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Upsert.swift"; sourceTree = ""; }; 56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; 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 = ""; }; @@ -1783,6 +1834,7 @@ 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */, 5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */, 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */, + 5615877F288D875E00A67323 /* Optional.swift */, 5605F1581C672E4000235C62 /* StandardLibrary.swift */, ); path = StandardLibrary; @@ -1874,7 +1926,6 @@ 56176C9E1EACEDF9000F3F2B /* Record */ = { isa = PBXGroup; children = ( - 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */, 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */, 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */, 56DA7CF6260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */, @@ -2404,7 +2455,17 @@ 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */, 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */, 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */, - 560D92441C672C4B00F4F92B /* PersistableRecord.swift */, + 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */, + 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */, + 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */, + 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */, + 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */, + 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */, + 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */, + 56D110D228AFC81400E64463 /* PersistableRecord.swift */, + 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */, + 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */, + 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, ); @@ -2423,14 +2484,6 @@ path = ValueReducer; sourceTree = ""; }; - 56D7E449221595FE0052464B /* Fixit */ = { - isa = PBXGroup; - children = ( - 567ECE4E2222E431009245CA /* GRDB-5.0.swift */, - ); - path = Fixit; - sourceTree = ""; - }; 56DAA2C41DE99D8D006E10C8 /* Cursor */ = { isa = PBXGroup; children = ( @@ -2526,8 +2579,8 @@ isa = PBXGroup; children = ( 56A2FA3524424D2A00E97D23 /* Export.swift */, + 566DDE0C288D763C0000DCFB /* Fixits.swift */, 56A2386F1B9C75030082EB20 /* Core */, - 56D7E449221595FE0052464B /* Fixit */, 5698AC291D9E5A480056AF8C /* FTS */, 56A238911B9C750B0082EB20 /* Migration */, 56300B6D1C53F592005A543B /* QueryInterface */, @@ -2754,7 +2807,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0730; - LastUpgradeCheck = 1200; + LastUpgradeCheck = 1400; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { 5654909F1D5A4798005622CB = { @@ -2942,6 +2995,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 56D110DF28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */, 5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 56256ED225D1ACD0008C2BDD /* Table.swift in Sources */, 56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, @@ -2953,18 +3007,23 @@ 564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 565490CF1D5AE252005622CB /* NSNumber.swift in Sources */, 56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 56158782288D875E00A67323 /* Optional.swift in Sources */, 56D91AA42205E03700770D8D /* SQLRelation.swift in Sources */, 565490E21D5AE252005622CB /* Record.swift in Sources */, 565490C11D5AE236005622CB /* FetchRequest.swift in Sources */, 568ECB1A25D9161600B71526 /* SQLSubquery.swift in Sources */, + 56D110D028AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */, 5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */, + 566DDE0F288D763C0000DCFB /* Fixits.swift in Sources */, 5656A8B22295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */, 56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 5653EB0B20944C7C00F46237 /* Association.swift in Sources */, + 56D110C128AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */, 564CE59F21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */, 56F5ABDA1D814330001F60CB /* NSData.swift in Sources */, + 56D110D528AFC81400E64463 /* PersistableRecord.swift in Sources */, 564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */, 5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 56894FD12606589C00268F4D /* Decimal.swift in Sources */, @@ -2973,6 +3032,7 @@ 56AE64142229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */, 5613ED3721A95A5C00DC7A68 /* Map.swift in Sources */, 5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */, + 56FA0C3228B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */, 564CE43321AA901800652B19 /* ValueConcurrentObserver.swift in Sources */, 563B8FC724A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */, 566B9C2225C6CC24004542CF /* RowDecodingError.swift in Sources */, @@ -2997,7 +3057,6 @@ 563EF45D2163309F007DAACD /* Inflections.swift in Sources */, 569D6DE0220EF9E100A058A9 /* SQLInterpolation.swift in Sources */, 5611620A25757583007AAF99 /* JoinAssociation.swift in Sources */, - 567ECE512222E431009245CA /* GRDB-5.0.swift in Sources */, 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */, 566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 560233C62724234F00529DF3 /* SharedValueObservation.swift in Sources */, @@ -3016,6 +3075,7 @@ 56DDDDF6242F87C70025E381 /* ValueObservationScheduler.swift in Sources */, 5659F49E1EA8D989004A4992 /* Pool.swift in Sources */, 5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */, + 56D110DA28AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */, 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */, 563B8FAE24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */, 565490CA1D5AE252005622CB /* DatabaseDateComponents.swift in Sources */, @@ -3043,17 +3103,20 @@ 56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */, 56F5ABD91D814330001F60CB /* Data.swift in Sources */, 565490D41D5AE252005622CB /* (null) in Sources */, + 56D110FC28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */, 56713FDF2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */, 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 565490B61D5AE236005622CB /* Configuration.swift in Sources */, - 565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */, + 565490E11D5AE252005622CB /* MutablePersistableRecord.swift in Sources */, 569BBA50229170FA00478429 /* Inflections+English.swift in Sources */, 563B8FB724A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */, 566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, + 56FA0C3B28B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */, 565490C81D5AE252005622CB /* CGFloat.swift in Sources */, 56F5ABDC1D814330001F60CB /* URL.swift in Sources */, 569EF0E4200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, 5695962B222C462D002CB7C9 /* HasManyThroughAssociation.swift in Sources */, + 56D110C628AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */, 565490D31D5AE252005622CB /* (null) in Sources */, 566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 56AACAAA22ACED7100A40F2A /* Fetch.swift in Sources */, @@ -3076,6 +3139,7 @@ 565490CD1D5AE252005622CB /* Date.swift in Sources */, 5653EB0820944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */, 565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */, + 56D110CB28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -3102,12 +3166,14 @@ files = ( 568ECAA025D7E53E00B71526 /* SQLOrdering.swift in Sources */, 56713FDE2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */, + 56158781288D875E00A67323 /* Optional.swift in Sources */, 5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */, 563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */, 56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 563B8FC624A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */, 56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 5656A8B12295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */, + 566DDE0E288D763C0000DCFB /* Fixits.swift in Sources */, 56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */, 5674A6F91F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */, @@ -3115,6 +3181,7 @@ 56012BA8257404E000B4925B /* CommonTableExpression.swift in Sources */, 56256ED125D1ACD0008C2BDD /* Table.swift in Sources */, 5653EB0A20944C7C00F46237 /* Association.swift in Sources */, + 56D110FB28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */, 56A2387E1B9C75030082EB20 /* Database.swift in Sources */, 56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5605F15A1C672E4000235C62 /* CGFloat.swift in Sources */, @@ -3122,11 +3189,13 @@ 5605F1641C672E4000235C62 /* Date.swift in Sources */, 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 564CE43221AA901800652B19 /* ValueConcurrentObserver.swift in Sources */, + 56D110D928AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */, 568ECA8B25D7013000B71526 /* SQLSelection.swift in Sources */, 56AACAA922ACED7100A40F2A /* Fetch.swift in Sources */, 5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */, 566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, + 56D110CF28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */, 5659F49B1EA8D989004A4992 /* Pool.swift in Sources */, 5653EB2220944C7C00F46237 /* HasOneAssociation.swift in Sources */, 563082E52430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */, @@ -3136,6 +3205,7 @@ 568D13202207213E00674B58 /* SQLQueryGenerator.swift in Sources */, 5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 563EF416215F87EB007DAACD /* OrderedDictionary.swift in Sources */, + 56FA0C3A28B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */, 563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */, 5698AD1B1DAAD17D0056AF8C /* FTS5Tokenizer.swift in Sources */, 5653EB0420944C7C00F46237 /* BelongsToAssociation.swift in Sources */, @@ -3146,6 +3216,7 @@ 56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5605F16A1C672E4000235C62 /* NSString.swift in Sources */, 566B910C1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, + 56D110DE28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */, 56A8C2331D1914540096E9D4 /* UUID.swift in Sources */, 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, @@ -3159,14 +3230,17 @@ 4E13D2F42769B87F0037588C /* DatabaseBackupProgress.swift in Sources */, 5656A81F2295B12F001FF3FF /* SQLAssociation.swift in Sources */, 5617294F223533F40006E219 /* EncodableRecord.swift in Sources */, + 56FA0C3128B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */, 563B8FAD24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */, 5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */, + 56D110CA28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */, 5659F48B1EA8D94E004A4992 /* Utils.swift in Sources */, 56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */, 56DAA2DE1DE9C827006E10C8 /* Cursor.swift in Sources */, 560A37A51C8F625000949E71 /* DatabasePool.swift in Sources */, + 56D110D428AFC81400E64463 /* PersistableRecord.swift in Sources */, 56256EDA25D1B316008C2BDD /* ForeignKey.swift in Sources */, 5674A7081F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 56AE64132229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */, @@ -3184,6 +3258,7 @@ 5605F15E1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 5695962A222C462D002CB7C9 /* HasManyThroughAssociation.swift in Sources */, 563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */, + 56D110C528AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */, 56B964BC1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 5605F1661C672E4000235C62 /* NSNull.swift in Sources */, 5656A8AE2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */, @@ -3199,7 +3274,6 @@ 569D6DDF220EF9E100A058A9 /* SQLInterpolation.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */, - 567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */, 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 568ECB1925D9161600B71526 /* SQLSubquery.swift in Sources */, @@ -3211,9 +3285,10 @@ 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 563B8F93249E6171007A48C9 /* Trace.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, + 56D110C028AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */, 56E9FACC221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */, 566B9C2125C6CC24004542CF /* RowDecodingError.swift in Sources */, - 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, + 560D92481C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */, 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 56717272261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */, @@ -3333,7 +3408,6 @@ 56176C7F1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */, 56741EAC1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 5672DE5C1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, - 56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */, 56B86E7A220FF4E000524C16 /* SQLLiteralTests.swift in Sources */, 56176C6C1EACCCC9000F3F2B /* FTS5PatternTests.swift in Sources */, 56419C7024A519A3004967E1 /* Support.swift in Sources */, @@ -3643,7 +3717,6 @@ 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 */, 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */, @@ -3711,12 +3784,14 @@ files = ( 568ECAA225D7E53E00B71526 /* SQLOrdering.swift in Sources */, 56713FE02691F409006153C3 /* JSONRequiredEncoder.swift in Sources */, + 56158783288D875E00A67323 /* Optional.swift in Sources */, AAA4DC77230F1E0600C74B15 /* FetchRequest.swift in Sources */, AAA4DC78230F1E0600C74B15 /* AssociationAggregate.swift in Sources */, AAA4DC79230F1E0600C74B15 /* SchedulingWatchdog.swift in Sources */, 563B8FC824A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */, AAA4DC7A230F1E0600C74B15 /* QueryInterfaceRequest.swift in Sources */, AAA4DC7B230F1E0600C74B15 /* TableRecord+QueryInterfaceRequest.swift in Sources */, + 566DDE10288D763C0000DCFB /* Fixits.swift in Sources */, AAA4DC7C230F1E0600C74B15 /* SQLExpression.swift in Sources */, AAA4DC7D230F1E0600C74B15 /* EncodableRecord+Encodable.swift in Sources */, AAA4DC7F230F1E0600C74B15 /* SQLOperators.swift in Sources */, @@ -3724,6 +3799,7 @@ 56012BB2257404E200B4925B /* CommonTableExpression.swift in Sources */, 56256ED325D1ACD0008C2BDD /* Table.swift in Sources */, AAA4DC81230F1E0600C74B15 /* Association.swift in Sources */, + 56D110FD28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */, AAA4DC82230F1E0600C74B15 /* Database.swift in Sources */, AAA4DC83230F1E0600C74B15 /* FTS3.swift in Sources */, AAA4DC84230F1E0600C74B15 /* CGFloat.swift in Sources */, @@ -3731,11 +3807,13 @@ AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */, AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */, AAA4DC8A230F1E0600C74B15 /* ValueConcurrentObserver.swift in Sources */, + 56D110DB28AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */, 568ECA8D25D7013000B71526 /* SQLSelection.swift in Sources */, AAA4DC8B230F1E0600C74B15 /* Fetch.swift in Sources */, AAA4DC8C230F1E0600C74B15 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, AAA4DC8D230F1E0600C74B15 /* FTS3+QueryInterface.swift in Sources */, AAA4DC8E230F1E0600C74B15 /* SQLFunctions.swift in Sources */, + 56D110D128AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */, AAA4DC8F230F1E0600C74B15 /* Pool.swift in Sources */, AAA4DC90230F1E0600C74B15 /* HasOneAssociation.swift in Sources */, 563082E72430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */, @@ -3745,6 +3823,7 @@ AAA4DC94230F1E0600C74B15 /* SQLQueryGenerator.swift in Sources */, AAA4DC95230F1E0600C74B15 /* RowAdapter.swift in Sources */, AAA4DC96230F1E0600C74B15 /* OrderedDictionary.swift in Sources */, + 56FA0C3C28B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */, AAA4DC97230F1E0600C74B15 /* DatabaseWriter.swift in Sources */, AAA4DC98230F1E0600C74B15 /* FTS5Tokenizer.swift in Sources */, AAA4DC99230F1E0600C74B15 /* BelongsToAssociation.swift in Sources */, @@ -3755,6 +3834,7 @@ AAA4DC9E230F1E0600C74B15 /* DatabaseMigrator.swift in Sources */, AAA4DC9F230F1E0600C74B15 /* NSString.swift in Sources */, AAA4DCA0230F1E0600C74B15 /* Database+Statements.swift in Sources */, + 56D110E028AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */, AAA4DCA1230F1E0600C74B15 /* UUID.swift in Sources */, AAA4DCA2230F1E0600C74B15 /* DatabaseValueConvertible.swift in Sources */, AAA4DCA4230F1E0600C74B15 /* Record.swift in Sources */, @@ -3768,14 +3848,17 @@ 4E13D2F62769B87F0037588C /* DatabaseBackupProgress.swift in Sources */, AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */, AAA4DCAA230F1E0600C74B15 /* EncodableRecord.swift in Sources */, + 56FA0C3328B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */, 563B8FAF24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */, AAA4DCAC230F1E0600C74B15 /* SQLGenerationContext.swift in Sources */, AAA4DCAD230F1E0600C74B15 /* URL.swift in Sources */, AAA4DCAE230F1E0600C74B15 /* RequestProtocols.swift in Sources */, + 56D110CC28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */, AAA4DCAF230F1E0600C74B15 /* Utils.swift in Sources */, AAA4DCB0230F1E0600C74B15 /* Configuration.swift in Sources */, AAA4DCB1230F1E0600C74B15 /* Cursor.swift in Sources */, AAA4DCB2230F1E0600C74B15 /* DatabasePool.swift in Sources */, + 56D110D628AFC81400E64463 /* PersistableRecord.swift in Sources */, 56256EDC25D1B316008C2BDD /* ForeignKey.swift in Sources */, AAA4DCB3230F1E0600C74B15 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, AAA4DCB4230F1E0600C74B15 /* HasOneThroughAssociation.swift in Sources */, @@ -3793,6 +3876,7 @@ AAA4DCC4230F1E0600C74B15 /* DatabaseDateComponents.swift in Sources */, AAA4DCC5230F1E0600C74B15 /* HasManyThroughAssociation.swift in Sources */, AAA4DCC6230F1E0600C74B15 /* DatabaseReader.swift in Sources */, + 56D110C728AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */, AAA4DCC8230F1E0600C74B15 /* FTS5Pattern.swift in Sources */, AAA4DCC9230F1E0600C74B15 /* NSNull.swift in Sources */, AAA4DCCA230F1E0600C74B15 /* TableRecord+Association.swift in Sources */, @@ -3808,7 +3892,6 @@ AAA4DCD0230F1E0600C74B15 /* SQLInterpolation.swift in Sources */, AAA4DCD1230F1E0600C74B15 /* DatabaseError.swift in Sources */, AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */, - AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */, AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */, AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */, 568ECB1B25D9161600B71526 /* SQLSubquery.swift in Sources */, @@ -3820,9 +3903,10 @@ AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */, 563B8F95249E6171007A48C9 /* Trace.swift in Sources */, AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */, + 56D110C228AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */, AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */, 566B9C2325C6CC24004542CF /* RowDecodingError.swift in Sources */, - AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */, + AAA4DCDF230F1E0600C74B15 /* MutablePersistableRecord.swift in Sources */, AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */, AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */, 56717274261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */, @@ -3942,7 +4026,6 @@ AAA4DD5A230F262000C74B15 /* EncryptionTests.swift in Sources */, AAA4DD5B230F262000C74B15 /* FetchRequestTests.swift in Sources */, AAA4DD5C230F262000C74B15 /* DatabaseQueueBackupTests.swift in Sources */, - AAA4DD5D230F262000C74B15 /* RecordCopyTests.swift in Sources */, AAA4DD5E230F262000C74B15 /* SQLLiteralTests.swift in Sources */, AAA4DD5F230F262000C74B15 /* FTS5PatternTests.swift in Sources */, 56419C7524A519A4004967E1 /* Support.swift in Sources */, @@ -4084,12 +4167,14 @@ files = ( 568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */, 56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */, + 56158780288D875E00A67323 /* Optional.swift in Sources */, 563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */, 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */, 5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */, 5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */, + 566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */, 56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 563EF44A2161F179007DAACD /* Inflections.swift in Sources */, 566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */, @@ -4097,6 +4182,7 @@ 56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */, 56256ED025D1ACD0008C2BDD /* Table.swift in Sources */, 563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */, + 56D110FA28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */, 56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */, 5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, @@ -4104,11 +4190,13 @@ 56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */, 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, + 56D110D828AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */, 568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */, 56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */, 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, + 56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */, 563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */, 564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */, 5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -4118,6 +4206,7 @@ 5605F1631C672E4000235C62 /* Date.swift in Sources */, 5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */, + 56FA0C3928B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */, 566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 5698AC371D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */, @@ -4128,6 +4217,7 @@ 56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */, 5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, + 56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */, 567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */, @@ -4141,14 +4231,17 @@ 4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */, 560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, 563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */, + 56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */, 5605F1691C672E4000235C62 /* NSString.swift in Sources */, 560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, 56A8C2301D1914540096E9D4 /* UUID.swift in Sources */, 56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */, + 56D110C928AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */, 56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */, 56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */, 56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */, 56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, + 56D110D328AFC81400E64463 /* PersistableRecord.swift in Sources */, 5653EB0920944C7C00F46237 /* Association.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, @@ -4166,6 +4259,7 @@ 566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56A2388B1B9C75030082EB20 /* Statement.swift in Sources */, 5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */, + 56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */, 5690C3401D23E82A00E59934 /* Data.swift in Sources */, 5659F4881EA8D94E004A4992 /* Utils.swift in Sources */, 566BE71E2342542F00A8254B /* LockedBox.swift in Sources */, @@ -4176,7 +4270,6 @@ 569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */, 568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */, 5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, - 567ECE4F2222E431009245CA /* GRDB-5.0.swift in Sources */, 56894FB72606589700268F4D /* Decimal.swift in Sources */, 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */, @@ -4193,6 +4286,7 @@ 5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 56D110BF28AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */, 566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */, 5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, @@ -4205,7 +4299,7 @@ 5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */, 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */, 5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */, - 560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */, + 560D92471C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */, 5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 5657AAB91D107001006283EF /* NSData.swift in Sources */, @@ -4307,6 +4401,7 @@ buildSettings = { CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; @@ -4328,6 +4423,7 @@ CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; @@ -4471,6 +4567,7 @@ CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; @@ -4497,6 +4594,7 @@ CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; @@ -4671,6 +4769,7 @@ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; + DEAD_CODE_STRIPPING = YES; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; @@ -4728,6 +4827,7 @@ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = YES; CURRENT_PROJECT_VERSION = 1; + DEAD_CODE_STRIPPING = YES; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; @@ -4757,6 +4857,7 @@ CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; @@ -4782,6 +4883,7 @@ CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; diff --git a/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSX.xcscheme b/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSX.xcscheme index 31044ab87..15e6e43c0 100644 --- a/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSX.xcscheme +++ b/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSX.xcscheme @@ -1,6 +1,6 @@ - - diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 7c7e7f0d3..c18cf147e 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -196,7 +196,7 @@ public struct Configuration { /// /// For example: /// - /// let dbQueue = DatabaseQueue() + /// let dbQueue = try DatabaseQueue() /// /// // fatal error: A transaction has been left opened at the end of a database access /// try dbQueue.inDatabase { db in @@ -208,7 +208,7 @@ public struct Configuration { /// /// var config = Configuration() /// config.allowsUnsafeTransactions = true - /// let dbQueue = DatabaseQueue(configuration: config) + /// let dbQueue = try DatabaseQueue(configuration: config) /// /// try dbQueue.inDatabase { db in /// try db.beginTransaction() @@ -295,7 +295,7 @@ public struct Configuration { var SQLiteConnectionDidOpen: (() -> Void)? var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)? var SQLiteConnectionDidClose: (() -> Void)? - var SQLiteOpenFlags: Int32 { + var SQLiteOpenFlags: CInt { let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE) return threadingMode.SQLiteOpenFlags | readWriteFlags } diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index bc4fdc94b..1917fd483 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -19,12 +19,9 @@ extension RangeReplaceableCollection { /// let strings = try Array(cursor) /// /// - parameter cursor: The cursor whose elements feed the collection. - public init(_ cursor: C) throws where C.Element == Element { + public init(_ cursor: some Cursor) throws { self.init() - // Prefer `forEach` over `next()` looping, as a slight performance - // improvement due to the single `sqlite3_stmt_busy` check for - // database cursors. - try cursor.forEach { append($0) } + try append(contentsOf: cursor) } /// Creates a collection containing the elements of a cursor. @@ -36,13 +33,23 @@ extension RangeReplaceableCollection { /// - parameter cursor: The cursor whose elements feed the collection. /// - parameter minimumCapacity: Prepares the returned collection to store /// the specified number of elements. - public init(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element { + public init(_ cursor: some Cursor, minimumCapacity: Int) throws { self.init() reserveCapacity(minimumCapacity) + try append(contentsOf: cursor) + } + + /// Adds the elements of a cursor to the end of this collection. + /// + /// In case of error, an unspecified amount of elements have been added to + /// the collection. + /// + /// - parameter newElements: The elements to append to the collection. + public mutating func append(contentsOf newElements: some Cursor) throws { // Prefer `forEach` over `next()` looping, as a slight performance // improvement due to the single `sqlite3_stmt_busy` check for // database cursors. - try cursor.forEach { append($0) } + try newElements.forEach { append($0) } } } @@ -112,9 +119,7 @@ extension Dictionary { /// - parameter keysAndValues: A cursor of key-value pairs to use for the /// new dictionary. Every key in `keysAndValues` must be unique. /// - precondition: The cursor must not have duplicate keys. - public init(uniqueKeysWithValues keysAndValues: C) - throws where C.Element == (Key, Value) - { + public init(uniqueKeysWithValues keysAndValues: some Cursor<(Key, Value)>) throws { self.init() // Prefer `forEach` over `next()` looping, as a slight performance // improvement due to the single `sqlite3_stmt_busy` check for @@ -144,9 +149,7 @@ extension Dictionary { /// - parameter keysAndValues: A cursor of key-value pairs to use for the /// new dictionary. Every key in `keysAndValues` must be unique. /// - precondition: The cursor must not have duplicate keys. - public init(minimumCapacity: Int, uniqueKeysWithValues keysAndValues: C) - throws where C.Element == (Key, Value) - { + public init(minimumCapacity: Int, uniqueKeysWithValues keysAndValues: some Cursor<(Key, Value)>) throws { self.init(minimumCapacity: minimumCapacity) // Prefer `forEach` over `next()` looping, as a slight performance // improvement due to the single `sqlite3_stmt_busy` check for @@ -167,7 +170,7 @@ extension Set { /// let strings = try Set(cursor) /// /// - parameter cursor: A cursor of values to gather into a set. - public init(_ cursor: C) throws where C.Element == Element { + public init(_ cursor: some Cursor) throws { self.init() // Prefer `forEach` over `next()` looping, as a slight performance // improvement due to the single `sqlite3_stmt_busy` check for @@ -185,7 +188,7 @@ extension Set { /// - parameter minimumCapacity: The minimum number of elements that the /// newly created set should be able to store without reallocating its /// storage buffer. - public init(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element { + public init(_ cursor: some Cursor, minimumCapacity: Int) throws { self.init(minimumCapacity: minimumCapacity) // Prefer `forEach` over `next()` looping, as a slight performance // improvement due to the single `sqlite3_stmt_busy` check for @@ -234,7 +237,7 @@ extension Sequence { /// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, /// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, /// `suffix`. -public protocol Cursor: AnyObject { +public protocol Cursor: AnyObject { /// The type of element traversed by the cursor. associatedtype Element @@ -247,10 +250,12 @@ public protocol Cursor: AnyObject { } extension Cursor { - /// Returns a Boolean value indicating whether the cursor contains - /// an element. - public func isEmpty() throws -> Bool { - try next() == nil + /// Returns a Boolean value indicating whether the cursor does not contain + /// any element. + /// + /// - important: This property may consume elements. + public var isEmpty: Bool { + get throws { try next() == nil } } /// Returns a Boolean value indicating whether the cursor contains an @@ -311,7 +316,7 @@ extension Cursor { /// Returns a cursor that skips any initial elements that satisfy /// `predicate`. /// - /// - Parameter predicate: A closure that takes an element of the cursir as + /// - Parameter predicate: A closure that takes an element of the cursor as /// its argument and returns `true` if the element should be skipped or /// `false` otherwise. Once `predicate` returns `false` it will not be /// called again. @@ -685,14 +690,14 @@ public final class AnyCursor: Cursor { /// Creates a cursor that wraps a base iterator but whose type depends only /// on the base iterator’s element type - public convenience init(iterator: I) where I.Element == Element { + public convenience init(iterator: some IteratorProtocol) { var iterator = iterator self.init { iterator.next() } } /// Creates a cursor that wraps a base sequence but whose type depends only /// on the base sequence’s element type - public convenience init(_ s: S) where S.Element == Element { + public convenience init(_ s: some Sequence) { self.init(iterator: s.makeIterator()) } diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index ac584849f..84f0a55a9 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -1,5 +1,30 @@ extension Database { - /// A SQLite schema. See + /// A cache for the available database schemas. + struct SchemaCache { + /// The available schema identifiers, in the order of SQLite resolution: + /// temp, main, then attached databases. + var schemaIdentifiers: [SchemaIdentifier]? + + /// The schema cache for each identifier. + fileprivate var schemas: [SchemaIdentifier: DatabaseSchemaCache] = [:] + + /// The schema cache for a given identifier + subscript(schemaID: SchemaIdentifier) -> DatabaseSchemaCache { // internal so that it can be tested + get { + schemas[schemaID] ?? DatabaseSchemaCache() + } + set { + schemas[schemaID] = newValue + } + } + + mutating func clear() { + schemaIdentifiers = nil + schemas.removeAll() + } + } + + /// An SQLite schema. See enum SchemaIdentifier: Hashable { /// The main database case main @@ -10,7 +35,12 @@ extension Database { /// An attached database: case attached(String) - /// The name of the schema in SQL queries + /// The name of the schema in SQL queries. + /// + /// For example: + /// + /// SELECT * FROM main.player; + /// -- ~~~~ var sql: String { switch self { case .main: return "main" @@ -29,12 +59,12 @@ extension Database { } } - /// A table identifier + /// The identifier of a database table or view. struct TableIdentifier { /// The SQLite schema var schemaID: SchemaIdentifier - /// The table name + /// The table or view name var name: String /// Returns the receiver, quoted for safe insertion as an identifier in @@ -60,7 +90,7 @@ extension Database { // 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. + // limited number of times (`SQLITE_MAX_SCHEMA_RETRY`). internalStatementCache.clear() publicStatementCache.clear() } @@ -68,9 +98,13 @@ extension Database { /// Clears the database schema cache if the database schema has changed /// since this method was last called. func clearSchemaCacheIfNeeded() throws { + // `PRAGMA schema_version` fetches a 4-bytes integer (Int32), stored + // at offset 40 of the database header: + // + // let schemaVersion = try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version")) - if _lastSchemaVersion != schemaVersion { - _lastSchemaVersion = schemaVersion + if lastSchemaVersion != schemaVersion { + lastSchemaVersion = schemaVersion clearSchemaCache() } } @@ -82,17 +116,17 @@ extension Database { return schemaIdentifiers } - var schemaIdentifiers = try Row - .fetchAll(self, sql: "PRAGMA database_list") + var schemaIdentifiers = try Array(Row + .fetchCursor(self, sql: "PRAGMA database_list") .map { row -> SchemaIdentifier in switch row[1] as String { case "main": return .main case "temp": return .temp case let other: return .attached(other) } - } + }) - // Temp schema shadows other schema: put it first + // Temp schema shadows all other schemas: put it first if let tempIdx = schemaIdentifiers.firstIndex(of: .temp) { schemaIdentifiers.swapAt(tempIdx, 0) } @@ -101,7 +135,8 @@ extension Database { return schemaIdentifiers } - /// Returns whether a table exists in the main or temp schema. + /// Returns whether a table exists, in the main or temp schema, or in an + /// attached database. public func tableExists(_ name: String) throws -> Bool { try schemaIdentifiers().contains { try exists(type: .table, name: name, in: $0) @@ -126,17 +161,7 @@ extension Database { // > "sqlite_". tableName.starts(with: "sqlite_") || tableName.starts(with: "pragma_") } - - /// Returns whether a table is an internal SQLite table. - /// - /// Those are tables whose name begins with `sqlite_` and `pragma_`. - /// - /// For more information, see - @available(*, deprecated, message: "Use Database.isSQLiteInternalTable(_:) static method instead.") - public func isSQLiteInternalTable(_ tableName: String) -> Bool { - Self.isSQLiteInternalTable(tableName) - } - + /// Returns whether a table is an internal GRDB table. /// /// Those are tables whose name begins with "grdb_". @@ -144,22 +169,16 @@ extension Database { tableName.starts(with: "grdb_") } - /// Returns whether a table is an internal GRDB table. - /// - /// Those are tables whose name begins with "grdb_". - @available(*, deprecated, message: "Use Database.isGRDBInternalTable(_:) static method instead.") - public func isGRDBInternalTable(_ tableName: String) -> Bool { - Self.isGRDBInternalTable(tableName) - } - - /// Returns whether a view exists in the main or temp schema. + /// Returns whether a view exists, in the main or temp schema, or in an + /// attached database. public func viewExists(_ name: String) throws -> Bool { try schemaIdentifiers().contains { try exists(type: .view, name: name, in: $0) } } - /// Returns whether a trigger exists in the main or temp schema. + /// Returns whether a trigger exists, in the main or temp schema, or in an + /// attached database. public func triggerExists(_ name: String) throws -> Bool { try schemaIdentifiers().contains { try exists(type: .trigger, name: name, in: $0) @@ -167,12 +186,9 @@ extension Database { } private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool { - // SQlite identifiers are case-insensitive, case-preserving: + // SQLite identifiers are case-insensitive, case-preserving: // http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html - let name = name.lowercased() - return try schema(schemaID) - .names(ofType: type) - .contains { $0.lowercased() == name } + try schema(schemaID).containsObjectNamed(name, ofType: type) } /// The primary key for table named `tableName`. @@ -246,7 +262,7 @@ extension Database { primaryKey = .hiddenRowID case 1: // Single column - let pkColumn = pkColumns.first! + let pkColumn = pkColumns[0] // https://www.sqlite.org/lang_createtable.html: // @@ -292,12 +308,21 @@ extension Database { /// /// - precondition: table exists. private func tableHasRowID(_ table: TableIdentifier) throws -> Bool { - // Not need to cache the result, because this information feeds + // No need to cache the result, because this information feeds // `PrimaryKeyInfo`, which is cached. // - // Use a distinctive alias so that we better understand in the - // future why this query appears in the error log. - // https://github.com/groue/GRDB.swift/issues/945#issuecomment-804896196 + // To check if the table has a rowid, we compile a statement that + // selects the `rowid` column. If compilation fails, we assume that the + // table is WITHOUT ROWID. This is not a very robust test (users may + // create WITHOUT ROWID tables with a `rowid` column), but nobody has + // reported any problem yet. + // + // Since compilation may fail, we may feed the SQLite error log, and + // users may wonder what are those errors. That's why we use a + // distinctive alias (`checkWithoutRowidOptimization`), so that anyone + // can search the GRDB code, find this documentation, and understand why + // this query appears in the error log: + // // // We don't use `try makeStatement(sql:)` in order to avoid throwing an // error (this annoys users who set a breakpoint on Swift errors). @@ -316,8 +341,9 @@ extension Database { /// SQLite does not define any index for INTEGER PRIMARY KEY columns: this /// method does not return any index that represents the primary key. /// - /// If you want to know if a set of columns uniquely identify a row, prefer - /// `table(_:hasUniqueKey:)` instead. + /// If you want to know if a set of columns uniquely identifies a row, because + /// the columns contain the primary key or a unique index, use + /// ``table(_:hasUniqueKey:)``. /// /// - throws: A DatabaseError if table does not exist. public func indexes(on tableName: String) throws -> [IndexInfo] { @@ -341,6 +367,7 @@ extension Database { .compactMap { row -> IndexInfo? in let indexName: String = row[1] let unique: Bool = row[2] + let origin: IndexInfo.Origin = row[3] let indexInfoRows = try Row // [seqno:0 cid:2 name:"column"] @@ -362,7 +389,7 @@ extension Database { } columns.append(column) } - return IndexInfo(name: indexName, columns: columns, unique: unique) + return IndexInfo(name: indexName, columns: columns, isUnique: unique, origin: origin) } if indexes.isEmpty { @@ -379,12 +406,21 @@ extension Database { } /// True if a sequence of columns uniquely identifies a row, that is to say - /// if the columns are the primary key, or if there is a unique index on them. - public func table( + /// if the columns contain the primary key, or a unique index. + /// + /// For example: + /// + /// // CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c); + /// // CREATE UNIQUE INDEX i ON t(a, b); + /// try db.table("t", hasUniqueKey: ["id"]) // true + /// try db.table("t", hasUniqueKey: ["a", "b"]) // true + /// try db.table("t", hasUniqueKey: ["c"]) // false + /// try db.table("t", hasUniqueKey: ["id", "a"]) // true + /// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true + public func table( _ tableName: String, - hasUniqueKey columns: T) + hasUniqueKey columns: some Sequence) throws -> Bool - where T.Iterator.Element == String { try columnsForUniqueKey(Array(columns), in: tableName) != nil } @@ -481,6 +517,12 @@ extension Database { throw DatabaseError.noSuchTable(tableName) } + private func foreignKeyViolations(in table: TableIdentifier) throws -> RecordCursor { + try ForeignKeyViolation.fetchCursor(self, sql: """ + PRAGMA \(table.schemaID.sql).foreign_key_check(\(table.name.quotedDatabaseIdentifier)) + """) + } + /// Throws a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY` /// if there exists a foreign key violation in the database. public func checkForeignKeys() throws { @@ -493,20 +535,14 @@ extension Database { try checkForeignKeys(from: foreignKeyViolations(in: tableName)) } - private func foreignKeyViolations(in table: TableIdentifier) throws -> RecordCursor { - try ForeignKeyViolation.fetchCursor(self, sql: """ - PRAGMA \(table.schemaID.sql).foreign_key_check(\(table.name.quotedDatabaseIdentifier)) - """) - } - private func checkForeignKeys(from violations: RecordCursor) throws { if let violation = try violations.next() { throw violation.databaseError(self) } } - /// Returns the actual name of the database table, in the main or temp - /// schema, or nil if the table does not exist. + /// Returns the actual name of the database table, or nil if the table does + /// not exist. /// /// - throws: A DatabaseError if table does not exist. func canonicalTableName(_ tableName: String) throws -> String? { @@ -590,14 +626,6 @@ extension Database { // 2 | lastName | TEXT | 0 | NULL | 0 | 0 let columnInfoQuery: String if sqlite3_libversion_number() < 3026000 { - if sqlite3_libversion_number() < 3008005 { - // Work around a bug in SQLite where PRAGMA table_info would - // return a result even after the table was deleted. - if try !tableExists(table) { - schemaCache[table.schemaID].set(columns: .missing, forTable: table.name) - return nil - } - } columnInfoQuery = "PRAGMA \(table.schemaID.sql).table_info(\(table.name.quotedDatabaseIdentifier))" } else { // Use PRAGMA table_xinfo so that we can load generated columns @@ -625,14 +653,14 @@ extension Database { return columns } - /// If there exists a unique key on columns, return the columns - /// ordered as the matching index (or primary key). Case of returned columns - /// is not guaranteed. - func columnsForUniqueKey( - _ columns: T, + /// If there exists a unique key that contains those columns, this method + /// returns the columns of the unique key, ordered as the matching index (or + /// primary key). The case of returned columns is not guaranteed to match + /// the case of input columns. + func columnsForUniqueKey( + _ columns: some Sequence, in tableName: String) throws -> [String]? - where T.Iterator.Element == String { let lowercasedColumns = Set(columns.map { $0.lowercased() }) if lowercasedColumns.isEmpty { @@ -640,25 +668,26 @@ extension Database { return nil } - // Assume "rowid" is a primary key - if lowercasedColumns == ["rowid"] { + // Check rowid + let primaryKey = try self.primaryKey(tableName) + if primaryKey.tableHasRowID && lowercasedColumns == ["rowid"] { return ["rowid"] } - // Check primaryKey. - let primaryKey = try self.primaryKey(tableName) + // Check primaryKey if Set(primaryKey.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns) { return primaryKey.columns } - // Is there is an explicit unique index on the columns? - let indexes = try self.indexes(on: tableName) - let matchingIndex = indexes.first { index in + // Check unique indexes + let matchingIndex = try indexes(on: tableName).first { index in index.isUnique && Set(index.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns) } - if let index = matchingIndex { - return index.columns + if let matchingIndex { + return matchingIndex.columns } + + // No matching unique key found return nil } @@ -671,12 +700,21 @@ extension Database { let primaryKey = try self.primaryKey(tableName) if let rowIDColumn = primaryKey.rowIDColumn { // Prefer the user-provided name of the rowid + // + // // CREATE TABLE player (id INTEGER PRIMARY KEY, ...) + // try db.existenceCheckColumns(in: "player") // ["id"] return [rowIDColumn] } else if primaryKey.tableHasRowID { // Prefer the rowid + // + // // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...) + // try db.existenceCheckColumns(in: "player") // ["rowid"] return [Column.rowID.name] } else { // WITHOUT ROWID table: use primary key columns + // + // // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...) WITHOUT ROWID + // try db.existenceCheckColumns(in: "player") // ["uuid"] return primaryKey.columns } } else { @@ -733,6 +771,9 @@ public struct ColumnInfo: FetchableRecord { /// expression may be a literal, as `1`, or `'foo'`. It may also contain a /// non-constant expression such as `CURRENT_TIMESTAMP`. /// + /// For more information, see + /// . + /// /// For example: /// /// try db.execute(sql: """ @@ -745,22 +786,13 @@ public struct ColumnInfo: FetchableRecord { /// """) /// let columnInfos = try db.columns(in: "player") /// columnInfos[0].defaultValueSQL // nil - /// columnInfos[1].defaultValueSQL // "'Anoynymous'" + /// columnInfos[1].defaultValueSQL // "'Anonymous'" /// columnInfos[2].defaultValueSQL // "0" /// columnInfos[3].defaultValueSQL // "CURRENT_TIMESTAMP" public let defaultValueSQL: String? - /// Zero for columns that are not part of the primary key. - /// - /// Before SQLite 3.7.16, it is 1 for columns that are part of the - /// primary key. - /// - /// Starting from SQLite 3.7.16, it is the one-based index of the column in - /// the primary key for columns that are part of the primary key. - /// - /// References: - /// - - /// - + /// For columns that are part of the primary key, this is the one-based + /// index of the column in the primary key. For other columns, it is zero. public let primaryKeyIndex: Int /// :nodoc: @@ -779,6 +811,26 @@ public struct ColumnInfo: FetchableRecord { /// /// See `Database.indexes(on:)` public struct IndexInfo { + /// The origin of an index. + /// + /// See ``Database/indexes(on:)``. + public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible { + public var rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } + + /// An index created from a CREATE INDEX statement. + public static let createIndex = Origin(rawValue: "c") + + /// An index created by a UNIQUE constraint. + public static let uniqueConstraint = Origin(rawValue: "u") + + /// An index created by a PRIMARY KEY constraint. + public static let primaryKeyConstraint = Origin(rawValue: "pk") + } + /// The name of the index public let name: String @@ -788,11 +840,8 @@ public struct IndexInfo { /// True if the index is unique public let isUnique: Bool - init(name: String, columns: [String], unique: Bool) { - self.name = name - self.columns = columns - self.isUnique = unique - } + /// The origin of the index + public let origin: Origin } /// A foreign key violation produced by PRAGMA foreign_key_check @@ -998,14 +1047,24 @@ public struct PrimaryKeyInfo { var fastPrimaryKeyColumn: String? { if let rowIDColumn = rowIDColumn { // Prefer the user-provided name of the rowid + // + // // CREATE TABLE player (id INTEGER PRIMARY KEY, ...) + // try db.primaryKey("player").fastPrimaryKeyColumn // "id" return rowIDColumn } else if tableHasRowID { // Prefer the rowid + // + // // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...) + // try db.primaryKey("player").fastPrimaryKeyColumn // "rowid" return Column.rowID.name } else if columns.count == 1 { // WITHOUT ROWID table: use primary key column + // + // // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...) WITHOUT ROWID + // try db.primaryKey("player").fastPrimaryKeyColumn // "uuid" return columns[0] } else { + // WITHOUT ROWID table with a multi-columns primary key return nil } } @@ -1041,6 +1100,7 @@ enum SchemaObjectType: String { case view } +/// All objects in a database schema (tables, views, indexes, triggers). struct SchemaInfo: Equatable { private var objects: Set @@ -1051,12 +1111,13 @@ struct SchemaInfo: Equatable { """) } - /// All names for a given type - func names(ofType type: SchemaObjectType) -> Set { - objects.reduce(into: []) { (set, key) in - if key.type == type.rawValue { - set.insert(key.name) - } + /// Returns whether there exists a object of given type with this name + /// (case-insensitive). + func containsObjectNamed(_ name: String, ofType type: SchemaObjectType) -> Bool { + let name = name.lowercased() + let type = type.rawValue + return objects.contains { + $0.type == type && $0.name.lowercased() == name } } diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index c91d7fe3d..e6b4d17cd 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -6,6 +6,8 @@ extension Database { /// Returns a new prepared statement that can be reused. /// + /// For example: + /// /// 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])! @@ -23,6 +25,8 @@ extension Database { /// Returns a new prepared statement that can be reused. /// + /// For example: + /// /// 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])! @@ -62,45 +66,7 @@ extension Database { /// Returns a new prepared statement that can be reused. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player WHERE id = ?") - /// let player1 = try Player.fetchOne(statement, arguments: [1])! - /// let player2 = try Player.fetchOne(statement, arguments: [2])! - /// - /// - parameter sql: An SQL query. - /// - returns: A Statement. - /// - throws: A DatabaseError whenever SQLite could not parse the sql query. - @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: 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 makeSelectStatement(literal: """ - /// SELECT COUNT(*) FROM player WHERE score > ? - /// """) - /// try makeSelectStatement(literal: """ - /// SELECT COUNT(*) FROM player WHERE score > \(1000) - /// """) - /// - /// // NOT OK - /// try makeSelectStatement(literal: """ - /// SELECT COUNT(*) FROM player - /// WHERE color = ? AND score > \(1000) - /// """) - @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. + /// For example: /// /// let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0) /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! @@ -111,7 +77,7 @@ extension Database { /// SQLite 3.20.0, see ) /// - returns: A Statement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. - func makeStatement(sql: String, prepFlags: Int32) throws -> Statement { + func makeStatement(sql: String, prepFlags: CUnsignedInt) throws -> Statement { let statements = SQLStatementCursor(database: self, sql: sql, arguments: nil, prepFlags: prepFlags) guard let statement = try statements.next() else { throw DatabaseError( @@ -145,6 +111,8 @@ extension Database { /// Returns a prepared statement that can be reused. /// + /// For example: + /// /// 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])! @@ -165,6 +133,8 @@ extension Database { /// Returns a prepared statement that can be reused. /// + /// For example: + /// /// 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])! @@ -202,140 +172,15 @@ extension Database { return statement } - /// Returns a prepared statement that can be reused. - /// - /// let statement = try db.cachedSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?") - /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! - /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! - /// - /// 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. - @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 internalCachedStatement(sql: String) throws -> Statement { try internalStatementCache.statement(sql) } - /// Returns a new prepared statement that can be reused. - /// - /// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)") - /// try statement.execute(arguments: ["Arthur"]) - /// try statement.execute(arguments: ["Barbara"]) - /// - /// - parameter sql: An SQL query. - /// - returns: An UpdateStatement. - /// - throws: A DatabaseError whenever SQLite could not parse the sql query. - @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: 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 makeUpdateStatement(literal: """ - /// UPDATE player SET name = ? - /// """) - /// try makeUpdateStatement(literal: """ - /// UPDATE player SET name = \("O'Brien") - /// """) - /// - /// // NOT OK - /// try makeUpdateStatement(literal: """ - /// UPDATE player SET name = ?, score = \(10) - /// """) - @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. - /// - /// let statement = try db.cachedUpdateStatement(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. - @available(*, deprecated, renamed: "cachedStatement(sql:)") - public func cachedUpdateStatement(sql: String) throws -> Statement { - try cachedStatement(sql: 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. /// + /// For example: + /// /// let statements = try db.allStatements(sql: """ /// INSERT INTO player (name) VALUES (?); /// INSERT INTO player (name) VALUES (?); @@ -420,6 +265,8 @@ extension Database { /// Executes one or several SQL statements, separated by semi-colons. /// + /// For example: + /// /// try db.execute( /// sql: "INSERT INTO player (name) VALUES (:name)", /// arguments: ["name": "Arthur"]) @@ -430,8 +277,6 @@ extension Database { /// INSERT INTO player (name) VALUES (?); /// """, arguments: ["Arthur", "Barbara", "O'Brien"]) /// - /// This method may throw a DatabaseError. - /// /// - parameters: /// - sql: An SQL query. /// - arguments: Statement arguments. @@ -455,8 +300,6 @@ extension Database { /// INSERT INTO player (name) VALUES (\("O'Brien")); /// """) /// - /// This method may throw a DatabaseError. - /// /// - parameter sqlLiteral: An `SQL` literal. /// - throws: A DatabaseError whenever an SQLite error occurs. public func execute(literal sqlLiteral: SQL) throws { @@ -467,17 +310,18 @@ extension Database { } } +/// A cursor over all statements in a SQL string. public class SQLStatementCursor: Cursor { private let database: Database private let cString: ContiguousArray - private let prepFlags: CInt + private let prepFlags: CUnsignedInt private let initialArgumentCount: Int? // Mutated by iteration private var offset: Int // offset in the C string private var arguments: StatementArguments? // Nil when arguments are set later - init(database: Database, sql: String, arguments: StatementArguments?, prepFlags: CInt = 0) { + init(database: Database, sql: String, arguments: StatementArguments?, prepFlags: CUnsignedInt = 0) { self.database = database self.cString = sql.utf8CString self.prepFlags = prepFlags @@ -488,27 +332,27 @@ public class SQLStatementCursor: Cursor { public func next() throws -> Statement? { guard offset < cString.count - 1 /* trailing \0 */ else { + // End of C string -> end of cursor. try checkArgumentsAreEmpty() return nil } return try cString.withUnsafeBufferPointer { buffer in - guard let baseAddress = buffer.baseAddress else { - // Should never happen since buffer contains at least - // the trailing \0 - return nil - } + let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0. + // Compile next statement var statementEnd: UnsafePointer? = nil - let compiledStatement = try Statement( + let statement = try Statement( database: database, statementStart: baseAddress + offset, statementEnd: &statementEnd, prepFlags: prepFlags) - offset = statementEnd! - baseAddress + // Advance to next statement + offset = statementEnd! - baseAddress // never nil because statement compilation did not fail. - guard let statement = compiledStatement else { + guard let statement else { + // No statement found -> end of cursor. try checkArgumentsAreEmpty() return nil } @@ -545,18 +389,22 @@ extension Database { /// Makes sure statement can be executed, and prepares database observation. @usableFromInline func statementWillExecute(_ statement: Statement) throws { - // Two things must prevent the statement from executing: aborted - // transactions, and database suspension. + // Aborted transactions prevent statement execution (see the + // documentation of this method for more information). try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments) + + // Suspended databases must not execute statements that create the risk + // of `0xdead10cc` exception (see the documentation of this method for + // more information). try checkForSuspensionViolation(from: statement) - // Database observation: record what the statement is looking at. + // Record the database region selected by the statement execution. if isRecordingSelectedRegion { selectedRegion.formUnion(statement.databaseRegion) } // Database observation: prepare transaction observers. - observationBroker.statementWillExecute(statement) + observationBroker?.statementWillExecute(statement) } /// May throw a cancelled commit error, if a transaction observer cancels @@ -567,13 +415,14 @@ extension Database { clearSchemaCache() } - try observationBroker.statementDidExecute(statement) + // Database observation: cleanup + 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 + func statementDidFail(_ statement: Statement, withResultCode resultCode: CInt) 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 // @@ -581,15 +430,25 @@ extension Database { 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) + // Extract values that may be modified by the user in their + // `TransactionObserver.databaseDidRollback(_:)` implementation + // (see below). + let message = lastErrorMessage + let arguments = statement.arguments + // Database observation: cleanup. + // + // If the statement failure is due to a transaction observer that has + // cancelled a transaction, this calls `TransactionObserver.databaseDidRollback(_:)`, + // and throws the user-provided cancelled commit error. + try observationBroker?.statementDidFail(statement) + + // Throw statement failure throw DatabaseError( resultCode: resultCode, - message: lastErrorMessage, + message: message, sql: statement.sql, - arguments: statement.arguments, + arguments: arguments, publicStatementArguments: configuration.publicStatementArguments) } } @@ -618,14 +477,12 @@ 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.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT) + let statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT)) #else let statement: Statement if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) { - // SQLite 3.24.0 or more - statement = try db.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT) + statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT)) } else { - // SQLite 3.19.3 or less statement = try db.makeStatement(sql: sql) } #endif diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index f935f7f17..b42479448 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -13,7 +13,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// You don't create a database directly. Instead, you use a DatabaseQueue, or /// a DatabasePool: /// -/// let dbQueue = DatabaseQueue(...) +/// let dbQueue = try DatabaseQueue(...) /// /// // The Database is the `db` in the closure: /// try dbQueue.write { db in @@ -26,8 +26,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - SQLite C API /// The raw SQLite connection, suitable for the SQLite C API. - /// It is constant, until close() sets it to nil. - public var sqliteConnection: SQLiteConnection? + /// + /// It is nil after the database has been successfully closed with + /// ``DatabaseReader/close()``. + public private(set) var sqliteConnection: SQLiteConnection? // MARK: - Configuration @@ -125,62 +127,84 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Internal properties - // Caches - struct SchemaCache { - var schemaIdentifiers: [SchemaIdentifier]? - fileprivate var schemas: [SchemaIdentifier: DatabaseSchemaCache] = [:] - - subscript(schemaID: SchemaIdentifier) -> DatabaseSchemaCache { // internal so that it can be tested - get { - schemas[schemaID] ?? DatabaseSchemaCache() - } - set { - schemas[schemaID] = newValue - } - } - - mutating func clear() { - schemaIdentifiers = nil - schemas.removeAll() - } - } + /// Support for schema changes performed with ``DatabasePool``: each read + /// access needs to clear the schema cache if the schema has been modified + /// by the writer connection since the previous read. This property is reset + /// to `PRAGMA schema_version` at the beginning of each DatabasePool read. + /// + /// DatabasePool writer connection and DatabaseQueue do not perform such + /// automatic schema management: they won't clear their schema cache if an + /// external connection modifies the schema. + /// + /// See `clearSchemaCacheIfNeeded()`. + var lastSchemaVersion: Int32? - var _lastSchemaVersion: Int32? // Support for clearSchemaCacheIfNeeded() + /// The cache for the available database schemas (main, temp, attached databases). var schemaCache = SchemaCache() + + /// The cache for statements managed by GRDB. It is distinct from + /// `publicStatementCache` so that we do not mess with statement arguments + /// set by the user. lazy var internalStatementCache = StatementCache(database: self) + + /// The cache for statements managed by the user. lazy var publicStatementCache = StatementCache(database: self) - // Database observation + /// The database authorizer provides information about compiled + /// database statements, and prevents the truncate optimization when + /// row deletions are observed by transaction observers. lazy var authorizer = StatementAuthorizer(self) - lazy var observationBroker = DatabaseObservationBroker(self) + + /// The observation broker supports database observation and + /// transaction observers. + /// + /// It is nil in read-only connections, because we do not report read-only + /// transactions to transaction observers. + private(set) var observationBroker: DatabaseObservationBroker? /// The list of compile options used when building SQLite - static let sqliteCompileOptions: Set = DatabaseQueue().inDatabase { - try! Set(String.fetchCursor($0, sql: "PRAGMA COMPILE_OPTIONS")) + static func sqliteCompileOptions() throws -> Set { + try DatabaseQueue().inDatabase { + try Set(String.fetchCursor($0, sql: "PRAGMA COMPILE_OPTIONS")) + } } - /// If true, select statement execution is recorded. - /// Use recordingSelectedRegion(_:), see `statementWillExecute(_:)` - var isRecordingSelectedRegion = false + /// Whether the database region selected by statement execution is + /// recorded into `selectedRegion`. + /// + /// To record the selected region, use `recordingSelection(_:_:)`. + private(set) var isRecordingSelectedRegion = false + + /// The database region selected by statement execution, when + /// `isRecordingSelectedRegion` is true. var selectedRegion = DatabaseRegion() - /// Support for checkForAbortedTransaction() + /// Support for `checkForAbortedTransaction()` var isInsideTransactionBlock = false - /// Support for checkForSuspensionViolation(from:) + /// Support for `checkForSuspensionViolation(from:)` @LockedBox var isSuspended = false - /// Support for checkForSuspensionViolation(from:) + /// Support for `checkForSuspensionViolation(from:)` /// This cache is never cleared: we assume journal mode never changes. var journalModeCache: String? // MARK: - Private properties + /// Support for ``Configuration/busyMode``. private var busyCallback: BusyCallback? + + /// Support for ``trace(options:_:)``. private var trace: ((TraceEvent) -> Void)? + + /// The registered custom SQL functions. private var functions = Set() + + /// The registered custom SQL collations. private var collations = Set() - private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly + + /// Support for `beginReadOnly()` and `endReadOnly()`. + private var readOnlyDepth = 0 // MARK: - Initializer @@ -192,6 +216,12 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags) self.description = description self.configuration = configuration + + // We do not report read-only transactions to transaction observers, so + // don't bother installing the observation broker for read-only connections. + if !configuration.readonly { + observationBroker = DatabaseObservationBroker(self) + } } deinit { @@ -200,7 +230,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Database Opening - private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection { + private static func openConnection(path: String, flags: CInt) throws -> SQLiteConnection { // See var sqliteConnection: SQLiteConnection? = nil let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil) @@ -233,9 +263,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib setupDefaultFunctions() setupDefaultCollations() setupAuthorizer() - if !configuration.readonly { - observationBroker.installCommitAndRollbackHooks() - } + observationBroker?.installCommitAndRollbackHooks() try activateExtendedCodes() #if SQLITE_HAS_CODEC @@ -273,7 +301,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib break case .timeout(let duration): - let milliseconds = Int32(duration * 1000) + let milliseconds = CInt(duration * 1000) sqlite3_busy_timeout(sqliteConnection, milliseconds) case .callback(let callback): @@ -294,12 +322,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib add(function: .capitalize) add(function: .lowercase) add(function: .uppercase) - - if #available(OSX 10.11, watchOS 3.0, *) { - add(function: .localizedCapitalize) - add(function: .localizedLowercase) - add(function: .localizedUppercase) - } + add(function: .localizedCapitalize) + add(function: .localizedLowercase) + add(function: .localizedUppercase) } private func setupDefaultCollations() { @@ -318,19 +343,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // // - DatabaseCursorTests.testIssue583() // - http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html - let authorizerP = Unmanaged.passUnretained(authorizer).toOpaque() - sqlite3_set_authorizer( - sqliteConnection, - { (authorizerP, actionCode, cString1, cString2, cString3, cString4) -> Int32 in - Unmanaged - .fromOpaque(authorizerP.unsafelyUnwrapped) - .takeUnretainedValue() - .authorize(actionCode, cString1, cString2, cString3, cString4) - }, - authorizerP) + authorizer.register() } - private func activateExtendedCodes() throws { let code = sqlite3_extended_result_codes(sqliteConnection, 1) guard code == SQLITE_OK else { @@ -372,12 +387,15 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib func close() throws { SchedulingWatchdog.preconditionValidQueue(self) - guard let sqliteConnection = sqliteConnection else { + guard let sqliteConnection else { // Already closed return } configuration.SQLiteConnectionWillClose?(sqliteConnection) + + // Finalize all cached statements since they would prevent + // immediate connection closing. internalStatementCache.clear() publicStatementCache.clear() @@ -388,6 +406,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // > return SQLITE_BUSY. let code = sqlite3_close(sqliteConnection) guard code == SQLITE_OK else { + // So there remain some unfinalized prepared statement somewhere. if let log = Self.logError { if code == SQLITE_BUSY { // Let the user know about unfinalized statements that did @@ -412,12 +431,15 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib func close_v2() { SchedulingWatchdog.preconditionValidQueue(self) - guard let sqliteConnection = sqliteConnection else { + guard let sqliteConnection else { // Already closed return } configuration.SQLiteConnectionWillClose?(sqliteConnection) + + // Finalize all cached statements since they would prevent + // immediate connection closing. internalStatementCache.clear() publicStatementCache.clear() @@ -502,9 +524,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib collation.name, SQLITE_UTF8, collationPointer, - { (collationPointer, length1, buffer1, length2, buffer2) -> Int32 in + { (collationPointer, length1, buffer1, length2, buffer2) in let collation = Unmanaged.fromOpaque(collationPointer!).takeUnretainedValue() - return Int32(collation.function(length1, buffer1, length2, buffer2).rawValue) + return CInt(collation.function(length1, buffer1, length2, buffer2).rawValue) }, nil) guard code == SQLITE_OK else { // Assume a GRDB bug: there is no point throwing any error. @@ -524,23 +546,26 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Read-Only Access + /// MUST be balanced with `endReadOnly()`. func beginReadOnly() throws { if configuration.readonly { return } - if _readOnlyDepth == 0 { + if readOnlyDepth == 0 { try internalCachedStatement(sql: "PRAGMA query_only = 1").execute() } - _readOnlyDepth += 1 + readOnlyDepth += 1 } + /// MUST balance `beginReadOnly()`. func endReadOnly() throws { if configuration.readonly { return } - _readOnlyDepth -= 1 - if _readOnlyDepth == 0 { + readOnlyDepth -= 1 + assert(readOnlyDepth >= 0, "unbalanced endReadOnly()") + if readOnlyDepth == 0 { try internalCachedStatement(sql: "PRAGMA query_only = 0").execute() } } - /// Grants read-only access, starting SQLite 3.8.0 + /// Grants read-only access in the wrapped closure. func readOnly(_ block: () throws -> T) throws -> T { try beginReadOnly() return try throwingFirstError( @@ -548,13 +573,33 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib finally: endReadOnly) } - /// Returns whether database connection is read-only. + /// Returns whether database connection is read-only (due to + /// `SQLITE_OPEN_READONLY` or `PRAGMA query_only=1`). var isReadOnly: Bool { - _readOnlyDepth > 0 || configuration.readonly + readOnlyDepth > 0 || configuration.readonly } // MARK: - Recording of the selected region + /// Extends the `region` argument with the database region selected by all + /// statements executed by the closure. + /// + /// For example: + /// + /// var region = DatabaseRegion() + /// try db.recordingSelection(®ion) { + /// let players = try Player.fetchAll(db) + /// let team = try Team.fetchOne(db, id: 42) + /// } + /// print(region) // player(*),team(*)[42] + /// + /// This method is used by ``ValueObservation``: + /// + /// let playersObservation = ValueObservation.tracking { db in + /// // Here all fetches are recorded, so that we know what is the + /// // database region that must be observed. + /// try Player.fetchAll(db) + /// } func recordingSelection(_ region: inout DatabaseRegion, _ block: () throws -> T) rethrows -> T { if region.isFullDatabase { return try block() @@ -606,57 +651,32 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib self.trace = trace if options.isEmpty || trace == nil { - #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) - sqlite3_trace_v2(sqliteConnection, 0, nil, nil) - #elseif os(Linux) + #if os(Linux) sqlite3_trace(sqliteConnection, nil) #else - if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - sqlite3_trace_v2(sqliteConnection, 0, nil, nil) - } else { - sqlite3_trace(sqliteConnection, nil, nil) - } + sqlite3_trace_v2(sqliteConnection, 0, nil, nil) #endif return } // sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0 // http://www.sqlite.org/changes.html#version_3_14 - // It is available from macOS 10.12, tvOS 10.0, watchOS 3.0 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) - let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_trace_v2(sqliteConnection, UInt32(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in - let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() - db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql) - return SQLITE_OK - }, dbPointer) - #elseif os(Linux) - setupTrace_v1() - #else - if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_trace_v2(sqliteConnection, UInt32(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in - let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() - db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql) - return SQLITE_OK - }, dbPointer) - } else { - setupTrace_v1() - } - #endif - } - - #if !(GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)) - private func setupTrace_v1() { + #if os(Linux) let dbPointer = Unmanaged.passUnretained(self).toOpaque() sqlite3_trace(sqliteConnection, { (dbPointer, sql) in guard let sql = sql.map(String.init(cString:)) else { return } let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() db.trace?(Database.TraceEvent.statement(TraceEvent.Statement(impl: .trace_v1(sql)))) }, dbPointer) + #else + let dbPointer = Unmanaged.passUnretained(self).toOpaque() + sqlite3_trace_v2(sqliteConnection, CUnsignedInt(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in + let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() + db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql) + return SQLITE_OK + }, dbPointer) + #endif } - #endif // Precondition: configuration.trace != nil private func trace_v2( @@ -665,7 +685,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib _ x: UnsafeMutableRawPointer?, _ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?) { - guard let trace = trace else { return } + guard let trace else { return } switch mask { case SQLITE_TRACE_STMT: @@ -688,13 +708,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib publicStatementArguments: configuration.publicStatementArguments)) let duration = TimeInterval(durationP.pointee) / 1.0e9 - #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) + #if !os(Linux) trace(TraceEvent.profile(statement: statement, duration: duration)) - #elseif os(Linux) - #else - if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - trace(TraceEvent.profile(statement: statement, duration: duration)) - } #endif } default: @@ -767,7 +782,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`, except /// reads in WAL mode. /// - /// Suspension ends with resume(). + /// Suspension ends with `resume()`. func suspend() { $isSuspended.update { isSuspended in if isSuspended { @@ -799,7 +814,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib isSuspended = false } - /// Support for checkForSuspensionViolation(from:) + /// Support for `checkForSuspensionViolation(from:)` private func journalMode() throws -> String { if let journalMode = journalModeCache { return journalMode @@ -820,9 +835,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib return journalMode } - /// Throws SQLITE_ABORT for suspended databases, if statement would lock - /// the database, in order to avoid the [`0xdead10cc` - /// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report). + /// If the database is suspended, and executing the statement would lock the + /// database in a way that may trigger the [`0xdead10cc` exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report), + /// this method rollbacks the current transaction and throws `SQLITE_ABORT`. + /// + /// See `suspend()` and ``Configuration/observesSuspensionNotifications``. func checkForSuspensionViolation(from statement: Statement) throws { try $isSuspended.read { isSuspended in guard isSuspended else { @@ -867,22 +884,24 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Transactions & Savepoint - /// Throws SQLITE_ABORT if called from a transaction-wrapping method and + /// Throws `SQLITE_ABORT` if called from a transaction-wrapping method and /// transaction has been aborted (for example, by `sqlite3_interrupt`, or a /// `ON CONFLICT ROLLBACK` clause. /// + /// For example: + /// /// try db.inTransaction { /// do { - /// // Aborted by sqlite3_interrupt or any other - /// // SQLite error which leaves transaction + /// // Throws an error because the transaction was rollbacked. + /// try ... + /// } catch { + /// // Catch the error and continue. /// ... - /// } catch { ... } + /// } /// /// // <- Here we're inside an aborted transaction. - /// try checkForAbortedTransaction(...) // throws + /// try checkForAbortedTransaction(...) // throws SQLITE_ABORT /// ... - /// - /// return .commit /// } func checkForAbortedTransaction( sql: @autoclosure () -> String? = nil, @@ -901,6 +920,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Executes a block inside a database transaction. /// + /// For example: + /// /// try dbQueue.inDatabase do { /// try db.inTransaction { /// try db.execute(sql: "INSERT ...") @@ -911,26 +932,29 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// If the block throws an error, the transaction is rollbacked and the /// error is rethrown. /// - /// This method is not reentrant: you can't nest transactions. + /// - warning: This method is not reentrant: you can't nest transactions. + /// Use ``inSavepoint(_:)`` instead. /// /// - parameters: /// - kind: The transaction type (default nil). /// /// If nil, and the database connection is read-only, the transaction - /// kind is `.deferred`. + /// kind is ``TransactionKind/deferred``. /// /// If nil, and the database connection is not read-only, the - /// transaction kind is `configuration.defaultTransactionKind`. + /// transaction kind is ``Configuration/defaultTransactionKind``. /// /// See for /// more information. /// - block: A block that executes SQL statements and return either - /// .commit or .rollback. + /// ``TransactionCompletion/commit`` or + /// ``TransactionCompletion/rollback``. /// - throws: The error thrown by the block. public func inTransaction(_ kind: TransactionKind? = nil, _ block: () throws -> TransactionCompletion) throws { // Begin transaction try beginTransaction(kind) + // Support for `checkForAbortedTransaction()`. let wasInsideTransactionBlock = isInsideTransactionBlock isInsideTransactionBlock = true defer { @@ -989,6 +1013,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib if readOnly { // Enter read-only mode before starting a transaction, so that the // transaction commit does not trigger database observation. + // See . try self.readOnly { try inSavepoint { result = try block() @@ -1006,6 +1031,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Executes a block inside a savepoint. /// + /// For example: + /// /// try dbQueue.inDatabase do { /// try db.inSavepoint { /// try db.execute(sql: "INSERT ...") @@ -1019,7 +1046,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// This method is reentrant: you can nest savepoints. /// /// - parameter block: A block that executes SQL statements and return - /// either .commit or .rollback. + /// either ``TransactionCompletion/commit`` or + /// ``TransactionCompletion/rollback``. /// - throws: The error thrown by the block. public func inSavepoint(_ block: () throws -> TransactionCompletion) throws { if !isInsideTransaction { @@ -1055,6 +1083,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // the user uses "grdb" as a savepoint name. try execute(sql: "SAVEPOINT grdb") + // Support for `checkForAbortedTransaction()`. let wasInsideTransactionBlock = isInsideTransactionBlock isInsideTransactionBlock = true defer { @@ -1111,16 +1140,17 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Begins a database transaction. /// - /// - parameter kind: The transaction type (default nil). + /// - parameters: + /// - kind: The transaction type (default nil). /// - /// If nil, and the database connection is read-only, the transaction kind - /// is `.deferred`. + /// If nil, and the database connection is read-only, the transaction + /// kind is ``TransactionKind/deferred``. /// - /// If nil, and the database connection is not read-only, the transaction - /// kind is `configuration.defaultTransactionKind`. + /// If nil, and the database connection is not read-only, the + /// transaction kind is ``Configuration/defaultTransactionKind``. /// - /// See for - /// more information. + /// See for + /// more information. /// - throws: A DatabaseError whenever an SQLite error occurs. public func beginTransaction(_ kind: TransactionKind? = nil) throws { // SQLite throws an error for non-deferred transactions when read-only. @@ -1184,6 +1214,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Memory Management + /// Free as much memory as possible. public func releaseMemory() { SchedulingWatchdog.preconditionValidQueue(self) sqlite3_db_release_memory(sqliteConnection) @@ -1280,7 +1311,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// any `DatabaseError` that would happen while performing the backup. public func backup( to destDb: Database, - pagesPerStep: Int32 = -1, + pagesPerStep: CInt = -1, progress: ((DatabaseBackupProgress) throws -> Void)? = nil) throws { @@ -1292,7 +1323,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib func backupInternal( to destDb: Database, - pagesPerStep: Int32 = -1, + pagesPerStep: CInt = -1, afterBackupInit: (() -> Void)? = nil, afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil) throws @@ -1377,7 +1408,7 @@ extension Database { /// } public func usePassphrase(_ passphrase: Data) throws { let code = passphrase.withUnsafeBytes { - sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count)) + sqlite3_key(sqliteConnection, $0.baseAddress, CInt($0.count)) } guard code == SQLITE_OK else { throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection))) @@ -1407,7 +1438,7 @@ extension Database { // > schema of the original db into the new one: // > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/ let code = passphrase.withUnsafeBytes { - sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count)) + sqlite3_rekey(sqliteConnection, $0.baseAddress, CInt($0.count)) } guard code == SQLITE_OK else { throw DatabaseError(resultCode: code, message: lastErrorMessage) @@ -1441,7 +1472,7 @@ extension Database { /// /// // Wait 1 second before failing with SQLITE_BUSY /// let configuration = Configuration(busyMode: .timeout(1)) - /// let dbQueue = DatabaseQueue(path: "...", configuration: configuration) + /// let dbQueue = try DatabaseQueue(path: "...", configuration: configuration) /// /// Relevant SQLite documentation: /// @@ -1464,7 +1495,7 @@ extension Database { } /// The available [checkpoint modes](https://www.sqlite.org/c3ref/wal_checkpoint_v2.html). - public enum CheckpointMode: Int32 { + public enum CheckpointMode: CInt { /// The `SQLITE_CHECKPOINT_PASSIVE` mode case passive = 0 @@ -1609,20 +1640,12 @@ extension Database { /// See `Database.trace(options:_:)` public static let statement = TracingOptions(rawValue: SQLITE_TRACE_STMT) - #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) + #if !os(Linux) /// Reports executed statements and the estimated duration that the /// statement took to run. /// /// See `Database.trace(options:_:)` public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE) - #elseif os(Linux) - #else - /// Reports executed statements and the estimated duration that the - /// statement took to run. - /// - /// See `Database.trace(options:_:)` - @available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) - public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE) #endif } @@ -1641,22 +1664,13 @@ extension Database { } var impl: Impl - #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) + #if !os(Linux) /// The executed SQL, where bound parameters are not expanded. /// /// For example: /// /// SELECT * FROM player WHERE email = ? public var sql: String { _sql } - #elseif os(Linux) - #else - /// The executed SQL, where bound parameters are not expanded. - /// - /// For example: - /// - /// SELECT * FROM player WHERE email = ? - @available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) - public var sql: String { _sql } #endif var _sql: String { @@ -1667,11 +1681,9 @@ extension Database { case let .trace_v2(sqliteStatement, unexpandedSQL, _, _): if let unexpandedSQL = unexpandedSQL { - return String(cString: unexpandedSQL) - .trimmingCharacters(in: .sqlStatementSeparators) + return String(cString: unexpandedSQL).trimmedSQLStatement } else { - return String(cString: sqlite3_sql(sqliteStatement)) - .trimmingCharacters(in: .sqlStatementSeparators) + return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement } } } @@ -1695,8 +1707,7 @@ extension Database { return "" } defer { sqlite3_free(cString) } - return String(cString: cString) - .trimmingCharacters(in: .sqlStatementSeparators) + return String(cString: cString).trimmedSQLStatement } } @@ -1792,7 +1803,7 @@ extension Database { case multiThread case serialized - var SQLiteOpenFlags: Int32 { + var SQLiteOpenFlags: CInt { switch self { case .`default`: return 0 diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index 6feed3285..d94322dbb 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -4,7 +4,7 @@ import Foundation public final class DatabaseCollation { /// The name of the collation public let name: String - let function: (Int32, UnsafeRawPointer?, Int32, UnsafeRawPointer?) -> ComparisonResult + let function: (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult /// Creates a collation. /// diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index ee205083a..6530f58fa 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -197,7 +197,7 @@ extension ResultCode { } } -extension ResultCode: GRDBSendable { } +extension ResultCode: Sendable { } /// DatabaseError wraps an SQLite error. public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index b71b70ca5..b7c23f7fe 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -3,7 +3,7 @@ public final class DatabaseFunction: Hashable { // SQLite identifies functions by (name + argument count) private struct Identity: Hashable { let name: String - let nArg: Int32 // -1 for variadic functions + let nArg: CInt // -1 for variadic functions } /// The name of the SQL function @@ -11,7 +11,7 @@ public final class DatabaseFunction: Hashable { private let identity: Identity let pure: Bool private let kind: Kind - private var eTextRep: Int32 { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) } + private var eTextRep: CInt { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) } /// Creates an SQL function. /// @@ -41,11 +41,11 @@ public final class DatabaseFunction: Hashable { /// not nil. public init( _ name: String, - argumentCount: Int32? = nil, + argumentCount: Int? = nil, pure: Bool = false, - function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) + function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?) { - self.identity = Identity(name: name, nArg: argumentCount ?? -1) + self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1) self.pure = pure self.kind = .function{ (argc, argv) in let arguments = (0.. DatabaseValueConvertible? { + /// func finalize() -> (any DatabaseValueConvertible)? { /// return sum /// } /// } /// - /// let dbQueue = DatabaseQueue() + /// let dbQueue = try DatabaseQueue() /// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self) /// try dbQueue.write { db in /// db.add(function: fn) @@ -98,11 +98,11 @@ public final class DatabaseFunction: Hashable { /// not nil. public init( _ name: String, - argumentCount: Int32? = nil, + argumentCount: Int? = nil, pure: Bool = false, aggregate: Aggregate.Type) { - self.identity = Identity(name: name, nArg: argumentCount ?? -1) + self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1) self.pure = pure self.kind = .aggregate { Aggregate() } } @@ -110,7 +110,7 @@ public final class DatabaseFunction: Hashable { /// Returns an SQL expression that applies the function. /// /// See - public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression { + public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression { switch kind { case .aggregate: return .function(name, arguments.map(\.sqlExpression)) @@ -166,8 +166,10 @@ public final class DatabaseFunction: Hashable { /// Feeds the `pApp` parameter of sqlite3_create_function_v2 /// private class FunctionDefinition { - let compute: (Int32, UnsafeMutablePointer?) throws -> DatabaseValueConvertible? - init(compute: @escaping (Int32, UnsafeMutablePointer?) throws -> DatabaseValueConvertible?) { + let compute: (CInt, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)? + init(compute: @escaping (CInt, UnsafeMutablePointer?) + throws -> (any DatabaseValueConvertible)?) + { self.compute = compute } } @@ -176,17 +178,17 @@ public final class DatabaseFunction: Hashable { /// Feeds the `pApp` parameter of sqlite3_create_function_v2 /// private class AggregateDefinition { - let makeAggregate: () -> DatabaseAggregate - init(makeAggregate: @escaping () -> DatabaseAggregate) { + let makeAggregate: () -> any DatabaseAggregate + init(makeAggregate: @escaping () -> any DatabaseAggregate) { self.makeAggregate = makeAggregate } } /// The current state of an aggregate, storable in SQLite private class AggregateContext { - var aggregate: DatabaseAggregate + var aggregate: any DatabaseAggregate var hasErrored = false - init(aggregate: DatabaseAggregate) { + init(aggregate: some DatabaseAggregate) { self.aggregate = aggregate } } @@ -195,10 +197,10 @@ public final class DatabaseFunction: Hashable { /// See private enum Kind { /// A regular function: SELECT f(1) - case function((Int32, UnsafeMutablePointer?) throws -> DatabaseValueConvertible?) + case function((CInt, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)?) /// An aggregate: SELECT f(foo) FROM bar GROUP BY baz - case aggregate(() -> DatabaseAggregate) + case aggregate(() -> any DatabaseAggregate) /// Feeds the `pApp` parameter of sqlite3_create_function_v2 /// @@ -213,7 +215,7 @@ public final class DatabaseFunction: Hashable { /// Feeds the `xFunc` parameter of sqlite3_create_function_v2 /// - var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer?) -> Void)? { + var xFunc: (@convention(c) (OpaquePointer?, CInt, UnsafeMutablePointer?) -> Void)? { guard case .function = self else { return nil } return { (sqliteContext, argc, argv) in let definition = Unmanaged @@ -231,7 +233,7 @@ public final class DatabaseFunction: Hashable { /// Feeds the `xStep` parameter of sqlite3_create_function_v2 /// - var xStep: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer?) -> Void)? { + var xStep: (@convention(c) (OpaquePointer?, CInt, UnsafeMutablePointer?) -> Void)? { guard case .aggregate = self else { return nil } return { (sqliteContext, argc, argv) in let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext) @@ -288,7 +290,7 @@ public final class DatabaseFunction: Hashable { // > the same aggregate function instance, the same buffer is returned. let stride = MemoryLayout>.stride let aggregateContextBufferP = UnsafeMutableRawBufferPointer( - start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, + start: sqlite3_aggregate_context(sqliteContext, CInt(stride))!, count: stride) if aggregateContextBufferP.contains(where: { $0 != 0 }) { @@ -314,7 +316,7 @@ public final class DatabaseFunction: Hashable { } } - private static func report(result: DatabaseValueConvertible?, in sqliteContext: OpaquePointer?) { + private static func report(result: (any DatabaseValueConvertible)?, in sqliteContext: OpaquePointer?) { switch result?.databaseValue.storage ?? .null { case .null: sqlite3_result_null(sqliteContext) @@ -326,7 +328,7 @@ public final class DatabaseFunction: Hashable { sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT) case .blob(let data): data.withUnsafeBytes { - sqlite3_result_blob(sqliteContext, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT) + sqlite3_result_blob(sqliteContext, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT) } } } @@ -369,12 +371,12 @@ extension DatabaseFunction { /// } /// } /// -/// func finalize() -> DatabaseValueConvertible? { +/// func finalize() -> (any DatabaseValueConvertible)? { /// return sum /// } /// } /// -/// let dbQueue = DatabaseQueue() +/// let dbQueue = try DatabaseQueue() /// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self) /// try dbQueue.write { db in /// db.add(function: fn) @@ -402,5 +404,5 @@ public protocol DatabaseAggregate { mutating func step(_ dbValues: [DatabaseValue]) throws /// Returns the final result - func finalize() throws -> DatabaseValueConvertible? + func finalize() throws -> (any DatabaseValueConvertible)? } diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 7b652e791..bf4b986fe 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -158,10 +158,8 @@ public final class DatabasePool: DatabaseWriter { } } -#if swift(>=5.6) && canImport(_Concurrency) // @unchecked because of databaseSnapshotCount and readerPool extension DatabasePool: @unchecked Sendable { } -#endif extension DatabasePool { @@ -216,20 +214,15 @@ extension DatabasePool { /// as much memory as possible. private func setupMemoryManagement() { let center = NotificationCenter.default - - // Use raw notification names because of - // FB9801372 (UIApplication.didReceiveMemoryWarningNotification should not be declared @MainActor) - // TODO: Reuse UIApplication.didReceiveMemoryWarningNotification when possible. - // TODO: Reuse UIApplication.didEnterBackgroundNotification when possible. center.addObserver( self, selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)), - name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"), + name: UIApplication.didReceiveMemoryWarningNotification, object: nil) center.addObserver( self, selector: #selector(DatabasePool.applicationDidEnterBackground(_:)), - name: NSNotification.Name(rawValue: "UIApplicationDidEnterBackgroundNotification"), + name: UIApplication.didEnterBackgroundNotification, object: nil) } @@ -350,7 +343,7 @@ extension DatabasePool: DatabaseReader { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func read(_ value: (Database) throws -> T) throws -> T { GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") - guard let readerPool = readerPool else { + guard let readerPool else { throw DatabaseError.connectionIsClosed() } return try readerPool.get { reader in @@ -364,7 +357,7 @@ extension DatabasePool: DatabaseReader { } public func asyncRead(_ value: @escaping (Result) -> Void) { - guard let readerPool = self.readerPool else { + guard let readerPool else { value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed"))) return } @@ -396,7 +389,7 @@ extension DatabasePool: DatabaseReader { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func unsafeRead(_ value: (Database) throws -> T) throws -> T { GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") - guard let readerPool = readerPool else { + guard let readerPool else { throw DatabaseError.connectionIsClosed() } return try readerPool.get { reader in @@ -408,7 +401,7 @@ extension DatabasePool: DatabaseReader { } public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { - guard let readerPool = self.readerPool else { + guard let readerPool else { value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed"))) return } @@ -439,7 +432,7 @@ extension DatabasePool: DatabaseReader { if let reader = currentReader { return try reader.reentrantSync(value) } else { - guard let readerPool = readerPool else { + guard let readerPool else { throw DatabaseError.connectionIsClosed() } return try readerPool.get { reader in @@ -529,7 +522,7 @@ extension DatabasePool: DatabaseReader { let isolationSemaphore = DispatchSemaphore(value: 0) do { - guard let readerPool = readerPool else { + guard let readerPool else { throw DatabaseError.connectionIsClosed() } let (reader, releaseReader) = try readerPool.get() @@ -622,7 +615,7 @@ extension DatabasePool: DatabaseReader { /// Returns a reader that can be used from the current dispatch queue, /// if any. private var currentReader: SerializedDatabase? { - guard let readerPool = readerPool else { + guard let readerPool else { return nil } @@ -653,17 +646,22 @@ extension DatabasePool: DatabaseReader { } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { - // TODO: throw instead of crashing when the database is closed - try readerPool!.barrier { + public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + return try readerPool.barrier { try writer.sync(updates) } } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { - // TODO: throw instead of crashing when the database is closed - readerPool!.asyncBarrier { - self.writer.sync(updates) + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + guard let readerPool else { + updates(.failure(DatabaseError.connectionIsClosed())) + return + } + readerPool.asyncBarrier { + self.writer.sync { updates(.success($0)) } } } @@ -727,7 +725,7 @@ extension DatabasePool: DatabaseReader { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { if configuration.readonly { // The easy case: the database does not change @@ -758,7 +756,7 @@ extension DatabasePool: DatabaseReader { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead") diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index ed0936f5c..dbcf000f7 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -51,14 +51,13 @@ public final class DatabaseQueue: DatabaseWriter { /// Opens an in-memory SQLite database. /// - /// let dbQueue = DatabaseQueue() + /// let dbQueue = try DatabaseQueue() /// /// Database memory is released when the database queue gets deallocated. /// /// - parameter configuration: A configuration. - public init(configuration: Configuration = Configuration()) { - // Assume SQLite always succeeds creating an in-memory database - writer = try! SerializedDatabase( + public init(configuration: Configuration = Configuration()) throws { + writer = try SerializedDatabase( path: ":memory:", configuration: configuration, defaultLabel: "GRDB.DatabaseQueue") @@ -94,20 +93,15 @@ extension DatabaseQueue { /// as much memory as possible. private func setupMemoryManagement() { let center = NotificationCenter.default - - // Use raw notification names because of - // FB9801372 (UIApplication.didReceiveMemoryWarningNotification should not be declared @MainActor) - // TODO: Reuse UIApplication.didReceiveMemoryWarningNotification when possible. - // TODO: Reuse UIApplication.didEnterBackgroundNotification when possible. center.addObserver( self, selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)), - name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"), + name: UIApplication.didReceiveMemoryWarningNotification, object: nil) center.addObserver( self, selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)), - name: NSNotification.Name(rawValue: "UIApplicationDidEnterBackgroundNotification"), + name: UIApplication.didEnterBackgroundNotification, object: nil) } @@ -309,12 +303,12 @@ extension DatabaseQueue { } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { try writer.sync(updates) } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { - writer.async(updates) + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + writer.async { updates(.success($0)) } } /// Synchronously executes database updates in a protected dispatch queue, @@ -349,7 +343,7 @@ extension DatabaseQueue { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { if configuration.readonly { // The easy case: the database does not change diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index d5ff1f34f..b88cc459a 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -19,7 +19,7 @@ import Dispatch /// connection to the database. Should you have to cope with external /// connections, protect yourself with transactions, and be ready to setup a /// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html). -public protocol DatabaseReader: AnyObject, GRDBSendable { +public protocol DatabaseReader: AnyObject, Sendable { /// The database configuration var configuration: Configuration { get } @@ -281,14 +281,14 @@ public protocol DatabaseReader: AnyObject, GRDBSendable { /// method instead. /// /// - parameter observation: the stared observation - /// - returns: a TransactionObserver + /// - returns: a cancellable /// /// :nodoc: func _add( observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable } extension DatabaseReader { @@ -341,8 +341,8 @@ extension DatabaseReader { /// - throws: The error thrown by `progress` if the backup is abandoned, or /// any `DatabaseError` that would happen while performing the backup. public func backup( - to writer: DatabaseWriter, - pagesPerStep: Int32 = -1, + to writer: some DatabaseWriter, + pagesPerStep: CInt = -1, progress: ((DatabaseBackupProgress) throws -> Void)? = nil) throws { @@ -356,7 +356,7 @@ extension DatabaseReader { func backup( to destDb: Database, - pagesPerStep: Int32 = -1, + pagesPerStep: CInt = -1, afterBackupInit: (() -> Void)? = nil, afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil) throws @@ -371,11 +371,9 @@ extension DatabaseReader { } } -#if compiler(>=5.6) && canImport(_Concurrency) extension DatabaseReader { // MARK: - Asynchronous Database Access - // TODO: remove @escaping as soon as it is possible /// Asynchronously executes a read-only function that accepts a database /// connection, and returns its result. /// @@ -422,7 +420,6 @@ extension DatabaseReader { } } - // TODO: remove @escaping as soon as it is possible /// Asynchronously executes a function that accepts a database connection. /// /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -465,7 +462,6 @@ extension DatabaseReader { } } } -#endif #if canImport(Combine) extension DatabaseReader { @@ -557,7 +553,7 @@ extension DatabaseReader { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { if scheduler.immediateInitialValue() { do { @@ -601,10 +597,10 @@ extension DatabaseReader { /// Instances of AnyDatabaseReader forward their methods to an arbitrary /// underlying database reader. public final class AnyDatabaseReader: DatabaseReader { - private let base: DatabaseReader + private let base: any DatabaseReader /// Creates a database reader that wraps a base database reader. - public init(_ base: DatabaseReader) { + public init(_ base: some DatabaseReader) { self.base = base } @@ -653,7 +649,7 @@ public final class AnyDatabaseReader: DatabaseReader { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { base._add( observation: observation, diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 0b2109089..9f47083b6 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -38,7 +38,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { /// Returns whether the region is empty. public var isEmpty: Bool { - guard let tableRegions = tableRegions else { + guard let tableRegions else { // full database return false } @@ -55,14 +55,6 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { /// from all tables. public static let fullDatabase = DatabaseRegion(tableRegions: nil) - // TODO: rename to init(table:) when this initializer is no longer public - /// The region that covers a full database table: all columns and all rows - /// from this table. - static func fullTable(_ table: String) -> DatabaseRegion { - let table = CaseInsensitiveIdentifier(rawValue: table) - return DatabaseRegion(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)]) - } - /// Creates an empty database region. public init() { self.init(tableRegions: [:]) @@ -71,9 +63,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { /// Creates a region that spans all rows and columns of a database table. /// /// - parameter table: A table name. - @available(*, deprecated, message: "In order to specify a table region, prefer `Table(tableName)`") - public init(table: String) { - self = .fullTable(table) + init(table: String) { + let table = CaseInsensitiveIdentifier(rawValue: table) + self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)]) } /// Full columns in a table: (some columns in a table) × (all rows) @@ -95,7 +87,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { /// this intersection. It is currently only used as support for /// the isModified(byEventsOfKind:) method. func intersection(_ other: DatabaseRegion) -> DatabaseRegion { - guard let tableRegions = tableRegions else { return other } + guard let tableRegions else { return other } guard let otherTableRegions = other.tableRegions else { return self } var tableRegionsIntersection: [CaseInsensitiveIdentifier: TableRegion] = [:] @@ -113,7 +105,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { /// Only keeps those rowIds in the given table func tableIntersection(_ table: String, rowIds: Set) -> DatabaseRegion { - guard var tableRegions = tableRegions else { + guard var tableRegions else { return DatabaseRegion(table: table, rowIds: rowIds) } @@ -133,7 +125,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { /// Returns the union of this region and the given one. public func union(_ other: DatabaseRegion) -> DatabaseRegion { - guard let tableRegions = tableRegions else { return .fullDatabase } + guard let tableRegions else { return .fullDatabase } guard let otherTableRegions = other.tableRegions else { return .fullDatabase } var tableRegionsUnion: [CaseInsensitiveIdentifier: TableRegion] = [:] @@ -178,7 +170,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { /// This method removes views (assuming no table exists with the same name /// as a view). private func canonicalTables(_ db: Database) throws -> DatabaseRegion { - guard let tableRegions = tableRegions else { return .fullDatabase } + guard let tableRegions else { return .fullDatabase } var region = DatabaseRegion() for (table, tableRegion) in tableRegions { if let canonicalTableName = try db.canonicalTableName(table.rawValue) { @@ -191,7 +183,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { /// Returns a region which doesn't contain any SQLite internal table. private func ignoringInternalSQLiteTables() -> DatabaseRegion { - guard let tableRegions = tableRegions else { return .fullDatabase } + guard let tableRegions else { return .fullDatabase } let filteredRegions = tableRegions.filter { !Database.isSQLiteInternalTable($0.key.rawValue) } @@ -215,7 +207,7 @@ extension DatabaseRegion { /// in the TransactionObserver.observes(eventsOfKind:) method, by calling /// region.isModified(byEventsOfKind:) public func isModified(by event: DatabaseEvent) -> Bool { - guard let tableRegions = tableRegions else { + guard let tableRegions else { // Full database: all changes are impactful return true } @@ -261,7 +253,7 @@ extension DatabaseRegion { extension DatabaseRegion { /// :nodoc: public var description: String { - guard let tableRegions = tableRegions else { + guard let tableRegions else { return "full database" } if tableRegions.isEmpty { @@ -336,7 +328,7 @@ private struct TableRegion: Equatable { } func contains(rowID: Int64) -> Bool { - guard let rowIds = rowIds else { + guard let rowIds else { return true } return rowIds.contains(rowID) @@ -348,7 +340,7 @@ private struct TableRegion: Equatable { /// `DatabaseRegionConvertible` is the protocol for values that can be turned /// into a `DatabaseRegion`. /// -/// Such values specify the region obserbed by `DatabaseRegionObservation`. +/// Such values specify the region observed by `DatabaseRegionObservation`. public protocol DatabaseRegionConvertible { /// Returns a database region. /// @@ -356,13 +348,11 @@ public protocol DatabaseRegionConvertible { func databaseRegion(_ db: Database) throws -> DatabaseRegion } -#if compiler(>=5.5) extension DatabaseRegionConvertible where Self == DatabaseRegion { /// The region that covers the full database: all columns and all rows /// from all tables. public static var fullDatabase: Self { DatabaseRegion.fullDatabase } } -#endif extension DatabaseRegion: DatabaseRegionConvertible { /// :nodoc: @@ -379,8 +369,8 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { _region = region } - public init(_ region: DatabaseRegionConvertible) { - _region = { try region.databaseRegion($0) } + public init(_ region: some DatabaseRegionConvertible) { + _region = region.databaseRegion } /// :nodoc: @@ -398,7 +388,7 @@ extension DatabaseRegion { } } - static func union(_ regions: [DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { + static func union(_ regions: [any DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { return { db in try regions.reduce(into: DatabaseRegion()) { union, region in try union.formUnion(region.databaseRegion(db)) diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 2abf47706..371a4e161 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -10,16 +10,13 @@ import Foundation /// For example: /// /// let observation = DatabaseRegionObservation(tracking: Player.all) -/// let observer = try observation.start(in: dbQueue) { db: Database in -/// print("Players have changed.") -/// } +/// let cancellable = try observation.start( +/// in: dbQueue, +/// onError: { error in ... }, +/// onChange: { (db: Database) in +/// print("A modification of the player table has just been committed.") +/// }) public struct DatabaseRegionObservation { - /// The extent of the database observation. The default is - /// `.observerLifetime`: the observation lasts until the - /// observer returned by the `start(in:onChange:)` method - /// is deallocated. - public var extent: Database.TransactionObservationExtent - /// A closure that is evaluated when the observation starts, and returns /// the observed database region. var observedRegion: (Database) throws -> DatabaseRegion @@ -36,16 +33,19 @@ extension DatabaseRegionObservation { /// let observation = DatabaseRegionObservation(tracking: Player.all()) /// /// var count = 0 - /// let observer = observation.start(in: dbQueue) { _ in - /// count += 1 - /// print("Players have been modified \(count) times.") - /// } + /// let cancellable = observation.start( + /// in: dbQueue, + /// onError: { error in ... }, + /// onChange: { _ in + /// count += 1 + /// print("Players have been modified \(count) times.") + /// }à /// - /// The observation lasts until the observer returned by `start` is - /// deallocated. See the `extent` property for more information. + /// The observation lasts until the cancellable returned by `start` is + /// cancelled or deallocated. /// /// - parameter regions: A list of observed regions. - public init(tracking regions: DatabaseRegionConvertible...) { + public init(tracking regions: any DatabaseRegionConvertible...) { self.init(tracking: regions) } @@ -59,42 +59,91 @@ extension DatabaseRegionObservation { /// let observation = DatabaseRegionObservation(tracking: [Player.all()]) /// /// var count = 0 - /// let observer = observation.start(in: dbQueue) { _ in + /// let cancellable = observation.start(in: dbQueue) { _ in /// count += 1 /// print("Players have been modified \(count) times.") /// } /// - /// The observation lasts until the observer returned by `start` is - /// deallocated. See the `extent` property for more information. + /// The observation lasts until the cancellable returned by `start` is + /// cancelled or deallocated. /// /// - parameter regions: A list of observed regions. - public init(tracking regions: [DatabaseRegionConvertible]) { - self.init( - extent: .observerLifetime, - observedRegion: DatabaseRegion.union(regions)) + public init(tracking regions: [any DatabaseRegionConvertible]) { + self.init(observedRegion: DatabaseRegion.union(regions)) } } extension DatabaseRegionObservation { + /// The state of a started DatabaseRegionObservation + private enum ObservationState { + case cancelled + case pending + case started(DatabaseRegionObserver) + } + /// Starts the observation in the provided database writer (such as /// a database queue or database pool), and returns a transaction observer. /// - /// - parameter reader: A DatabaseWriter. + /// For example: + /// + /// let observation = DatabaseRegionObservation.tracking(Player.all()) + /// let cancellable = observation.start( + /// in: dbQueue, + /// onError: { error in ... }, + /// onChange: { (db: Database) in + /// print("A modification of the player table has just been committed.") + /// }) + /// + /// If the `start` method is called from a writing database access method, + /// the observation of impactful transactions starts immediately. Otherwise, + /// it blocks the current thread until a write access can be established. + /// + /// - parameter writer: A DatabaseWriter. + /// - parameter onError: A closure that is provided eventual errors that + /// happen during observation /// - parameter onChange: A closure that is provided a database connection /// with write access each time the observed region has been modified. - /// - returns: a TransactionObserver + /// - returns: a cancellable. public func start( - in dbWriter: DatabaseWriter, + in writer: some DatabaseWriter, + onError: @escaping (Error) -> Void, onChange: @escaping (Database) -> Void) - throws -> TransactionObserver + -> AnyDatabaseCancellable { + @LockedBox var state = ObservationState.pending + // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. - return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in - let region = try observedRegion(db).observableRegion(db) - let observer = DatabaseRegionObserver(region: region, onChange: onChange) - db.add(transactionObserver: observer, extent: extent) - return observer + writer.unsafeReentrantWrite { db in + do { + let region = try observedRegion(db).observableRegion(db) + $state.update { + let observer = DatabaseRegionObserver(region: region, onChange: { + if case .cancelled = state { + return + } + onChange($0) + }) + + // Use the `.observerLifetime` extent so that we can cancel + // the observation by deallocating the observer. This is + // a simpler way to cancel the observation than waiting for + // *another* write access in order to explicitly remove + // the observer. + db.add(transactionObserver: observer, extent: .observerLifetime) + + $0 = .started(observer) + } + } catch { + onError(error) + } + } + + return AnyDatabaseCancellable { + // Deallocates the transaction observer. This makes sure that the + // `onChange` callback will never be called again, because the + // observation was started with the `.observerLifetime` extent. + state = .cancelled } } } @@ -111,7 +160,7 @@ extension DatabaseRegionObservation { /// Error completion, if any, is only emitted, synchronously, /// on subscription. @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func publisher(in writer: DatabaseWriter) -> DatabasePublishers.DatabaseRegion { + public func publisher(in writer: some DatabaseWriter) -> DatabasePublishers.DatabaseRegion { DatabasePublishers.DatabaseRegion(self, in: writer) } } @@ -160,10 +209,10 @@ extension DatabasePublishers { public typealias Output = Database public typealias Failure = Error - let writer: DatabaseWriter + let writer: any DatabaseWriter let observation: DatabaseRegionObservation - init(_ observation: DatabaseRegionObservation, in writer: DatabaseWriter) { + init(_ observation: DatabaseRegionObservation, in writer: some DatabaseWriter) { self.writer = writer self.observation = observation } @@ -183,13 +232,13 @@ extension DatabasePublishers { { private struct WaitingForDemand { let downstream: Downstream - let writer: DatabaseWriter + let writer: any DatabaseWriter let observation: DatabaseRegionObservation } private struct Observing { let downstream: Downstream - let writer: DatabaseWriter // Retain writer until subscription is finished + let writer: any DatabaseWriter // Retain writer until subscription is finished var remainingDemand: Subscribers.Demand } @@ -204,14 +253,14 @@ extension DatabasePublishers { case finished } - // Observer is not stored in self.state because we must enter the + // cancellable is not stored in self.state because we must enter the // .observing state *before* the observation starts. - private var observer: TransactionObserver? + private var cancellable: AnyDatabaseCancellable? private var state: State private var lock = NSRecursiveLock() // Allow re-entrancy init( - writer: DatabaseWriter, + writer: some DatabaseWriter, observation: DatabaseRegionObservation, downstream: Downstream) { @@ -228,18 +277,14 @@ extension DatabasePublishers { guard demand > 0 else { return } - do { - state = .observing(Observing( - downstream: info.downstream, - writer: info.writer, - remainingDemand: demand)) - observer = try info.observation.start( - in: info.writer, - onChange: { [weak self] in self?.receive($0) }) - } catch { - state = .finished - info.downstream.receive(completion: .failure(error)) - } + state = .observing(Observing( + downstream: info.downstream, + writer: info.writer, + remainingDemand: demand)) + cancellable = info.observation.start( + in: info.writer, + onError: { [weak self] in self?.receive(failure: $0) }, + onChange: { [weak self] in self?.receive($0) }) case var .observing(info): info.remainingDemand += demand @@ -253,7 +298,7 @@ extension DatabasePublishers { func cancel() { lock.synchronized { - observer = nil + cancellable = nil state = .finished } } @@ -272,6 +317,15 @@ extension DatabasePublishers { } } } + + private func receive(failure error: Error) { + lock.synchronized { + if case let .observing(info) = state { + state = .finished + info.downstream.receive(completion: .failure(error)) + } + } + } } } #endif diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index e9d7a6ae4..c3ff65c43 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -89,7 +89,7 @@ extension DatabaseSnapshot { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { _addReadOnly( observation: observation, diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 41e02913f..263018574 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -31,7 +31,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon case blob(Data) /// Returns Int64, Double, String, Data or nil. - public var value: DatabaseValueConvertible? { + public var value: (any DatabaseValueConvertible)? { switch self { case .null: return nil @@ -67,7 +67,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon /// /// The result is nil unless object adopts DatabaseValueConvertible. public init?(value: Any) { - guard let convertible = value as? DatabaseValueConvertible else { + guard let convertible = value as? any DatabaseValueConvertible else { return nil } self = convertible.databaseValue @@ -116,7 +116,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon } /// Returns a DatabaseValue initialized from a raw SQLite statement pointer. - init(sqliteStatement: SQLiteStatement, index: Int32) { + init(sqliteStatement: SQLiteStatement, index: CInt) { switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_NULL: storage = .null @@ -157,13 +157,11 @@ extension DatabaseValue: StatementBinding { } } -extension DatabaseValue: GRDBSendable { } +extension DatabaseValue: Sendable { } -#if swift(>=5.6) && canImport(_Concurrency) // @unchecked due to Foundation.Data not conforming to Sendable // TODO: Remove @unchecked when Foundation has been upgraded extension DatabaseValue.Storage: @unchecked Sendable { } -#endif // MARK: - Hashable & Equatable diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index a027ecdb5..0e59f9b53 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -19,7 +19,17 @@ public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding { var databaseValue: DatabaseValue { get } /// Returns a value initialized from `dbValue`, if possible. + /// + /// - parameter dbValue: A DatabaseValue. + /// - returns: A decoded value, or, if decoding is impossible, nil. static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? + + /// Creates a value from a missing column, if possible. + /// + /// - warning: Do not customize the default implementation. + /// + /// - returns: A decoded value, or, if decoding is impossible, nil. + static func fromMissingColumn() -> Self? } extension DatabaseValueConvertible { @@ -30,6 +40,12 @@ extension DatabaseValueConvertible { public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { databaseValue.bind(to: sqliteStatement, at: index) } + + // `Optional` overrides this default behavior. + /// Default implementation fails to decode a value from a missing column. + public static func fromMissingColumn() -> Self? { + nil // failure. + } } // MARK: - Conversions @@ -49,7 +65,7 @@ extension DatabaseValueConvertible { static func decode( fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, + atUncheckedIndex index: CInt, context: @autoclosure () -> RowDecodingContext) throws -> Self { @@ -62,7 +78,7 @@ extension DatabaseValueConvertible { if let sqliteStatement = row.sqliteStatement { return try decode( fromStatement: sqliteStatement, - atUncheckedIndex: Int32(index), + atUncheckedIndex: CInt(index), context: RowDecodingContext(row: row, key: .columnIndex(index))) } return try decode( @@ -70,48 +86,9 @@ extension DatabaseValueConvertible { context: RowDecodingContext(row: row, key: .columnIndex(index))) } - static func decodeIfPresent( - fromDatabaseValue dbValue: DatabaseValue, - context: @autoclosure () -> RowDecodingContext) - throws -> Self? - { - // Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null. - if let value = fromDatabaseValue(dbValue) { - return value - } else if dbValue.isNull { - return nil - } else { - throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) - } - } - - static func decodeIfPresent( - fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, - context: @autoclosure () -> RowDecodingContext) - throws -> Self? - { - let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) - if let value = fromDatabaseValue(dbValue) { - return value - } else if dbValue.isNull { - return nil - } else { - 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 { - return try decodeIfPresent( - fromStatement: sqliteStatement, - atUncheckedIndex: Int32(index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - return try decodeIfPresent( - fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) + try Optional.decode(fromRow: row, atUncheckedIndex: index) } } @@ -128,16 +105,17 @@ extension DatabaseValueConvertible { /// } public final class DatabaseValueCursor: DatabaseCursor { public typealias Element = Value - public let statement: Statement + /// :nodoc: + public let _statement: Statement /// :nodoc: public var _isDone = false - private let columnIndex: Int32 + private let columnIndex: CInt - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - self.statement = statement + init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { + self._statement = statement if let adapter = adapter { // adapter may redefine the index of the leftmost column - columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement)) + columnIndex = try CInt(adapter.baseColumnIndex(atIndex: 0, layout: statement)) } else { columnIndex = 0 } @@ -149,61 +127,15 @@ public final class DatabaseValueCursor: Databas deinit { // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. - try? statement.reset() + try? _statement.reset() } /// :nodoc: - public func _element(sqliteStatement: SQLiteStatement) -> Value { - // TODO GRDB6: don't crash on decoding errors - try! Value.decode( + public func _element(sqliteStatement: SQLiteStatement) throws -> Value { + try Value.decode( fromStatement: sqliteStatement, atUncheckedIndex: columnIndex, - context: RowDecodingContext(statement: statement, index: Int(columnIndex))) - } -} - -/// A cursor of optional database values extracted from a single column. -/// For example: -/// -/// try dbQueue.read { db in -/// let urls: NullableDatabaseValueCursor = try Optional.fetchCursor(db, sql: "SELECT url FROM link") -/// while let url = urls.next() { // URL? -/// print(url) -/// } -/// } -public final class NullableDatabaseValueCursor: DatabaseCursor { - public typealias Element = Value? - public let statement: Statement - /// :nodoc: - public var _isDone = false - private let columnIndex: Int32 - - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - self.statement = statement - if let adapter = adapter { - // adapter may redefine the index of the leftmost column - columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement)) - } else { - columnIndex = 0 - } - - // Assume cursor is created for immediate iteration: reset and set arguments - try statement.reset(withArguments: arguments) - } - - deinit { - // Statement reset fails when sqlite3_step has previously failed. - // Just ignore reset error. - try? statement.reset() - } - - /// :nodoc: - public func _element(sqliteStatement: SQLiteStatement) -> Value? { - // TODO GRDB6: don't crash on decoding errors - try! Value.decodeIfPresent( - fromStatement: sqliteStatement, - atUncheckedIndex: columnIndex, - context: RowDecodingContext(statement: statement, index: Int(columnIndex))) + context: RowDecodingContext(statement: _statement, index: Int(columnIndex))) } } @@ -246,7 +178,7 @@ extension DatabaseValueConvertible { public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> DatabaseValueCursor { try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) @@ -266,7 +198,7 @@ extension DatabaseValueConvertible { public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Self] { try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) @@ -289,11 +221,11 @@ extension DatabaseValueConvertible { public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Self? { // fetchOne returns nil if there is no row, or if there is a row with a null value - let cursor = try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) + let cursor = try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) return try cursor.next() ?? nil } } @@ -313,7 +245,7 @@ extension DatabaseValueConvertible where Self: Hashable { public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) @@ -347,7 +279,7 @@ extension DatabaseValueConvertible { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> DatabaseValueCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -368,7 +300,7 @@ extension DatabaseValueConvertible { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Self] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -392,7 +324,7 @@ extension DatabaseValueConvertible { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Self? { try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -415,7 +347,7 @@ extension DatabaseValueConvertible where Self: Hashable { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -506,7 +438,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// A cursor over fetched values. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let strings = try request.fetchCursor(db) // Cursor of String /// while let string = try strings.next() { // String /// ... @@ -526,7 +458,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// An array of fetched values. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let strings = try request.fetchAll(db) // [String] /// /// - parameter db: A database connection. @@ -541,7 +473,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// The result is nil if the request returns no row, or if no value can be /// extracted from the first row. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let string = try request.fetchOne(db) // String? /// /// - parameter db: A database connection. @@ -555,7 +487,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable { /// A set of fetched values. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let strings = try request.fetchSet(db) // Set /// /// - parameter db: A database connection. @@ -565,295 +497,3 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable { try RowDecoder.fetchSet(db, self) } } - -/// Swift's Optional comes with built-in methods that allow to fetch cursors -/// and arrays of optional DatabaseValueConvertible: -/// -/// 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.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 Prepared Statement - - /// Returns a cursor over optional values fetched from a prepared statement. - /// - /// 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? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispatch queue. - /// - /// - parameters: - /// - statement: The statement to run. - /// - arguments: Optional statement arguments. - /// - adapter: Optional RowAdapter - /// - returns: A cursor over fetched optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor( - _ statement: Statement, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> NullableDatabaseValueCursor - { - try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) - } - - /// Returns an array of optional values fetched from a prepared statement. - /// - /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") - /// let names = try Optional.fetchAll(statement) // [String?] - /// - /// - parameters: - /// - statement: The statement to run. - /// - arguments: Optional statement arguments. - /// - adapter: Optional RowAdapter - /// - returns: An array of optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll( - _ statement: Statement, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> [Wrapped?] - { - try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) - } -} - -extension Optional where Wrapped: DatabaseValueConvertible & Hashable { - /// Returns a set of optional values fetched from a prepared statement. - /// - /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") - /// let names = try Optional.fetchSet(statement) // Set - /// - /// - parameters: - /// - statement: The statement to run. - /// - arguments: Optional statement arguments. - /// - adapter: Optional RowAdapter - /// - returns: A set of optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet( - _ statement: Statement, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> Set - { - try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) - } -} - -extension Optional where Wrapped: DatabaseValueConvertible { - - // MARK: Fetching From SQL - - /// Returns a cursor over optional values fetched from an SQL query. - /// - /// let names = try Optional.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String? - /// while let name = try names.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispatch queue. - /// - /// - parameters: - /// - db: A database connection. - /// - sql: An SQL query. - /// - arguments: Statement arguments. - /// - adapter: Optional RowAdapter - /// - returns: A cursor over fetched optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor( - _ db: Database, - sql: String, - arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) - throws -> NullableDatabaseValueCursor - { - try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) - } - - /// Returns an array of optional values fetched from an SQL query. - /// - /// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String?] - /// - /// - parameters: - /// - db: A database connection. - /// - sql: An SQL query. - /// - arguments: Statement arguments. - /// - adapter: Optional RowAdapter - /// - returns: An array of optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll( - _ db: Database, - sql: String, - arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) - throws -> [Wrapped?] - { - try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) - } -} - -extension Optional where Wrapped: DatabaseValueConvertible & Hashable { - /// Returns a set of optional values fetched from an SQL query. - /// - /// let names = try String.fetchSet(db, sql: "SELECT name FROM ...") // Set - /// - /// - parameters: - /// - db: A database connection. - /// - sql: An SQL query. - /// - arguments: Statement arguments. - /// - adapter: Optional RowAdapter - /// - returns: A set of optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet( - _ db: Database, - sql: String, - arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) - throws -> Set - { - try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) - } -} - -extension Optional where Wrapped: DatabaseValueConvertible { - - // MARK: Fetching From FetchRequest - - /// Returns a cursor over optional values fetched from a fetch request. - /// - /// let request = Player.select(Column("name")) - /// let names = try Optional.fetchCursor(db, request) // Cursor of String? - /// while let name = try names.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispatch queue. - /// - /// - parameters: - /// - db: A database connection. - /// - request: A FetchRequest. - /// - returns: A cursor over fetched optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) - throws -> NullableDatabaseValueCursor - { - let request = try request.makePreparedRequest(db, forSingleResult: false) - return try fetchCursor(request.statement, adapter: request.adapter) - } - - /// Returns an array of optional values fetched from a fetch request. - /// - /// let request = Player.select(Column("name")) - /// let names = try Optional.fetchAll(db, request) // [String?] - /// - /// - parameters: - /// - db: A database connection. - /// - request: A FetchRequest. - /// - returns: An array of optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: R) throws -> [Wrapped?] { - let request = try request.makePreparedRequest(db, forSingleResult: false) - return try fetchAll(request.statement, adapter: request.adapter) - } -} - -extension Optional where Wrapped: DatabaseValueConvertible & Hashable { - /// Returns a set of optional values fetched from a fetch request. - /// - /// let request = Player.select(Column("name")) - /// let names = try Optional.fetchSet(db, request) // Set - /// - /// - parameters: - /// - db: A database connection. - /// - request: A FetchRequest. - /// - returns: A set of optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: R) throws -> Set { - let request = try request.makePreparedRequest(db, forSingleResult: false) - return try fetchSet(request.statement, adapter: request.adapter) - } -} - -extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible { - - // MARK: Fetching Optional values - - /// A cursor over fetched optional values. - /// - /// let request: ... // Some FetchRequest that fetches Optional - /// let strings = try request.fetchCursor(db) // Cursor of String? - /// while let string = try strings.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispatch queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor { - try Optional.fetchCursor(db, self) - } - - /// An array of fetched optional values. - /// - /// let request: ... // Some FetchRequest that fetches Optional - /// let strings = try request.fetchAll(db) // [String?] - /// - /// - parameter db: A database connection. - /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] { - try Optional.fetchAll(db, self) - } - - /// The first fetched value. - /// - /// The result is nil if the request returns no row, or if no value can be - /// extracted from the first row. - /// - /// let request: ... // Some FetchRequest that fetches String? - /// let string = try request.fetchOne(db) // String? - /// - /// - parameter db: A database connection. - /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? { - try RowDecoder.Wrapped.fetchOne(db, self) - } -} - -extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible & Hashable { - /// A set of fetched optional values. - /// - /// let request: ... // Some FetchRequest that fetches Optional - /// let strings = try request.fetchSet(db) // Set - /// - /// - parameter db: A database connection. - /// - returns: A set of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { - try Optional.fetchSet(db, self) - } -} diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 3ab24d3ea..83ebc6e00 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -89,7 +89,7 @@ public protocol DatabaseWriter: DatabaseReader { /// - parameter updates: The updates to the database. /// - throws: The error thrown by the updates. @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T + func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T /// Asynchronously executes database updates in a protected dispatch queue, /// outside of any transaction, and returns the result. @@ -98,8 +98,10 @@ public protocol DatabaseWriter: DatabaseReader { /// until all pending writes and reads are completed. They postpone all /// other writes and reads until they are completed. /// - /// - parameter updates: The updates to the database. - func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) + /// - parameter updates: A function that accesses the database. Its argument + /// is a `Result` that provides the database connection, or the failure + /// that would prevent establishing the barrier access to the database. + func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) /// Asynchronously executes database updates in a protected dispatch queue, /// wrapped inside a transaction. @@ -286,13 +288,13 @@ extension DatabaseWriter { /// the observer lifetime (observation lasts until observer /// is deallocated). public func add( - transactionObserver: TransactionObserver, + transactionObserver: some TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) { writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) } } - public func remove(transactionObserver: TransactionObserver) { + public func remove(transactionObserver: some TransactionObserver) { writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) } } @@ -365,7 +367,7 @@ extension DatabaseWriter { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") let observer = ValueWriteOnlyObserver( @@ -380,11 +382,9 @@ extension DatabaseWriter { } } -#if compiler(>=5.6) && canImport(_Concurrency) extension DatabaseWriter { // MARK: - Asynchronous Database Access - // TODO: remove @escaping as soon as it is possible /// Asynchronously executes database updates, wrapped inside a transaction, /// and returns the result. /// @@ -408,7 +408,6 @@ extension DatabaseWriter { } } - // TODO: remove @escaping as soon as it is possible /// Asynchronously executes database updates, outside of any transaction, /// and returns the result. /// @@ -432,7 +431,6 @@ extension DatabaseWriter { } } - // TODO: remove @escaping as soon as it is possible /// Asynchronously executes database updates, outside of any transaction, /// and returns the result. /// @@ -450,12 +448,8 @@ extension DatabaseWriter { async throws -> T { try await withUnsafeThrowingContinuation { continuation in - asyncBarrierWriteWithoutTransaction { db in - do { - try continuation.resume(returning: updates(db)) - } catch { - continuation.resume(throwing: error) - } + asyncBarrierWriteWithoutTransaction { dbResult in + continuation.resume(with: dbResult.flatMap { db in Result { try updates(db) } }) } } } @@ -494,8 +488,6 @@ extension DatabaseWriter { } } } -#endif - #if canImport(Combine) extension DatabaseWriter { @@ -633,7 +625,7 @@ extension DatabasePublishers { public typealias Output = Output public typealias Failure = Error - fileprivate let upstream: AnyPublisher + fileprivate let upstream: any Publisher public func receive(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input { upstream.receive(subscriber: subscriber) @@ -644,7 +636,7 @@ extension DatabasePublishers { @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Publisher where Failure == Error { fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write { - .init(upstream: eraseToAnyPublisher()) + .init(upstream: self) } } #endif @@ -693,10 +685,10 @@ public class DatabaseFuture { /// Instances of AnyDatabaseWriter forward their methods to an arbitrary /// underlying database writer. public final class AnyDatabaseWriter: DatabaseWriter { - private let base: DatabaseWriter + private let base: any DatabaseWriter /// Creates a database writer that wraps a base database writer. - public init(_ base: DatabaseWriter) { + public init(_ base: some DatabaseWriter) { self.base = base } @@ -760,11 +752,11 @@ public final class AnyDatabaseWriter: DatabaseWriter { } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { try base.barrierWriteWithoutTransaction(updates) } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { base.asyncBarrierWriteWithoutTransaction(updates) } @@ -790,7 +782,7 @@ public final class AnyDatabaseWriter: DatabaseWriter { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { base._add( observation: observation, diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index b474d1aef..56804c8e8 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -4,13 +4,14 @@ /// rows should be interpreted. /// /// struct Player: FetchableRecord { ... } -/// let request: ... // Some FetchRequest that fetches Player +/// let request: some FetchRequest = ... +/// /// try request.fetchCursor(db) // Cursor of Player /// try request.fetchAll(db) // [Player] /// try request.fetchSet(db) // Set /// try request.fetchOne(db) // Player? /// try request.fetchCount(db) // Int -public protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible { +public protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible { /// The type that tells how fetched database rows should be interpreted. associatedtype RowDecoder @@ -52,14 +53,14 @@ public struct PreparedRequest { public var statement: Statement /// An eventual adapter for rows fetched by the select statement - public var adapter: RowAdapter? + public var adapter: (any RowAdapter)? /// Support for eager loading of hasMany associations. var supplementaryFetch: ((Database, [Row]) throws -> Void)? init( statement: Statement, - adapter: RowAdapter?, + adapter: (any RowAdapter)?, supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil) { self.statement = statement @@ -74,7 +75,7 @@ extension PreparedRequest: Refinable { } extension FetchRequest { /// Returns an adapted request. - public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { + public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest { AdaptedFetchRequest(self, adapter) } } @@ -84,11 +85,11 @@ public struct AdaptedFetchRequest: FetchRequest { public typealias RowDecoder = Base.RowDecoder let base: Base - let adapter: (Database) throws -> RowAdapter + let adapter: (Database) throws -> any RowAdapter /// Creates an adapted request from a base request and a closure that builds /// a row adapter from a database connection. - init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) { + init(_ base: Base, _ adapter: @escaping (Database) throws -> any RowAdapter) { self.base = base self.adapter = adapter } @@ -154,9 +155,7 @@ public struct AnyFetchRequest: FetchRequest { extension AnyFetchRequest { /// Creates a request that wraps and forwards operations to `request`. - public init(_ request: Request) - where Request.RowDecoder == RowDecoder - { + public init(_ request: some FetchRequest) { self.init(request: ConcreteFetchRequestEraser(request: request)) } } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 5355a6f78..acc03f583 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -7,7 +7,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, { // It is not a violation of the Demeter law when another type uses this // property, which is exposed for optimizations. - let impl: RowImpl + let impl: any RowImpl /// Unless we are producing a row array, we use a single row when iterating /// a statement: @@ -44,7 +44,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, } /// Creates a row from a dictionary of values. - public convenience init(_ dictionary: [String: DatabaseValueConvertible?]) { + public convenience init(_ dictionary: [String: (any DatabaseValueConvertible)?]) { self.init(impl: ArrayRowImpl(columns: dictionary.map { ($0, $1?.databaseValue ?? .null) })) } @@ -53,7 +53,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, /// The result is nil unless all dictionary keys are strings, and values /// adopt DatabaseValueConvertible. public convenience init?(_ dictionary: [AnyHashable: Any]) { - var initDictionary = [String: DatabaseValueConvertible?]() + var initDictionary = [String: (any DatabaseValueConvertible)?]() for (key, value) in dictionary { guard let columnName = key as? String else { return nil @@ -73,7 +73,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, /// let row: Row = ["foo": 1, "foo": "bar", "baz": nil] /// print(row) /// // Prints [foo:1 foo:"bar" baz:NULL] - public convenience init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) { + public convenience init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) { self.init(impl: ArrayRowImpl(columns: elements.map { ($0, $1?.databaseValue ?? .null) })) } @@ -128,7 +128,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, columnNames: statement.columnNames)) } - init(impl: RowImpl) { + init(impl: any RowImpl) { self.statement = nil self.sqliteStatement = nil self.impl = impl @@ -213,7 +213,7 @@ extension Row { /// /// Indexes span from 0 for the leftmost column to (row.count - 1) for the /// righmost column. - public subscript(_ index: Int) -> DatabaseValueConvertible? { + public subscript(_ index: Int) -> (any DatabaseValueConvertible)? { _checkIndex(index) return impl.databaseValue(atUncheckedIndex: index).storage.value } @@ -223,39 +223,18 @@ extension Row { /// Indexes span from 0 for the leftmost column to (row.count - 1) for the /// righmost column. /// - /// If the SQLite value is NULL, the result is nil. Otherwise the SQLite - /// value is converted to the requested type `Value`. Should this conversion - /// fail, a fatal error is raised. - @inlinable - public subscript(_ index: Int) -> Value? { - try! decodeIfPresent(Value.self, atIndex: index) - } - - /// Returns the value at given index, converted to the requested type. + /// For example: /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the - /// righmost column. + /// let row = try Row.fetchOne(db, sql: "SELECT 42")! + /// let score: Int = row[0] // 42 /// - /// If the SQLite value is NULL, the result is nil. Otherwise the SQLite - /// value is converted to the requested type `Value`. Should this conversion - /// fail, a fatal error is raised. + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")! + /// let name: String = row[0] // "Alice" /// - /// This method exists as an optimization opportunity for types that adopt - /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions - /// (see ). - @inline(__always) - @inlinable - public subscript(_ index: Int) -> Value? { - try! decodeIfPresent(Value.self, atIndex: index) - } - - /// Returns the value at given index, converted to the requested type. + /// When the database value may be nil, ask for an optional: /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the - /// righmost column. - /// - /// This method crashes if the fetched SQLite value is NULL, or if the - /// SQLite value can not be converted to `Value`. + /// let row = try Row.fetchOne(db, sql: "SELECT NULL")! + /// let name: String? = row[0] // nil @inlinable public subscript(_ index: Int) -> Value { try! decode(Value.self, atIndex: index) @@ -266,12 +245,22 @@ extension Row { /// Indexes span from 0 for the leftmost column to (row.count - 1) for the /// righmost column. /// - /// This method crashes if the fetched SQLite value is NULL, or if the - /// SQLite value can not be converted to `Value`. - /// /// This method exists as an optimization opportunity for types that adopt - /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions - /// (see ). + /// ``StatementColumnConvertible``. It can trigger SQLite built-in + /// conversions (see ). + /// + /// For example: + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 42")! + /// let score: Int = row[0] // 42 + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")! + /// let name: String = row[0] // "Alice" + /// + /// When the database value may be nil, ask for an optional: + /// + /// let row = try Row.fetchOne(db, sql: "SELECT NULL")! + /// let name: String? = row[0] // nil @inline(__always) @inlinable public subscript(_ index: Int) -> Value { @@ -285,7 +274,7 @@ extension Row { /// the same name, the leftmost column is considered. /// /// The result is nil if the row does not contain the column. - public subscript(_ columnName: String) -> DatabaseValueConvertible? { + public subscript(_ columnName: String) -> (any DatabaseValueConvertible)? { // IMPLEMENTATION NOTE // This method has a single known use case: checking if the value is nil, // as in: @@ -304,40 +293,23 @@ extension Row { /// Column name lookup is case-insensitive, and when several columns have /// the same name, the leftmost column is considered. /// - /// If the column is missing or if the SQLite value is NULL, the result is - /// nil. Otherwise the SQLite value is converted to the requested type - /// `Value`. Should this conversion fail, a fatal error is raised. - @inlinable - public subscript(_ columnName: String) -> Value? { - try! decodeIfPresent(Value.self, forKey: columnName) - } - - /// Returns the value at given column, converted to the requested type. + /// For example: /// - /// Column name lookup is case-insensitive, and when several columns have - /// the same name, the leftmost column is considered. + /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! + /// let score: Int = row["score"] // 42 /// - /// If the column is missing or if the SQLite value is NULL, the result is - /// nil. Otherwise the SQLite value is converted to the requested type - /// `Value`. Should this conversion fail, a fatal error is raised. + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String = row["name"] // "Alice" /// - /// This method exists as an optimization opportunity for types that adopt - /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions - /// (see ). - @inlinable - public subscript(_ columnName: String) -> Value? { - try! decodeIfPresent(Value.self, forKey: columnName) - } - - /// Returns the value at given column, converted to the requested type. + /// When the database value may be nil, ask for an optional: /// - /// Column name lookup is case-insensitive, and when several columns have - /// the same name, the leftmost column is considered. + /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! + /// let name: String? = row["name"] // nil /// - /// If the row does not contain the column, a fatal error is raised. + /// When the column does not exist, nil is returned: /// - /// This method crashes if the fetched SQLite value is NULL, or if the - /// SQLite value can not be converted to `Value`. + /// let row = try Row.fetchOne(db, sql: "SELECT ...")! + /// let name: String? = row["missing"] // nil @inlinable public subscript(_ columnName: String) -> Value { try! decode(Value.self, forKey: columnName) @@ -348,27 +320,40 @@ extension Row { /// Column name lookup is case-insensitive, and when several columns have /// the same name, the leftmost column is considered. /// - /// If the row does not contain the column, a fatal error is raised. - /// - /// This method crashes if the fetched SQLite value is NULL, or if the - /// SQLite value can not be converted to `Value`. - /// /// This method exists as an optimization opportunity for types that adopt - /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions + /// `StatementColumnConvertible`. It can trigger SQLite built-in conversions /// (see ). + /// + /// For example: + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! + /// let score: Int = row["score"] // 42 + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String = row["name"] // "Alice" + /// + /// When the database value may be nil, ask for an optional: + /// + /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! + /// let name: String? = row["name"] // nil + /// + /// When the column does not exist, nil is returned: + /// + /// let row = try Row.fetchOne(db, sql: "SELECT ...")! + /// let name: String? = row["missing"] // nil @inlinable public subscript(_ columnName: String) -> Value { try! decode(Value.self, forKey: columnName) } - /// Returns Int64, Double, String, NSData or nil, depending on the value + /// Returns Int64, Double, String, Data or nil, depending on the value /// stored at the given column. /// /// Column name lookup is case-insensitive, and when several columns have /// the same name, the leftmost column is considered. /// /// The result is nil if the row does not contain the column. - public subscript(_ column: Column) -> DatabaseValueConvertible? { + public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? { self[column.name] } @@ -377,47 +362,25 @@ extension Row { /// Column name lookup is case-insensitive, and when several columns have /// the same name, the leftmost column is considered. /// - /// If the column is missing or if the SQLite value is NULL, the result is - /// nil. Otherwise the SQLite value is converted to the requested type - /// `Value`. Should this conversion fail, a fatal error is raised. + /// For example: + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! + /// let score: Int = row[Column("score")] // 42 + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String = row[Column("name")] // "Alice" + /// + /// When the database value may be nil, ask for an optional: + /// + /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! + /// let name: String? = row[Column("name")] // nil + /// + /// When the column does not exist, nil is returned: + /// + /// let row = try Row.fetchOne(db, sql: "SELECT ...")! + /// let name: String? = row[Column("missing")] // nil @inlinable - public subscript(_ column: Column) -> Value? { - try! decodeIfPresent(Value.self, forKey: column.name) - } - - /// Returns the value at given column, converted to the requested type. - /// - /// Column name lookup is case-insensitive, and when several columns have - /// the same name, the leftmost column is considered. - /// - /// If the column is missing or if the SQLite value is NULL, the result is - /// nil. Otherwise the SQLite value is converted to the requested type - /// `Value`. Should this conversion fail, a fatal error is raised. - /// - /// This method exists as an optimization opportunity for types that adopt - /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions - /// (see ). - @inlinable - public subscript(_ column: Column) - -> Value? - where - Value: DatabaseValueConvertible & StatementColumnConvertible, - Column: ColumnExpression - { - try! decodeIfPresent(Value.self, forKey: column.name) - } - - /// Returns the value at given column, converted to the requested type. - /// - /// Column name lookup is case-insensitive, and when several columns have - /// the same name, the leftmost column is considered. - /// - /// If the row does not contain the column, a fatal error is raised. - /// - /// This method crashes if the fetched SQLite value is NULL, or if the - /// SQLite value can not be converted to `Value`. - @inlinable - public subscript(_ column: Column) -> Value { + public subscript(_ column: some ColumnExpression) -> Value { try! decode(Value.self, forKey: column.name) } @@ -426,25 +389,36 @@ extension Row { /// Column name lookup is case-insensitive, and when several columns have /// the same name, the leftmost column is considered. /// - /// If the row does not contain the column, a fatal error is raised. - /// - /// This method crashes if the fetched SQLite value is NULL, or if the - /// SQLite value can not be converted to `Value`. - /// /// This method exists as an optimization opportunity for types that adopt - /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions + /// ``StatementColumnConvertible``. It can trigger SQLite built-in conversions /// (see ). + /// + /// For example: + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! + /// let score: Int = row[Column("score")] // 42 + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String = row[Column("name")] // "Alice" + /// + /// When the database value may be nil, ask for an optional: + /// + /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! + /// let name: String? = row[Column("name")] // nil + /// + /// When the column does not exist, nil is returned: + /// + /// let row = try Row.fetchOne(db, sql: "SELECT ...")! + /// let name: String? = row[Column("missing")] // nil @inlinable - public subscript(_ column: Column) + public subscript(_ column: some ColumnExpression) -> Value - where - Value: DatabaseValueConvertible & StatementColumnConvertible, - Column: ColumnExpression + where Value: DatabaseValueConvertible & StatementColumnConvertible { try! decode(Value.self, forKey: column.name) } - /// Returns the optional Data at given index. + /// Returns the optional `Data` at given index. /// /// Indexes span from 0 for the leftmost column to (row.count - 1) for the /// righmost column. @@ -458,7 +432,7 @@ extension Row { try! decodeDataNoCopyIfPresent(atIndex: index) } - /// Returns the optional Data at given column. + /// Returns the optional `Data` at given column. /// /// Column name lookup is case-insensitive, and when several columns have /// the same name, the leftmost column is considered. @@ -473,18 +447,18 @@ extension Row { try! decodeDataNoCopyIfPresent(forKey: columnName) } - /// Returns the optional `NSData` at given column. + /// Returns the optional `Data` at given column. /// /// Column name lookup is case-insensitive, and when several columns have /// the same name, the leftmost column is considered. /// /// If the column is missing or if the SQLite value is NULL, the result is - /// nil. If the SQLite value can not be converted to NSData, a fatal error + /// nil. If the SQLite value can not be converted to Data, a fatal error /// is raised. /// /// The returned data does not owns its bytes: it must not be used longer /// than the row's lifetime. - public func dataNoCopy(_ column: Column) -> Data? { + public func dataNoCopy(_ column: some ColumnExpression) -> Data? { try! decodeDataNoCopyIfPresent(forKey: column.name) } } @@ -513,7 +487,7 @@ extension Row { /// let request = Book.including(required: Book.author) /// let row = try Row.fetchOne(db, request)! /// - /// print(Book(row: row).title) + /// try print(Book(row: row).title) /// // Prints "Moby-Dick" /// /// let author: Author = row["author"] @@ -525,7 +499,7 @@ extension Row { /// let request = Book.including(required: Book.author.including(required: Author.country)) /// let row = try Row.fetchOne(db, request)! /// - /// print(Book(row: row).title) + /// try print(Book(row: row).title) /// // Prints "Moby-Dick" /// /// let country: Country = row["country"] @@ -548,7 +522,7 @@ extension Row { /// let request = Book.including(optional: Book.author) /// let row = try Row.fetchOne(db, request)! /// - /// print(Book(row: row).title) + /// try print(Book(row: row).title) /// // Prints "Moby-Dick" /// /// let author: Author? = row["author"] @@ -560,7 +534,7 @@ extension Row { /// let request = Book.including(optional: Book.author.including(optional: Author.country)) /// let row = try Row.fetchOne(db, request)! /// - /// print(Book(row: row).title) + /// try print(Book(row: row).title) /// // Prints "Moby-Dick" /// /// let country: Country? = row["country"] @@ -583,7 +557,7 @@ extension Row { /// let request = Author.including(all: Author.books) /// let row = try Row.fetchOne(db, request)! /// - /// print(Author(row: row).name) + /// try print(Author(row: row).name) /// // Prints "Herman Melville" /// /// let books: [Book] = row["books"] @@ -605,7 +579,7 @@ extension Row { /// let request = Author.including(all: Author.books) /// let row = try Row.fetchOne(db, request)! /// - /// print(Author(row: row).name) + /// try print(Author(row: row).name) /// // Prints "Herman Melville" /// /// let books: Set = row["books"] @@ -702,24 +676,6 @@ extension Row { // MARK: - Throwing DatabaseValueConvertible Decoding Methods extension Row { - /// Returns the value at given index, converted to the requested type. - /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the - /// righmost column. - /// - /// If the SQLite value is NULL, the result is nil. Otherwise the SQLite - /// value is converted to the requested type `Value`. If the conversion - /// fail, a `RowDecodingError` is thrown. - @inlinable - func decodeIfPresent( - _ type: Value.Type = Value.self, - atIndex index: Int) - throws -> Value? - { - _checkIndex(index) - return try Value.decodeIfPresent(fromRow: self, atUncheckedIndex: index) - } - /// Returns the value at given index, converted to the requested type. /// /// Indexes span from 0 for the leftmost column to (row.count - 1) for the @@ -737,26 +693,6 @@ extension Row { return try Value.decode(fromRow: self, atUncheckedIndex: index) } - /// Returns the value at given column, converted to the requested type. - /// - /// Column name lookup is case-insensitive, and when several columns have - /// the same name, the leftmost column is considered. - /// - /// If the column is missing or if the SQLite value is NULL, the result is - /// nil. Otherwise the SQLite value is converted to the requested type - /// `Value`. If the conversion fails, a `RowDecodingError` is thrown. - @inlinable - func decodeIfPresent( - _ type: Value.Type = Value.self, - forKey columnName: String) - throws -> Value? - { - guard let index = index(forColumn: columnName) else { - return nil - } - return try Value.decodeIfPresent(fromRow: self, atUncheckedIndex: index) - } - /// Returns the value at given column, converted to the requested type. /// /// Column name lookup is case-insensitive, and when several columns have @@ -772,7 +708,11 @@ extension Row { throws -> Value { guard let index = index(forColumn: columnName) else { - throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self)) + if let value = Value.fromMissingColumn() { + return value + } else { + throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self)) + } } return try Value.decode(fromRow: self, atUncheckedIndex: index) } @@ -781,29 +721,6 @@ extension Row { // MARK: - Throwing DatabaseValueConvertible & StatementColumnConvertible Decoding Methods extension Row { - /// Returns the value at given index, converted to the requested type. - /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the - /// righmost column. - /// - /// If the SQLite value is NULL, the result is nil. Otherwise the SQLite - /// value is converted to the requested type `Value`. If the conversion - /// fail, a `RowDecodingError` is thrown. - /// - /// This method exists as an optimization opportunity for types that adopt - /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions - /// (see ). - @inline(__always) - @inlinable - func decodeIfPresent( - _ type: Value.Type = Value.self, - atIndex index: Int) - throws -> Value? - { - _checkIndex(index) - return try Value.fastDecodeIfPresent(fromRow: self, atUncheckedIndex: index) - } - /// Returns the value at given index, converted to the requested type. /// /// Indexes span from 0 for the leftmost column to (row.count - 1) for the @@ -826,31 +743,6 @@ extension Row { return try Value.fastDecode(fromRow: self, atUncheckedIndex: index) } - /// Returns the value at given column, converted to the requested type. - /// - /// Column name lookup is case-insensitive, and when several columns have - /// the same name, the leftmost column is considered. - /// - /// If the column is missing or if the SQLite value is NULL, the result is - /// nil. Otherwise the SQLite value is converted to the requested type - /// `Value`. If the conversion fails, a `RowDecodingError` is thrown. - /// - /// This method exists as an optimization opportunity for types that adopt - /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions - /// (see ). - @inline(__always) - @inlinable - func decodeIfPresent( - _ type: Value.Type = Value.self, - forKey columnName: String) - throws -> Value? - { - guard let index = index(forColumn: columnName) else { - return nil - } - return try Value.fastDecodeIfPresent(fromRow: self, atUncheckedIndex: index) - } - /// Returns the value at given column, converted to the requested type. /// /// Column name lookup is case-insensitive, and when several columns have @@ -870,7 +762,11 @@ extension Row { throws -> Value { guard let index = index(forColumn: columnName) else { - throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self)) + if let value = Value.fromMissingColumn() { + return value + } else { + throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self)) + } } return try Value.fastDecode(fromRow: self, atUncheckedIndex: index) } @@ -884,16 +780,6 @@ extension Row { { try impl.fastDecode(type, atUncheckedIndex: index) } - - // Support for fast decoding in scoped rows - @usableFromInline - func fastDecodeIfPresent( - _ type: Value.Type, - atUncheckedIndex index: Int) - throws -> Value? - { - try impl.fastDecodeIfPresent(type, atUncheckedIndex: index) - } } // MARK: - Throwing Data Decoding Methods @@ -986,7 +872,7 @@ extension Row { /// let request = Book.including(optional: Book.author) /// let row = try Row.fetchOne(db, request)! /// - /// print(Book(row: row).title) + /// try print(Book(row: row).title) /// // Prints "Moby-Dick" /// /// let author: Author? = row["author"] @@ -998,7 +884,7 @@ extension Row { /// let request = Book.including(optional: Book.author.including(optional: Author.country)) /// let row = try Row.fetchOne(db, request)! /// - /// print(Book(row: row).title) + /// try print(Book(row: row).title) /// // Prints "Moby-Dick" /// /// let country: Country? = row["country"] @@ -1018,7 +904,7 @@ extension Row { guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else { return nil } - return Record(row: scopedRow) + return try Record(row: scopedRow) } /// Returns the record associated with the given scope. @@ -1028,7 +914,7 @@ extension Row { /// let request = Book.including(required: Book.author) /// let row = try Row.fetchOne(db, request)! /// - /// print(Book(row: row).title) + /// try print(Book(row: row).title) /// // Prints "Moby-Dick" /// /// let author: Author = row["author"] @@ -1040,7 +926,7 @@ extension Row { /// let request = Book.including(required: Book.author.including(required: Author.country)) /// let row = try Row.fetchOne(db, request)! /// - /// print(Book(row: row).title) + /// try print(Book(row: row).title) /// // Prints "Moby-Dick" /// /// let country: Country = row["country"] @@ -1087,7 +973,7 @@ extension Row { scope \(String(reflecting: scope)) only contains null values """)) } - return Record(row: scopedRow) + return try Record(row: scopedRow) } } @@ -1101,7 +987,7 @@ extension Row { /// let request = Author.including(all: Author.books) /// let row = try Row.fetchOne(db, request)! /// - /// print(Author(row: row).name) + /// try print(Author(row: row).name) /// // Prints "Herman Melville" /// /// let books: [Book] = row["books"] @@ -1140,7 +1026,7 @@ extension Row { var collection = Collection() collection.reserveCapacity(rows.count) for row in rows { - collection.append(Collection.Element(row: row)) + try collection.append(Collection.Element(row: row)) } return collection } @@ -1152,7 +1038,7 @@ extension Row { /// let request = Author.including(all: Author.books) /// let row = try Row.fetchOne(db, request)! /// - /// print(Author(row: row).name) + /// try print(Author(row: row).name) /// // Prints "Herman Melville" /// /// let books: Set = row["books"] @@ -1186,7 +1072,7 @@ extension Row { } var set = Set(minimumCapacity: rows.count) for row in rows { - set.insert(Record(row: row)) + try set.insert(Record(row: row)) } return set } @@ -1201,13 +1087,14 @@ extension Row { /// } public final class RowCursor: DatabaseCursor { public typealias Element = Row - public let statement: Statement + /// :nodoc: + public let _statement: Statement /// :nodoc: public var _isDone = false @usableFromInline let _row: Row // Reused for performance - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - self.statement = statement + init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { + self._statement = statement self._row = try Row(statement: statement).adapted(with: adapter, layout: statement) // Assume cursor is created for immediate iteration: reset and set arguments @@ -1217,7 +1104,7 @@ public final class RowCursor: DatabaseCursor { deinit { // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. - try? statement.reset() + try? _statement.reset() } /// :nodoc: @@ -1261,7 +1148,7 @@ extension Row { public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> RowCursor { try RowCursor(statement: statement, arguments: arguments, adapter: adapter) @@ -1281,7 +1168,7 @@ extension Row { public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Row] { // The cursor reuses a single mutable row. Return immutable copies. @@ -1302,7 +1189,7 @@ extension Row { public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { // The cursor reuses a single mutable row. Return immutable copies. @@ -1323,7 +1210,7 @@ extension Row { public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Row? { let cursor = try fetchCursor(statement, arguments: arguments, adapter: adapter) @@ -1370,7 +1257,7 @@ extension Row { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> RowCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -1395,7 +1282,7 @@ extension Row { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Row] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -1420,7 +1307,7 @@ extension Row { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -1445,7 +1332,7 @@ extension Row { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Row? { try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -1547,13 +1434,13 @@ extension Row { } } -extension FetchRequest where RowDecoder == Row { +extension FetchRequest { // MARK: Fetching Rows /// A cursor over fetched rows. /// - /// let request: ... // Some FetchRequest that fetches Row + /// let request: some FetchRequest = ... /// let rows = try request.fetchCursor(db) // RowCursor /// while let row = try rows.next() { // Row /// let id: Int64 = row[0] @@ -1582,7 +1469,7 @@ extension FetchRequest where RowDecoder == Row { /// An array of fetched rows. /// - /// let request: ... // Some FetchRequest that fetches Row + /// let request: some FetchRequest = ... /// let rows = try request.fetchAll(db) /// /// - parameter db: A database connection. @@ -1594,7 +1481,7 @@ extension FetchRequest where RowDecoder == Row { /// A set of fetched rows. /// - /// let request: ... // Some FetchRequest that fetches Row + /// let request: some FetchRequest = ... /// let rows = try request.fetchSet(db) /// /// - parameter db: A database connection. @@ -1606,7 +1493,7 @@ extension FetchRequest where RowDecoder == Row { /// The first fetched row. /// - /// let request: ... // Some FetchRequest that fetches Row + /// let request: some FetchRequest = ... /// let row = try request.fetchOne(db) /// /// - parameter db: A database connection. @@ -1810,13 +1697,13 @@ extension Row { /// row.scopes["bar"] // [bar:2] /// row.scopes["baz"] // nil public struct ScopesView: Collection { - public typealias Index = Dictionary.Index + public typealias Index = Dictionary.Index private let row: Row - private let scopes: [String: _LayoutedRowAdapter] + private let scopes: [String: any _LayoutedRowAdapter] private let prefetchedRows: Row.PrefetchedRowsView /// The scopes defined on this row. - public var names: Dictionary.Keys { + public var names: Dictionary.Keys { scopes.keys } @@ -1824,7 +1711,7 @@ extension Row { self.init(row: Row(), scopes: [:], prefetchedRows: Row.PrefetchedRowsView()) } - init(row: Row, scopes: [String: _LayoutedRowAdapter], prefetchedRows: Row.PrefetchedRowsView) { + init(row: Row, scopes: [String: any _LayoutedRowAdapter], prefetchedRows: Row.PrefetchedRowsView) { self.row = row self.scopes = scopes self.prefetchedRows = prefetchedRows @@ -2039,7 +1926,7 @@ extension Row { } } -extension OrderedDictionary where Key == String, Value == Row.Prefetch { +extension OrderedDictionary { fileprivate mutating func setRows(_ rows: [Row], forKeyPath keyPath: [String]) { var keyPath = keyPath let key = keyPath.removeFirst() @@ -2068,11 +1955,6 @@ protocol RowImpl { atUncheckedIndex index: Int) throws -> Value - func fastDecodeIfPresent( - _ type: Value.Type, - atUncheckedIndex index: Int) - throws -> Value? - func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? @@ -2123,17 +2005,6 @@ extension RowImpl { context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) } - func fastDecodeIfPresent( - _ type: Value.Type, - atUncheckedIndex index: Int) - throws -> Value? - { - // unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization) - try Value.decodeIfPresent( - fromDatabaseValue: databaseValue(atUncheckedIndex: index), - context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) - } - func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { // unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization) try Data.decode( @@ -2143,7 +2014,7 @@ extension RowImpl { func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? { // unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization) - try Data.decodeIfPresent( + try Optional.decode( fromDatabaseValue: databaseValue(atUncheckedIndex: index), context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) } @@ -2154,9 +2025,7 @@ extension RowImpl { struct ArrayRowImpl: RowImpl { let columns: [(String, DatabaseValue)] - init(columns: C) - where C: Collection, C.Element == (String, DatabaseValue) - { + init(columns: some Collection<(String, DatabaseValue)>) { self.columns = Array(columns) } @@ -2182,12 +2051,9 @@ struct ArrayRowImpl: RowImpl { } } -#if swift(>=5.6) && canImport(_Concurrency) // @unchecked because columns property is not inferred as Sendable // TODO: remove this @unchecked when compiler can handle tuples. extension ArrayRowImpl: @unchecked Sendable { } -#endif - // TODO: merge with ArrayRowImpl eventually? /// See Row.init(copiedFromStatementRef:sqliteStatement:) @@ -2238,7 +2104,7 @@ private struct StatementRowImpl: RowImpl { self.sqliteStatement = sqliteStatement // Optimize row[columnName] let lowercaseColumnNames = (0.. Bool { // Avoid extracting values, because this modifies the SQLite statement. - sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL + sqlite3_column_type(sqliteStatement, CInt(index)) == SQLITE_NULL } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue { - DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index)) + DatabaseValue(sqliteStatement: sqliteStatement, index: CInt(index)) } func fastDecode( @@ -2268,40 +2134,29 @@ private struct StatementRowImpl: RowImpl { { try Value.fastDecode( fromStatement: sqliteStatement, - atUncheckedIndex: Int32(index), - context: RowDecodingContext(statement: statement, index: index)) - } - - func fastDecodeIfPresent( - _ type: Value.Type, - atUncheckedIndex index: Int) - throws -> Value? - { - try Value.fastDecodeIfPresent( - fromStatement: sqliteStatement, - atUncheckedIndex: Int32(index), + atUncheckedIndex: CInt(index), context: RowDecodingContext(statement: statement, index: index)) } func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { - guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { + guard sqlite3_column_type(sqliteStatement, CInt(index)) != SQLITE_NULL else { throw RowDecodingError.valueMismatch(Data.self, statement: statement, index: index) } - guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else { + guard let bytes = sqlite3_column_blob(sqliteStatement, CInt(index)) else { return Data() } - let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index))) + let count = Int(sqlite3_column_bytes(sqliteStatement, CInt(index))) return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) } func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? { - guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { + guard sqlite3_column_type(sqliteStatement, CInt(index)) != SQLITE_NULL else { return nil } - guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else { + guard let bytes = sqlite3_column_blob(sqliteStatement, CInt(index)) else { return Data() } - let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index))) + let count = Int(sqlite3_column_bytes(sqliteStatement, CInt(index))) return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) } @@ -2328,11 +2183,11 @@ private struct SQLiteStatementRowImpl: RowImpl { var isFetched: Bool { true } func columnName(atUncheckedIndex index: Int) -> String { - String(cString: sqlite3_column_name(sqliteStatement, Int32(index))) + String(cString: sqlite3_column_name(sqliteStatement, CInt(index))) } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue { - DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index)) + DatabaseValue(sqliteStatement: sqliteStatement, index: CInt(index)) } func index(forColumn name: String) -> Int? { diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index d9505506e..978e44ede 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -18,7 +18,7 @@ import Foundation /// row.scopes["b"] // [2, 3, 4] /// row.scopes["c"] // [5, 6] /// row.scopes["d"] // [7, 8] -public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] { +public func splittingRowAdapters(columnCounts: [Int]) -> [any RowAdapter] { guard !columnCounts.isEmpty else { // Identity adapter return [SuffixRowAdapter(fromIndex: 0)] @@ -66,14 +66,14 @@ public struct _LayoutedColumnMapping { /// Use it in your custom RowAdapter type: /// /// struct FooBarAdapter : RowAdapter { - /// func layoutAdapter(layout: _RowLayout) throws -> _LayoutedRowAdapter { + /// func layoutAdapter(layout: _RowLayout) throws -> any _LayoutedRowAdapter { /// return _LayoutedColumnMapping(layoutColumns: [(1, "foo"), (2, "bar")]) /// } /// } /// /// // [foo:"foo" bar: "bar"] /// try Row.fetchOne(db, sql: "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter()) - init(layoutColumns: S) where S.Iterator.Element == (Int, String) { + init(layoutColumns: some Sequence<(Int, String)>) { self._layoutColumns = Array(layoutColumns) self.lowercaseColumnIndexes = Dictionary( layoutColumns @@ -97,7 +97,7 @@ extension _LayoutedColumnMapping: _LayoutedRowAdapter { public var _mapping: _LayoutedColumnMapping { self } /// Returns the empty dictionary. - public var _scopes: [String: _LayoutedRowAdapter] { [:] } + public var _scopes: [String: any _LayoutedRowAdapter] { [:] } } /// :nodoc: @@ -124,7 +124,7 @@ public protocol _LayoutedRowAdapter { var _mapping: _LayoutedColumnMapping { get } /// The layouted row adapters for each scope. - var _scopes: [String: _LayoutedRowAdapter] { get } + var _scopes: [String: any _LayoutedRowAdapter] { get } } /// `_RowLayout` is a protocol that supports the `RowAdapter` protocol. It @@ -169,14 +169,14 @@ public protocol _RowAdapter { /// // column named "foo" whose value is the leftmost value of the /// // base row. /// struct FirstColumnAdapter : RowAdapter { - /// func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + /// func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { /// return _LayoutedColumnMapping(layoutColumns: [(0, "foo")]) /// } /// } /// /// // [foo:1] /// try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: FirstColumnAdapter()) - func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter + func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter } /// `RowAdapter` is a protocol that helps two incompatible row interfaces @@ -208,7 +208,7 @@ extension RowAdapter { /// /// - parameter scopes: A dictionary that maps scope names to /// row adapters. - public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter { + public func addingScopes(_ scopes: [String: any RowAdapter]) -> any RowAdapter { if scopes.isEmpty { return self } else { @@ -218,7 +218,7 @@ extension RowAdapter { } extension RowAdapter { - func baseColumnIndex(atIndex index: Int, layout: _RowLayout) throws -> Int { + func baseColumnIndex(atIndex index: Int, layout: some _RowLayout) throws -> Int { try _layoutedAdapter(from: layout)._mapping.baseColumnIndex(atMappingIndex: index) } } @@ -229,7 +229,7 @@ public struct EmptyRowAdapter: RowAdapter { public init() { } /// :nodoc: - public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { _LayoutedColumnMapping(layoutColumns: []) } } @@ -252,7 +252,7 @@ public struct ColumnMapping: RowAdapter { } /// :nodoc: - public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { let layoutColumns = try mapping .map { (mappedColumn, baseColumn) -> (Int, String) in guard let index = layout._layoutIndex(ofColumn: baseColumn) else { @@ -293,7 +293,7 @@ public struct SuffixRowAdapter: RowAdapter { } /// :nodoc: - public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { _LayoutedColumnMapping(layoutColumns: layout._layoutColumns.suffix(from: index)) } } @@ -322,7 +322,7 @@ public struct RangeRowAdapter: RowAdapter { } /// :nodoc: - public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { _LayoutedColumnMapping(layoutColumns: layout._layoutColumns[range]) } } @@ -352,10 +352,10 @@ public struct RangeRowAdapter: RowAdapter { public struct ScopeAdapter: RowAdapter { /// The base adapter - let base: RowAdapter + let base: any RowAdapter /// The scope adapters - let scopes: [String: RowAdapter] + let scopes: [String: any RowAdapter] /// Creates an adapter that preserves row contents and add scoped rows. /// @@ -392,13 +392,13 @@ public struct ScopeAdapter: RowAdapter { /// row adapters. /// - parameter scopes: A dictionary that maps scope names to /// row adapters. - public init(base: RowAdapter, scopes: [String: RowAdapter]) { + public init(base: some RowAdapter, scopes: [String: any RowAdapter]) { self.base = base self.scopes = scopes } /// :nodoc: - public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { let layoutedAdapter = try base._layoutedAdapter(from: layout) var layoutedScopes = layoutedAdapter._scopes for (name, adapter) in scopes { @@ -413,14 +413,14 @@ public struct ScopeAdapter: RowAdapter { /// The `_LayoutedRowAdapter` for `ScopeAdapter` struct LayoutedScopeAdapter: _LayoutedRowAdapter { let _mapping: _LayoutedColumnMapping - let _scopes: [String: _LayoutedRowAdapter] + let _scopes: [String: any _LayoutedRowAdapter] } struct ChainedAdapter: RowAdapter { - let first: RowAdapter - let second: RowAdapter + let first: any RowAdapter + let second: any RowAdapter - func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { try second._layoutedAdapter(from: first._layoutedAdapter(from: layout)._mapping) } } @@ -444,7 +444,7 @@ public struct RenameColumnAdapter: RowAdapter { } /// :nodoc: - public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { let layoutColumns = layout._layoutColumns.map { (index, column) in (index, transform(column)) } return _LayoutedColumnMapping(layoutColumns: layoutColumns) } @@ -452,13 +452,13 @@ public struct RenameColumnAdapter: RowAdapter { extension Row { /// Creates a row from a base row and a statement adapter - convenience init(base: Row, adapter: _LayoutedRowAdapter) { + convenience init(base: Row, adapter: some _LayoutedRowAdapter) { self.init(impl: AdaptedRowImpl(base: base, adapter: adapter)) } /// Returns self if adapter is nil - func adapted(with adapter: RowAdapter?, layout: _RowLayout) throws -> Row { - guard let adapter = adapter else { + func adapted(with adapter: (any RowAdapter)?, layout: some _RowLayout) throws -> Row { + guard let adapter else { return self } return try Row(base: self, adapter: adapter._layoutedAdapter(from: layout)) @@ -467,10 +467,10 @@ extension Row { struct AdaptedRowImpl: RowImpl { let base: Row - let adapter: _LayoutedRowAdapter + let adapter: any _LayoutedRowAdapter let mapping: _LayoutedColumnMapping - init(base: Row, adapter: _LayoutedRowAdapter) { + init(base: Row, adapter: some _LayoutedRowAdapter) { self.base = base self.adapter = adapter self.mapping = adapter._mapping @@ -503,15 +503,6 @@ struct AdaptedRowImpl: RowImpl { return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex) } - func fastDecodeIfPresent( - _ type: Value.Type, - atUncheckedIndex index: Int) - throws -> Value? - { - let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) - return try Value.fastDecodeIfPresent(fromRow: base, atUncheckedIndex: mappedIndex) - } - func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) return try base.impl.fastDecodeDataNoCopy(atUncheckedIndex: mappedIndex) diff --git a/GRDB/Core/RowDecodingError.swift b/GRDB/Core/RowDecodingError.swift index 54cf0d6f8..e2ca849d4 100644 --- a/GRDB/Core/RowDecodingError.swift +++ b/GRDB/Core/RowDecodingError.swift @@ -1,6 +1,6 @@ /// A key that is used to decode a value in a row @usableFromInline -enum RowKey: Hashable, GRDBSendable { +enum RowKey: Hashable, Sendable { /// A column name case columnName(String) @@ -18,7 +18,7 @@ enum RowKey: Hashable, GRDBSendable { @usableFromInline enum RowDecodingError: Error { @usableFromInline - struct Context: CustomDebugStringConvertible, GRDBSendable { + struct Context: CustomDebugStringConvertible, Sendable { /// A description of what went wrong, for debugging purposes. @usableFromInline let debugDescription: String @@ -78,7 +78,7 @@ enum RowDecodingError: Error { static func valueMismatch( _ type: Any.Type, sqliteStatement: SQLiteStatement, - index: Int32, + index: CInt, context: RowDecodingContext) -> Self { @@ -99,7 +99,7 @@ enum RowDecodingError: Error { valueMismatch( type, context: RowDecodingContext(statement: statement, index: index), - databaseValue: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: Int32(index))) + databaseValue: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: CInt(index))) } /// Convenience method that builds the `column not found: ` @@ -137,7 +137,7 @@ struct RowDecodingContext { } else if let sqliteStatement = row.sqliteStatement { self.key = key self.row = row.copy() - self.sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators) + self.sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement self.statementArguments = nil // Can't rebuild them } else { self.key = key diff --git a/GRDB/Core/SQL.swift b/GRDB/Core/SQL.swift index 19891d08b..cae3770d3 100644 --- a/GRDB/Core/SQL.swift +++ b/GRDB/Core/SQL.swift @@ -10,16 +10,42 @@ /// try db.execute(literal: query) /// } public struct SQL { - /// `SQL` is an array of elements which can be qualified with table - /// aliases. This is how `SQL` can blend well in the query interface. + /// `SQL.Element` is a component of an `SQL` literal. + /// + /// Elements can be qualified with table aliases, and this is how `SQL` + /// blends well in the query interface. See below how the `createdAt` column + /// is qualified with the `player` table in the generated SQL, in order to + /// avoid any conflict with the `team.createdAt` column: + /// + /// func date(_ value: SQLSpecificExpressible) -> SQLExpression { + /// // An SQL literal made of three elements: + /// // - "DATE(" raw sql string + /// // - expression + /// // - ")" raw sql string + /// SQL("DATE(\(value))").sqlExpression + /// } + /// + /// // SELECT player.*, team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamId + /// // WHERE DATE(player.createdAt) = '2022-08-17' + /// let request = Player + /// .filter(date(Column("createdAt")) == "2022-08-17") + /// .including(required: Player.team) enum Element { - // Can't be qualified with a table alias + /// A raw SQL literal with eventual arguments. case sql(String, StatementArguments = StatementArguments()) - // Does not need to be qualified with a table alias + + /// A subquery. case subquery(SQLSubquery) - // Cases below can be qualified with a table alias + + /// An expression. case expression(SQLExpression) + + /// A selection. case selection(SQLSelection) + + /// An ordering. case ordering(SQLOrdering) var isEmpty: Bool { @@ -27,6 +53,17 @@ public struct SQL { case let .sql(sql, _): return sql.isEmpty default: + // Subqueries, expressions, selections and orderings are + // assumed to be non-empty. + // + // Nothing prevents the user from creating an ill-formed empty + // expression, but we don't care about such misuse: + // + // // An ill-formed empty expression + // let expression = SQL("").sqlExpression + // + // let sql: SQL = "\(expression)" + // sql.isEmpty // false, deal with it ¯\_(ツ)_/¯ return false } } @@ -54,7 +91,8 @@ public struct SQL { fileprivate func qualified(with alias: TableAlias) -> Element { switch self { case .sql: - // Can't qualify raw SQL string + /// A raw SQL string can't be qualified with a table alias, + /// because we can't parse it. return self case .subquery: // Subqueries don't need table alias @@ -96,7 +134,7 @@ public struct SQL { /// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ") /// let request = User.select(emailLiteral.sqlExpression) /// let emails = try String.fetchAll(db, request) - public init(_ expression: SQLSpecificExpressible) { + public init(_ expression: some SQLSpecificExpressible) { self.init(elements: [.expression(expression.sqlExpression)]) } @@ -172,7 +210,7 @@ extension SQL: SQLSpecificExpressible { /// Use this property when you need an explicit `SQLExpression`. /// For example: /// - /// func date(_ value: SQLExpressible) -> SQLExpression { + /// func date(_ value: some SQLExpressible) -> SQLExpression { /// SQL("DATE(\(value))").sqlExpression /// } /// @@ -185,20 +223,36 @@ extension SQL: SQLSpecificExpressible { } extension SQL: SQLSelectable { + /// Creates a literal SQL expression. + /// + /// Use this property when you need an explicit `SQLSelection`. For example: + /// + /// // SELECT firstName AS givenName, lastName AS familyName FROM player + /// let selection = SQL("firstName AS givenName, lastName AS familyName").sqlSelection + /// let request = Player.select(selection) public var sqlSelection: SQLSelection { .literal(self) } } extension SQL: SQLOrderingTerm { + /// Creates a literal SQL ordering. + /// + /// Use this property when you need an explicit `SQLOrdering`. For example: + /// + /// // SELECT * FROM player ORDER BY name DESC + /// let ordering = SQL("name DESC").sqlOrdering + /// let request = Player.order(ordering) public var sqlOrdering: SQLOrdering { .literal(self) } } -extension Sequence where Element == SQL { +extension Sequence { /// Returns the concatenated `SQL` literal of this sequence of literals, - /// inserting the given separator between each element. + /// inserting the given raw SQL separator between each element. + /// + /// For example: /// /// let components: [SQL] = [ /// "UPDATE player", @@ -206,6 +260,9 @@ extension Sequence where Element == SQL { /// "WHERE id = \(id)" /// ] /// let query = components.joined(separator: " ") + /// + /// - Note: The separator is a raw SQL string, not an SQL literal that + /// supports [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md). public func joined(separator: String = "") -> SQL { if separator.isEmpty { return SQL(elements: flatMap(\.elements)) @@ -215,9 +272,11 @@ extension Sequence where Element == SQL { } } -extension Collection where Element == SQL { +extension Collection { /// Returns the concatenated `SQL` literal of this collection of literals, - /// inserting the given SQL separator between each element. + /// inserting the given raw SQL separator between each element. + /// + /// For example: /// /// let components: [SQL] = [ /// "UPDATE player", @@ -225,6 +284,9 @@ extension Collection where Element == SQL { /// "WHERE id = \(id)" /// ] /// let query = components.joined(separator: " ") + /// + /// - Note: The separator is a raw SQL string, not an SQL literal that + /// supports [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md). public func joined(separator: String = "") -> SQL { if separator.isEmpty { return SQL(elements: flatMap(\.elements)) diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 04bca77e7..1d97599e2 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -13,14 +13,14 @@ public struct SQLRequest { } /// The request adapter - public var adapter: RowAdapter? + public var adapter: (any RowAdapter)? private(set) var sqlLiteral: SQL let cache: Cache? private init( literal sqlLiteral: SQL, - adapter: RowAdapter?, + adapter: (any RowAdapter)?, fromCache cache: Cache?, type: RowDecoder.Type) { @@ -51,7 +51,7 @@ extension SQLRequest { public init( sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil, + adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( @@ -77,7 +77,7 @@ extension SQLRequest { /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. /// - returns: A SQLRequest - public init(literal sqlLiteral: SQL, adapter: RowAdapter? = nil, cached: Bool = false) { + public init(literal sqlLiteral: SQL, adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( literal: sqlLiteral, adapter: adapter, @@ -86,7 +86,7 @@ extension SQLRequest { } } -extension SQLRequest where RowDecoder == Row { +extension SQLRequest { /// Creates a request from an SQL string, optional arguments, and /// optional row adapter. /// @@ -104,7 +104,7 @@ extension SQLRequest where RowDecoder == Row { public init( sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil, + adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( @@ -130,7 +130,7 @@ extension SQLRequest where RowDecoder == Row { /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. /// - returns: A SQLRequest - public init(literal sqlLiteral: SQL, adapter: RowAdapter? = nil, cached: Bool = false) { + public init(literal sqlLiteral: SQL, adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( literal: sqlLiteral, adapter: adapter, diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index 28f3ede1d..83cb6d17a 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -52,7 +52,7 @@ final class SchedulingWatchdog { GRDBPrecondition(allows(db), message(), file: file, line: line) } - /// Returns true iff the database argument can be used in the current + /// Returns whether the database argument can be used in the current /// dispatch queue. static func allows(_ db: Database) -> Bool { current?.allows(db) ?? false diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 0b261340a..0927f9fc1 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -249,9 +249,7 @@ final class SerializedDatabase { } } -#if swift(>=5.6) && canImport(_Concurrency) // @unchecked because the wrapped `Database` itself is not Sendable. // It happens the job of SerializedDatabase is precisely to provide thread-safe // access to `Database`. extension SerializedDatabase: @unchecked Sendable { } -#endif diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 2017130d5..e43085934 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -3,9 +3,26 @@ import Foundation /// A raw SQLite statement, suitable for the SQLite C API. public typealias SQLiteStatement = OpaquePointer -extension CharacterSet { - /// Statements are separated by semicolons and white spaces - static let sqlStatementSeparators = CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines) +extension String { + /// SQL statements are separated by semicolons and white spaces. + /// + /// This character set is not an accurate representation of actual SQLite + /// separators (which do not include non-ASCII white spaces for example), + /// and must not be used for parsing. Its only purpose is to trim compiled + /// SQL statements with `String.trimmedSQLStatement`. + private static let sqlStatementSeparators = CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines) + + /// Returns a string trimmed from SQL statement separators. + /// + /// For example: + /// + /// // "SELECT * FROM player" + /// " SELECT * FROM player;".trimmedSQLStatement + /// + /// - precondition: the input string is a successfully compiled SQL statement. + var trimmedSQLStatement: String { + trimmingCharacters(in: String.sqlStatementSeparators) + } } /// A statement represents an SQL query. @@ -27,28 +44,30 @@ public final class Statement { SchedulingWatchdog.preconditionValidQueue(database) // trim white space and semicolumn for homogeneous output - return String(cString: sqlite3_sql(sqliteStatement)) - .trimmingCharacters(in: .sqlStatementSeparators) + return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement } /// The column names, ordered from left to right. public lazy var columnNames: [String] = { let sqliteStatement = self.sqliteStatement - return (0.., statementEnd: UnsafeMutablePointer?>, - prepFlags: Int32) throws + prepFlags: CUnsignedInt) throws { SchedulingWatchdog.preconditionValidQueue(database) @@ -92,16 +116,16 @@ public final class Statement { authorizer.reset() var sqliteStatement: SQLiteStatement? = nil - let code: Int32 + let code: CInt // sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20 #if GRDBCUSTOMSQLITE || GRDBCIPHER code = sqlite3_prepare_v3( - database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), + database.sqliteConnection, statementStart, -1, prepFlags, &sqliteStatement, statementEnd) #else if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) { code = sqlite3_prepare_v3( - database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), + database.sqliteConnection, statementStart, -1, prepFlags, &sqliteStatement, statementEnd) } else { code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd) @@ -115,16 +139,16 @@ public final class Statement { sql: String(cString: statementStart)) } - guard let statement = sqliteStatement else { + guard let sqliteStatement else { return nil } self.database = database - self.sqliteStatement = statement + self.sqliteStatement = sqliteStatement self.databaseRegion = authorizer.selectedRegion self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache self.transactionEffect = authorizer.transactionEffect - self.databaseEventKinds = authorizer.databaseEventKinds + self.authorizerEventKinds = authorizer.databaseEventKinds } deinit { @@ -143,7 +167,7 @@ public final class Statement { // Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)" fileprivate lazy var sqliteArgumentNames: [String?] = { - (0..(_ value: T, at index: CInt) { + func bind(_ value: some StatementBinding, at index: CInt) { let code = value.bind(to: sqliteStatement, at: index) // It looks like sqlite3_bind_xxx() functions do not access the file system. @@ -358,12 +382,6 @@ public final 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 { SchedulingWatchdog.allows(database) ? sql : "Statement" @@ -402,15 +420,34 @@ public protocol _DatabaseCursor: Cursor { /// Must be initialized to false. var _isDone: Bool { get set } + /// The statement iterated by the cursor + var _statement: Statement { get } + /// Called after one successful call to `sqlite3_step()`. Returns the /// element for the current statement step. func _element(sqliteStatement: SQLiteStatement) throws -> Element } /// A protocol for cursors that iterate a database statement. -public protocol DatabaseCursor: _DatabaseCursor { - /// The statement iterated by the cursor - var statement: Statement { get } +public protocol DatabaseCursor: _DatabaseCursor { } + +// Read-only access to statement information. We don't want the user to modify +// a statement through a cursor, in case this would mess with the cursor state. +extension DatabaseCursor { + /// The SQL query + public var sql: String { _statement.sql } + + /// The SQL statement arguments. + public var arguments: StatementArguments { _statement.arguments } + + /// The column names, ordered from left to right. + public var columnNames: [String] { _statement.columnNames } + + /// The number of columns in the resulting rows. + public var columnCount: Int { _statement.columnCount } + + /// The database region that the cursor looks into. + public var databaseRegion: DatabaseRegion { _statement.databaseRegion } } extension DatabaseCursor { @@ -419,7 +456,7 @@ extension DatabaseCursor { if _isDone { return nil } - if let element = try statement.step(_element) { + if let element = try _statement.step(_element) { return element } _isDone = true @@ -431,7 +468,9 @@ extension DatabaseCursor { @inlinable public func forEach(_ body: (Element) throws -> Void) throws { if _isDone { return } - try statement.forEachStep { try body(_element(sqliteStatement: $0)) } + try _statement.forEachStep { + try body(_element(sqliteStatement: $0)) + } _isDone = true } } @@ -448,12 +487,12 @@ extension DatabaseCursor { /// } final class StatementCursor: DatabaseCursor { typealias Element = Void - let statement: Statement + let _statement: Statement var _isDone = false // Use Statement.makeCursor() instead init(statement: Statement, arguments: StatementArguments? = nil) throws { - self.statement = statement + self._statement = statement // Assume cursor is created for immediate iteration: reset and set arguments try statement.reset(withArguments: arguments) @@ -462,7 +501,7 @@ final class StatementCursor: DatabaseCursor { deinit { // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. - try? statement.reset() + try? _statement.reset() } @usableFromInline @@ -473,7 +512,7 @@ final class StatementCursor: DatabaseCursor { extension Statement { var releasesDatabaseLock: Bool { - guard let transactionEffect = transactionEffect else { + guard let transactionEffect else { return false } @@ -584,7 +623,7 @@ public protocol StatementBinding { /// .filter(sql: "team = :team", arguments: ["team": "Blue"]) /// .filter(sql: "score > ?", arguments: [1000]) /// .fetchAll(db) -public struct StatementArguments: CustomStringConvertible, Equatable, +public struct StatementArguments: CustomStringConvertible, Hashable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral { private(set) var values: [DatabaseValue] @@ -607,12 +646,12 @@ public struct StatementArguments: CustomStringConvertible, Equatable, /// Creates statement arguments from a sequence of optional values. /// - /// let values: [DatabaseValueConvertible?] = ["foo", 1, nil] + /// let values: [(any DatabaseValueConvertible)?] = ["foo", 1, nil] /// db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values)) /// /// - parameter sequence: A sequence of DatabaseValueConvertible values. /// - returns: A StatementArguments. - public init(_ sequence: Sequence) where Sequence.Element == DatabaseValueConvertible? { + public init(_ sequence: some Sequence<(any DatabaseValueConvertible)?>) { values = sequence.map { $0?.databaseValue ?? .null } namedValues = .init() } @@ -624,7 +663,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, /// /// - parameter sequence: A sequence of DatabaseValueConvertible values. /// - returns: A StatementArguments. - public init(_ sequence: Sequence) where Sequence.Element: DatabaseValueConvertible { + public init(_ sequence: some Sequence) { values = sequence.map(\.databaseValue) namedValues = .init() } @@ -655,12 +694,12 @@ public struct StatementArguments: CustomStringConvertible, Equatable, /// Creates statement arguments from a sequence of (key, value) dictionary, /// such as a dictionary. /// - /// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"] + /// let values: [String: (any DatabaseValueConvertible)?] = ["firstName": nil, "lastName": "Miller"] /// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values)) /// /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. - public init(_ dictionary: [String: DatabaseValueConvertible?]) { + public init(_ dictionary: [String: (any DatabaseValueConvertible)?]) { namedValues = dictionary.mapValues { $0?.databaseValue ?? .null } values = .init() } @@ -668,14 +707,12 @@ public struct StatementArguments: CustomStringConvertible, Equatable, /// Creates statement arguments from a sequence of (key, value) pairs, such /// as a dictionary. /// - /// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"] + /// let values: [String: (any DatabaseValueConvertible)?] = ["firstName": nil, "lastName": "Miller"] /// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values)) /// /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. - public init(_ sequence: Sequence) - where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?) - { + public init(_ sequence: some Sequence<(String, (any DatabaseValueConvertible)?)>) { namedValues = .init(minimumCapacity: sequence.underestimatedCount) for (key, value) in sequence { namedValues[key] = value?.databaseValue ?? .null @@ -691,7 +728,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, /// - parameter dictionary: A dictionary. /// - returns: A StatementArguments. public init?(_ dictionary: [AnyHashable: Any]) { - var initDictionary = [String: DatabaseValueConvertible?]() + var initDictionary = [String: (any DatabaseValueConvertible)?]() for (key, value) in dictionary { guard let columnName = key as? String else { return nil @@ -910,7 +947,7 @@ extension StatementArguments { /// try db.execute( /// sql: "INSERT INTO player (name, score) VALUES (?, ?)" /// arguments: arguments) - public init(arrayLiteral elements: DatabaseValueConvertible?...) { + public init(arrayLiteral elements: (any DatabaseValueConvertible)?...) { self.init(elements) } } @@ -923,7 +960,7 @@ extension StatementArguments { /// try db.execute( /// sql: "INSERT INTO player (name, score) VALUES (:name, :score)" /// arguments: arguments) - public init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) { + public init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) { self.init(elements) } } @@ -933,11 +970,11 @@ extension StatementArguments { /// :nodoc: public var description: String { let valuesDescriptions = values.map(\.description) - let namedValuesDescriptions = namedValues.map { (key, value) -> String in + let namedValuesDescriptions = namedValues.map { (key, value) in "\(String(reflecting: key)): \(value)" } return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]" } } -extension StatementArguments: GRDBSendable { } +extension StatementArguments: Sendable { } diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 8f3cbbf00..0b6eaa025 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -2,14 +2,19 @@ import Glibc #endif -/// A class that gathers information about one statement during its compilation. +/// `StatementAuthorizer` provides information about compiled database +/// statements, and prevents the truncate optimization when row deletions are +/// observed by transaction observers. +/// +/// +/// final class StatementAuthorizer { private unowned var database: Database - /// What this statements reads + /// What a statement reads. var selectedRegion = DatabaseRegion() - /// What this statements writes + /// What a statement writes. var databaseEventKinds: [DatabaseEventKind] = [] /// True if a statement alters the schema in a way that requires @@ -27,6 +32,20 @@ final class StatementAuthorizer { self.database = database } + /// Registers the authorizer with `sqlite3_set_authorizer`. + func register() { + let authorizerP = Unmanaged.passUnretained(self).toOpaque() + sqlite3_set_authorizer( + database.sqliteConnection, + { (authorizerP, actionCode, cString1, cString2, cString3, cString4) in + Unmanaged + .fromOpaque(authorizerP.unsafelyUnwrapped) + .takeUnretainedValue() + .authorize(actionCode, cString1, cString2, cString3, cString4) + }, + authorizerP) + } + /// Reset before compiling a new statement func reset() { selectedRegion = DatabaseRegion() @@ -36,13 +55,13 @@ final class StatementAuthorizer { isDropStatement = false } - func authorize( - _ actionCode: Int32, + private func authorize( + _ actionCode: CInt, _ cString1: UnsafePointer?, _ cString2: UnsafePointer?, _ cString3: UnsafePointer?, _ cString4: UnsafePointer?) - -> Int32 + -> CInt { // Uncomment when debugging // print(""" @@ -74,7 +93,7 @@ final class StatementAuthorizer { guard let columnName = cString2.map(String.init) else { return SQLITE_OK } if columnName.isEmpty { // SELECT COUNT(*) FROM table - selectedRegion.formUnion(DatabaseRegion.fullTable(tableName)) + selectedRegion.formUnion(DatabaseRegion(table: tableName)) } else { // SELECT column FROM table selectedRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName])) @@ -91,18 +110,21 @@ final class StatementAuthorizer { guard let cString1 = cString1 else { return SQLITE_OK } // Deletions from sqlite_master and sqlite_temp_master are not like - // other deletions: the update hook does not notify them, and they - // are prevented when the truncate optimization is disabled. - // Let's authorize such deletions by returning SQLITE_OK: + // other deletions: `sqlite3_update_hook` does not notify them, and + // they are prevented when the truncate optimization is disabled. + // Let's always authorize such deletions by returning SQLITE_OK: guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK } guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK } let tableName = String(cString: cString1) databaseEventKinds.append(.delete(tableName: tableName)) - // Now we prevent the truncate optimization so that transaction - // observers are notified of individual row deletions. - if database.observationBroker.observesDeletions(on: tableName) { + if let observationBroker = database.observationBroker, + observationBroker.observesDeletions(on: tableName) + { + // Prevent the truncate optimization so that + // `sqlite3_update_hook` notifies individual row deletions to + // transaction observers. return SQLITE_IGNORE } else { return SQLITE_OK @@ -152,19 +174,6 @@ final class StatementAuthorizer { if strcmp(cString2, "sqlite_drop_column") == 0 { invalidatesDatabaseSchemaCache = true } - - // Starting SQLite 3.19.0, `SELECT COUNT(*) FROM table` triggers - // an authorization callback for SQLITE_READ with an empty - // column: http://www.sqlite.org/changes.html#version_3_19_0 - // - // Before SQLite 3.19.0, `SELECT COUNT(*) FROM table` does not - // trigger any authorization callback that tells about the - // counted table: any use of the COUNT function makes the - // region undetermined (the full database). - guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK } - if sqlite3_stricmp(cString2, "COUNT") == 0 { - selectedRegion = .fullDatabase - } return SQLITE_OK default: @@ -172,7 +181,7 @@ final class StatementAuthorizer { } } - func insertUpdateEventKind(tableName: String, columnName: String) { + private func insertUpdateEventKind(tableName: String, columnName: String) { for (index, eventKind) in databaseEventKinds.enumerated() { if case .update(let t, let columnNames) = eventKind, t == tableName { var columnNames = columnNames @@ -186,7 +195,7 @@ final class StatementAuthorizer { } private struct AuthorizerActionCode: RawRepresentable, CustomStringConvertible { - let rawValue: Int32 + let rawValue: CInt var description: String { switch rawValue { diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 14d5785cc..b7009b92a 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -19,27 +19,53 @@ /// } /// } public protocol StatementColumnConvertible { - - /// Initializes a value from a raw SQLite statement pointer, if possible. + /// Creates a value from a raw SQLite statement pointer, if possible. /// - /// For example, here is the how Int64 adopts StatementColumnConvertible: + /// This method can be called with a NULL database value. /// - /// extension Int64: StatementColumnConvertible { - /// init?(sqliteStatement: SQLiteStatement, index: Int32) { - /// self = sqlite3_column_int64(sqliteStatement, index) - /// } - /// } - /// - /// This initializer is never called for NULL database values. Just return - /// `nil` for failed conversions: GRDB will interpret a nil result as a - /// decoding failure. - /// - /// See for more information. + /// - warning: Do not customize the default implementation. /// /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - init?(sqliteStatement: SQLiteStatement, index: Int32) + /// - returns: A decoded value, or, if decoding is impossible, nil. + static func fromStatement( + _ sqliteStatement: SQLiteStatement, + atUncheckedIndex index: CInt) + -> Self? + + /// Creates a value from a raw SQLite statement pointer, if possible. + /// + /// For example, here is the how Int64 adopts StatementColumnConvertible: + /// + /// extension Int64: StatementColumnConvertible { + /// init?(sqliteStatement: SQLiteStatement, index: CInt) { + /// self = sqlite3_column_int64(sqliteStatement, index) + /// } + /// } + /// + /// See for more information. + /// + /// - precondition: This initializer must not be called with NULL database + /// values. + /// - parameters: + /// - sqliteStatement: A pointer to an SQLite statement. + /// - index: The column index. + /// - returns: A decoded value, or, if decoding is impossible, nil. + init?(sqliteStatement: SQLiteStatement, index: CInt) +} + +extension StatementColumnConvertible { + // `Optional` overrides this default behavior. + /// Default implementation fails on decoding NULL. + @inline(__always) + @inlinable + public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? { + if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { + return nil + } + return self.init(sqliteStatement: sqliteStatement, index: index) + } } // MARK: - Conversions @@ -48,7 +74,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { @usableFromInline /* private */ static func _valueMismatch( fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, + atUncheckedIndex index: CInt, context: @autoclosure () -> RowDecodingContext) throws -> Never { @@ -59,22 +85,6 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { context: context()) } - @inline(__always) - @inlinable - static func fastDecode( - fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, - context: @autoclosure () -> RowDecodingContext) - throws -> Self - { - guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL, - let value = self.init(sqliteStatement: sqliteStatement, index: index) - else { - try _valueMismatch(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context()) - } - return value - } - @inline(__always) @inlinable static func fastDecode( @@ -85,7 +95,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { if let sqliteStatement = row.sqliteStatement { return try fastDecode( fromStatement: sqliteStatement, - atUncheckedIndex: Int32(index), + atUncheckedIndex: CInt(index), context: RowDecodingContext(row: row, key: .columnIndex(index))) } // Support for fast decoding from adapted rows @@ -94,21 +104,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { @inline(__always) @inlinable - static func fastDecodeIfPresent( + static func fastDecode( fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, + atUncheckedIndex index: CInt, context: @autoclosure () -> RowDecodingContext) - throws -> Self? + throws -> Self { - if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { - return nil - } - guard let value = self.init(sqliteStatement: sqliteStatement, index: index) else { + if let value = fromStatement(sqliteStatement, atUncheckedIndex: index) { + return value + } else { try _valueMismatch(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context()) } - return value } + // Support for Decodable @inline(__always) @inlinable static func fastDecodeIfPresent( @@ -116,14 +125,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { atUncheckedIndex index: Int) throws -> Self? { - if let sqliteStatement = row.sqliteStatement { - return try fastDecodeIfPresent( - fromStatement: sqliteStatement, - atUncheckedIndex: Int32(index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - // Support for fast decoding from adapted rows - return try row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index) + try Optional.fastDecode(fromRow: row, atUncheckedIndex: index) } } @@ -142,16 +144,17 @@ public final class FastDatabaseValueCursor: DatabaseCursor where Value: DatabaseValueConvertible & StatementColumnConvertible { public typealias Element = Value - public let statement: Statement + /// :nodoc: + public let _statement: Statement /// :nodoc: public var _isDone = false - @usableFromInline let columnIndex: Int32 + @usableFromInline let columnIndex: CInt - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - self.statement = statement + init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { + self._statement = statement if let adapter = adapter { // adapter may redefine the index of the leftmost column - columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement)) + columnIndex = try CInt(adapter.baseColumnIndex(atIndex: 0, layout: statement)) } else { columnIndex = 0 } @@ -163,66 +166,16 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible deinit { // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. - try? statement.reset() + try? _statement.reset() } /// :nodoc: @inlinable - public func _element(sqliteStatement: SQLiteStatement) -> Value { - // TODO GRDB6: don't crash on decoding errors - try! Value.fastDecode( + public func _element(sqliteStatement: SQLiteStatement) throws -> Value { + try Value.fastDecode( fromStatement: sqliteStatement, atUncheckedIndex: columnIndex, - context: RowDecodingContext(statement: statement, index: Int(columnIndex))) - } -} - -/// A cursor of optional database values extracted from a single column. -/// For example: -/// -/// try dbQueue.read { db in -/// let emails: FastNullableDatabaseValueCursor = -/// try Optional.fetchCursor(db, sql: "SELECT email FROM player") -/// while let email = emails.next() { // String? -/// print(email ?? "") -/// } -/// } -public final class FastNullableDatabaseValueCursor: DatabaseCursor -where Value: DatabaseValueConvertible & StatementColumnConvertible -{ - public typealias Element = Value? - public let statement: Statement - /// :nodoc: - public var _isDone = false - @usableFromInline let columnIndex: Int32 - - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - self.statement = statement - if let adapter = adapter { - // adapter may redefine the index of the leftmost column - columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement)) - } else { - columnIndex = 0 - } - - // Assume cursor is created for immediate iteration: reset and set arguments - try statement.reset(withArguments: arguments) - } - - deinit { - // Statement reset fails when sqlite3_step has previously failed. - // Just ignore reset error. - try? statement.reset() - } - - /// :nodoc: - @inlinable - public func _element(sqliteStatement: SQLiteStatement) -> Value? { - // TODO GRDB6: don't crash on decoding errors - try! Value.fastDecodeIfPresent( - fromStatement: sqliteStatement, - atUncheckedIndex: columnIndex, - context: RowDecodingContext(statement: statement, index: Int(columnIndex))) + context: RowDecodingContext(statement: _statement, index: Int(columnIndex))) } } @@ -257,7 +210,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> FastDatabaseValueCursor { try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) @@ -277,7 +230,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Self] { try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) @@ -297,11 +250,11 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Self? { - // fetchOne returns nil if there is no row, or if there is a row with a null value - let cursor = try FastNullableDatabaseValueCursor( + // fetchOne handles both a missing row, and one row with a NULL value. + let cursor = try FastDatabaseValueCursor( statement: statement, arguments: arguments, adapter: adapter) @@ -324,7 +277,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) @@ -358,7 +311,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> FastDatabaseValueCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -379,7 +332,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Self] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -400,7 +353,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Self? { try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -423,7 +376,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -513,7 +466,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// A cursor over fetched values. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let strings = try request.fetchCursor(db) // Cursor of String /// while let string = try strings.next() { // String /// ... @@ -533,7 +486,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// An array of fetched values. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let strings = try request.fetchAll(db) // [String] /// /// - parameter db: A database connection. @@ -548,7 +501,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// The result is nil if the request returns no row, or if no value can be /// extracted from the first row. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let string = try request.fetchOne(db) // String? /// /// - parameter db: A database connection. @@ -562,7 +515,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible & Hashable { /// A set of fetched values. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let strings = try request.fetchSet(db) // Set /// /// - parameter db: A database connection. @@ -572,303 +525,3 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol try RowDecoder.fetchSet(db, self) } } - -/// Swift's Optional comes with built-in methods that allow to fetch cursors -/// and arrays of optional DatabaseValueConvertible: -/// -/// 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.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 Prepared Statement - - /// Returns a cursor over optional values fetched from a prepared statement. - /// - /// 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? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispatch queue. - /// - /// - parameters: - /// - statement: The statement to run. - /// - arguments: Optional statement arguments. - /// - adapter: Optional RowAdapter - /// - returns: A cursor over fetched optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor( - _ statement: Statement, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> FastNullableDatabaseValueCursor - { - try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) - } - - /// Returns an array of optional values fetched from a prepared statement. - /// - /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") - /// let names = try Optional.fetchAll(statement) // [String?] - /// - /// - parameters: - /// - statement: The statement to run. - /// - arguments: Optional statement arguments. - /// - adapter: Optional RowAdapter - /// - returns: An array of optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll( - _ statement: Statement, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> [Wrapped?] - { - try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) - } -} - -extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable { - /// Returns a set of optional values fetched from a prepared statement. - /// - /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") - /// let names = try Optional.fetchSet(statement) // Set - /// - /// - parameters: - /// - statement: The statement to run. - /// - arguments: Optional statement arguments. - /// - adapter: Optional RowAdapter - /// - returns: A set of optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet( - _ statement: Statement, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> Set - { - try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) - } -} - -extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible { - - // MARK: Fetching From SQL - - /// Returns a cursor over optional values fetched from an SQL query. - /// - /// let names = try Optional.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String? - /// while let name = try names.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispatch queue. - /// - /// - parameters: - /// - db: A database connection. - /// - sql: An SQL query. - /// - arguments: Statement arguments. - /// - adapter: Optional RowAdapter - /// - returns: A cursor over fetched optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor( - _ db: Database, - sql: String, - arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) - throws -> FastNullableDatabaseValueCursor - { - try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) - } - - /// Returns an array of optional values fetched from an SQL query. - /// - /// let names = try Optional.fetchAll(db, sql: "SELECT name FROM ...") // [String?] - /// - /// - parameters: - /// - db: A database connection. - /// - sql: An SQL query. - /// - arguments: Statement arguments. - /// - adapter: Optional RowAdapter - /// - returns: An array of optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll( - _ db: Database, - sql: String, - arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) - throws -> [Wrapped?] - { - try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) - } -} - -extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable { - /// Returns a set of optional values fetched from an SQL query. - /// - /// let names = try Optional.fetchSet(db, sql: "SELECT name FROM ...") // Set - /// - /// - parameters: - /// - db: A database connection. - /// - sql: An SQL query. - /// - arguments: Statement arguments. - /// - adapter: Optional RowAdapter - /// - returns: A set of optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet( - _ db: Database, - sql: String, - arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) - throws -> Set - { - try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) - } -} - -extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible { - - // MARK: Fetching From FetchRequest - - /// Returns a cursor over optional values fetched from a fetch request. - /// - /// let request = Player.select(Column("name")) - /// let names = try Optional.fetchCursor(db, request) // Cursor of String? - /// while let name = try names.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispatch queue. - /// - /// - parameters: - /// - db: A database connection. - /// - request: A FetchRequest. - /// - returns: A cursor over fetched optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) - throws -> FastNullableDatabaseValueCursor - { - let request = try request.makePreparedRequest(db, forSingleResult: false) - return try fetchCursor(request.statement, adapter: request.adapter) - } - - /// Returns an array of optional values fetched from a fetch request. - /// - /// let request = Player.select(Column("name")) - /// let names = try Optional.fetchAll(db, request) // [String?] - /// - /// - parameters: - /// - db: A database connection. - /// - request: A FetchRequest. - /// - returns: An array of optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: R) throws -> [Wrapped?] { - let request = try request.makePreparedRequest(db, forSingleResult: false) - return try fetchAll(request.statement, adapter: request.adapter) - } -} - -extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable { - /// Returns a set of optional values fetched from a fetch request. - /// - /// let request = Player.select(Column("name")) - /// let names = try Optional.fetchSet(db, request) // Set - /// - /// - parameters: - /// - db: A database connection. - /// - request: A FetchRequest. - /// - returns: A set of optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: R) throws -> Set { - let request = try request.makePreparedRequest(db, forSingleResult: false) - return try fetchSet(request.statement, adapter: request.adapter) - } -} - -extension FetchRequest -where - RowDecoder: _OptionalProtocol, - RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible -{ - - // MARK: Fetching Optional values - - /// A cursor over fetched optional values. - /// - /// let request: ... // Some FetchRequest that fetches Optional - /// let strings = try request.fetchCursor(db) // Cursor of String? - /// while let string = try strings.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispatch queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor { - try Optional.fetchCursor(db, self) - } - - /// An array of fetched optional values. - /// - /// let request: ... // Some FetchRequest that fetches Optional - /// let strings = try request.fetchAll(db) // [String?] - /// - /// - parameter db: A database connection. - /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] { - try Optional.fetchAll(db, self) - } - - /// The first fetched value. - /// - /// The result is nil if the request returns no row, or if no value can be - /// extracted from the first row. - /// - /// let request: ... // Some FetchRequest that fetches String? - /// let string = try request.fetchOne(db) // String? - /// - /// - parameter db: A database connection. - /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? { - try RowDecoder.Wrapped.fetchOne(db, self) - } -} - -extension FetchRequest -where - RowDecoder: _OptionalProtocol, - RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable -{ - /// A set of fetched optional values. - /// - /// let request: ... // Some FetchRequest that fetches Optional - /// let strings = try request.fetchSet(db) // Set - /// - /// - parameter db: A database connection. - /// - returns: A set of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { - try Optional.fetchSet(db, self) - } -} diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index ec5d1c1ad..7248b6fc0 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -2,7 +2,7 @@ import Foundation /// Data is convertible to and from DatabaseValue. extension Data: DatabaseValueConvertible, StatementColumnConvertible { - public init(sqliteStatement: SQLiteStatement, index: Int32) { + public init(sqliteStatement: SQLiteStatement, index: CInt) { if let bytes = sqlite3_column_blob(sqliteStatement, index) { let count = Int(sqlite3_column_bytes(sqliteStatement, index)) self.init(bytes: bytes, count: count) // copy bytes @@ -33,7 +33,7 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible { public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { withUnsafeBytes { - sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT) + sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT) } } } @@ -43,21 +43,21 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible { extension Data { static func fastDecodeNoCopy( fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, + atUncheckedIndex index: CInt, context: @autoclosure () -> RowDecodingContext) throws -> Data { - guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { + guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else { throw RowDecodingError.valueMismatch( Data.self, sqliteStatement: sqliteStatement, index: index, context: context()) } - guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else { + guard let bytes = sqlite3_column_blob(sqliteStatement, index) else { return Data() } - let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index))) + let count = Int(sqlite3_column_bytes(sqliteStatement, index)) return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) } @@ -69,7 +69,7 @@ extension Data { if let sqliteStatement = row.sqliteStatement { return try fastDecodeNoCopy( fromStatement: sqliteStatement, - atUncheckedIndex: Int32(index), + atUncheckedIndex: CInt(index), context: RowDecodingContext(row: row, key: .columnIndex(index))) } // Support for fast decoding from adapted rows @@ -78,17 +78,17 @@ extension Data { static func fastDecodeNoCopyIfPresent( fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, + atUncheckedIndex index: CInt, context: @autoclosure () -> RowDecodingContext) -> Data? { - guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { + guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else { return nil } - guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else { + guard let bytes = sqlite3_column_blob(sqliteStatement, index) else { return Data() } - let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index))) + let count = Int(sqlite3_column_bytes(sqliteStatement, index)) return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) } @@ -100,7 +100,7 @@ extension Data { if let sqliteStatement = row.sqliteStatement { return fastDecodeNoCopyIfPresent( fromStatement: sqliteStatement, - atUncheckedIndex: Int32(index), + atUncheckedIndex: CInt(index), context: RowDecodingContext(row: row, key: .columnIndex(index))) } // Support for fast decoding from adapted rows diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 20dff9652..37463d044 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -71,17 +71,17 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { guard let cString = sqlite3_column_text(sqliteStatement, index) else { return nil } let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen - let optionalComponents = cString.withMemoryRebound( + let components = cString.withMemoryRebound( to: Int8.self, capacity: length + 1 /* trailing \0 */) { cString in SQLiteDateParser().components(cString: cString, length: length) } - guard let components = optionalComponents else { + guard let components else { return nil } self.init(components.dateComponents, format: components.format) diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index 505632efe..cc1d9490a 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -120,7 +120,7 @@ extension Date: StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_INTEGER, SQLITE_FLOAT: self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, index)) diff --git a/GRDB/Core/Support/Foundation/Decimal.swift b/GRDB/Core/Support/Foundation/Decimal.swift index 56f1533b8..07b72f168 100644 --- a/GRDB/Core/Support/Foundation/Decimal.swift +++ b/GRDB/Core/Support/Foundation/Decimal.swift @@ -28,7 +28,7 @@ extension Decimal: DatabaseValueConvertible { extension Decimal: StatementColumnConvertible { @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_INTEGER: self.init(sqlite3_column_int64(sqliteStatement, index)) diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 3e88a7aa6..8802db099 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -51,7 +51,7 @@ extension UUID: DatabaseValueConvertible { extension UUID: StatementColumnConvertible { @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_TEXT: let string = String(cString: sqlite3_column_text(sqliteStatement, index)!) diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift index b65e64a34..0ac8736c6 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift @@ -2,7 +2,7 @@ import Foundation private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { let dbValue: DatabaseValue - let codingPath: [CodingKey] + let codingPath: [any CodingKey] /// Decodes a null value. /// @@ -153,7 +153,7 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { private struct DatabaseValueDecoder: Decoder { let dbValue: DatabaseValue - let codingPath: [CodingKey] + let codingPath: [any CodingKey] var userInfo: [CodingUserInfoKey: Any] { [:] } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift index 5682ca7c9..f9f7127d8 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift @@ -3,7 +3,7 @@ import Foundation private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { let encode: (DatabaseValue) -> Void - var codingPath: [CodingKey] { [] } + var codingPath: [any CodingKey] { [] } /// Encodes a null value. /// @@ -37,7 +37,7 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: T) throws where T: Encodable { - if let dbValueConvertible = value as? DatabaseValueConvertible { + if let dbValueConvertible = value as? any DatabaseValueConvertible { // Prefer DatabaseValueConvertible encoding over Decodable. // This allows us to encode Date as String, for example. encode(dbValueConvertible.databaseValue) @@ -57,7 +57,7 @@ private class DatabaseValueEncoder: Encoder { /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. - var codingPath: [CodingKey] { [] } + var codingPath: [any CodingKey] { [] } /// Any contextual information set by the user for encoding. var userInfo: [CodingUserInfoKey: Any] = [:] @@ -119,10 +119,8 @@ private class DatabaseValueEncoder: Encoder { 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 - } + // 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 diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift index b49824f5e..a8c06371a 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift @@ -10,6 +10,8 @@ extension SQLOrderingTerm where Self: RawRepresentable, Self.RawValue: SQLOrderi } } +extension SQLSpecificExpressible where Self: RawRepresentable, Self.RawValue: SQLSpecificExpressible { } + extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpressible { /// Returns the raw value as an SQL expression. public var sqlExpression: SQLExpression { @@ -23,6 +25,30 @@ extension StatementBinding where Self: RawRepresentable, Self.RawValue: Statemen } } +/// `StatementColumnConvertible` is free for `RawRepresentable` types whose raw +/// value is itself `StatementColumnConvertible`. +/// +/// // If the RawValue adopts StatementColumnConvertible... +/// enum Color : Int { +/// case red +/// case white +/// case rose +/// } +/// +/// // ... then the RawRepresentable type can freely +/// // adopt StatementColumnConvertible: +/// extension Color: StatementColumnConvertible { } +extension StatementColumnConvertible where Self: RawRepresentable, Self.RawValue: StatementColumnConvertible { + @inline(__always) + @inlinable + public init?(sqliteStatement: SQLiteStatement, index: CInt) { + guard let rawValue = RawValue(sqliteStatement: sqliteStatement, index: index) else { + return nil + } + self.init(rawValue: rawValue) + } +} + /// `DatabaseValueConvertible` is free for `RawRepresentable` types whose raw /// value is itself `DatabaseValueConvertible`. /// diff --git a/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift b/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift index 8ab622a19..96e9d041f 100644 --- a/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift +++ b/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift @@ -2,7 +2,7 @@ struct JSONRequiredError: Error { } /// The encoder that always ends up with a JSONRequiredError struct JSONRequiredEncoder: Encoder { - var codingPath: [CodingKey] + var codingPath: [any CodingKey] var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { @@ -15,7 +15,7 @@ struct JSONRequiredEncoder: Encoder { func singleValueContainer() -> SingleValueEncodingContainer { self } struct KeyedContainer: KeyedEncodingContainerProtocol { - var codingPath: [CodingKey] + var codingPath: [any CodingKey] var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } // swiftlint:disable comma diff --git a/GRDB/Core/Support/StandardLibrary/Optional.swift b/GRDB/Core/Support/StandardLibrary/Optional.swift new file mode 100644 index 000000000..4c9e3a3b9 --- /dev/null +++ b/GRDB/Core/Support/StandardLibrary/Optional.swift @@ -0,0 +1,97 @@ +extension Optional: StatementBinding where Wrapped: StatementBinding { + public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { + switch self { + case .none: + return sqlite3_bind_null(sqliteStatement, index) + case let .some(value): + return value.bind(to: sqliteStatement, at: index) + } + } +} + +extension Optional: SQLExpressible where Wrapped: SQLExpressible { + public var sqlExpression: SQLExpression { + switch self { + case .none: + return .null + case let .some(value): + return value.sqlExpression + } + } +} + +extension Optional: SQLOrderingTerm where Wrapped: SQLOrderingTerm { + public var sqlOrdering: SQLOrdering { + switch self { + case .none: + return .expression(.null) + case let .some(value): + return value.sqlOrdering + } + } +} + +extension Optional: SQLSelectable where Wrapped: SQLSelectable { + public var sqlSelection: SQLSelection { + switch self { + case .none: + return .expression(.null) + case let .some(value): + return value.sqlSelection + } + } +} + +extension Optional: SQLSpecificExpressible where Wrapped: SQLSpecificExpressible { } + +extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvertible { + public var databaseValue: DatabaseValue { + switch self { + case .none: + return .null + case let .some(value): + return value.databaseValue + } + } + + public static func fromMissingColumn() -> Self? { + .some(.none) // success + } + + public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { + if let value = Wrapped.fromDatabaseValue(dbValue) { + // Valid value + return value + } else if dbValue.isNull { + // NULL + return .some(.none) + } else { + // Invalid value + return .none + } + } +} + +extension Optional: StatementColumnConvertible where Wrapped: StatementColumnConvertible { + @inline(__always) + @inlinable + public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? { + if let value = Wrapped.fromStatement(sqliteStatement, atUncheckedIndex: index) { + // Valid value + return value + } else if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { + // NULL + return .some(.none) + } else { + // Invalid value + return .none + } + } + + public init?(sqliteStatement: SQLiteStatement, index: CInt) { + guard let value = Wrapped(sqliteStatement: sqliteStatement, index: index) else { + return nil + } + self = .some(value) + } +} diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index f2163cd75..1cb6a403d 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -8,7 +8,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible { /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - public init(sqliteStatement: SQLiteStatement, index: Int32) { + public init(sqliteStatement: SQLiteStatement, index: CInt) { self = sqlite3_column_int64(sqliteStatement, index) != 0 } @@ -100,7 +100,7 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { let int64 = sqlite3_column_int64(sqliteStatement, index) guard let v = Int(exactly: int64) else { return nil } self = v @@ -131,7 +131,7 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { let int64 = sqlite3_column_int64(sqliteStatement, index) guard let v = Int8(exactly: int64) else { return nil } self = v @@ -162,7 +162,7 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { let int64 = sqlite3_column_int64(sqliteStatement, index) guard let v = Int16(exactly: int64) else { return nil } self = v @@ -193,7 +193,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { let int64 = sqlite3_column_int64(sqliteStatement, index) guard let v = Int32(exactly: int64) else { return nil } self = v @@ -222,7 +222,7 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible { /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - public init(sqliteStatement: SQLiteStatement, index: Int32) { + public init(sqliteStatement: SQLiteStatement, index: CInt) { self = sqlite3_column_int64(sqliteStatement, index) } @@ -260,7 +260,7 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { let int64 = sqlite3_column_int64(sqliteStatement, index) guard let v = UInt(exactly: int64) else { return nil } self = v @@ -291,7 +291,7 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { let int64 = sqlite3_column_int64(sqliteStatement, index) guard let v = UInt8(exactly: int64) else { return nil } self = v @@ -322,7 +322,7 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { let int64 = sqlite3_column_int64(sqliteStatement, index) guard let v = UInt16(exactly: int64) else { return nil } self = v @@ -353,7 +353,7 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { let int64 = sqlite3_column_int64(sqliteStatement, index) guard let v = UInt32(exactly: int64) else { return nil } self = v @@ -384,7 +384,7 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { let int64 = sqlite3_column_int64(sqliteStatement, index) guard let v = UInt64(exactly: int64) else { return nil } self = v @@ -413,7 +413,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible { /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - public init(sqliteStatement: SQLiteStatement, index: Int32) { + public init(sqliteStatement: SQLiteStatement, index: CInt) { self = sqlite3_column_double(sqliteStatement, index) } @@ -447,7 +447,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible { /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - public init(sqliteStatement: SQLiteStatement, index: Int32) { + public init(sqliteStatement: SQLiteStatement, index: CInt) { self = Float(sqlite3_column_double(sqliteStatement, index)) } @@ -481,7 +481,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible { /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - public init(sqliteStatement: SQLiteStatement, index: Int32) { + public init(sqliteStatement: SQLiteStatement, index: CInt) { self = String(cString: sqlite3_column_text(sqliteStatement, index)!) } @@ -587,7 +587,6 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.localizedCapitalized) /// let names = try String.fetchAll(dbQueue, request) // [String] - @available(OSX 10.11, watchOS 3.0, *) public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in guard let string = String.fromDatabaseValue(dbValues[0]) else { @@ -608,7 +607,6 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.localizedLowercased) /// let names = try String.fetchAll(dbQueue, request) // [String] - @available(OSX 10.11, watchOS 3.0, *) public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in guard let string = String.fromDatabaseValue(dbValues[0]) else { @@ -629,7 +627,6 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.localizedUppercased) /// let names = try String.fetchAll(dbQueue, request) // [String] - @available(OSX 10.11, watchOS 3.0, *) public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in guard let string = String.fromDatabaseValue(dbValues[0]) else { diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index ffdd7cf02..2d1a41e99 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -5,75 +5,93 @@ extension Database { /// Add a transaction observer, so that it gets notified of /// database changes. /// + /// This method has no effect on read-only database connections. + /// /// - parameter transactionObserver: A transaction observer. /// - parameter extent: The duration of the observation. The default is /// the observer lifetime (observation lasts until observer /// is deallocated). public func add( - transactionObserver: TransactionObserver, + transactionObserver: some TransactionObserver, extent: TransactionObservationExtent = .observerLifetime) { SchedulingWatchdog.preconditionValidQueue(self) + guard let observationBroker else { return } // Drop cached statements that delete, because the addition of an // observer may change the need for truncate optimization prevention. - publicStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) } - internalStatementCache.removeAll{ $0.databaseEventKinds.contains(where: \.isDelete) } + publicStatementCache.removeAll { $0.isDeleteStatement } + internalStatementCache.removeAll{ $0.isDeleteStatement } observationBroker.add(transactionObserver: transactionObserver, extent: extent) } /// Remove a transaction observer. - public func remove(transactionObserver: TransactionObserver) { + public func remove(transactionObserver: some TransactionObserver) { SchedulingWatchdog.preconditionValidQueue(self) + guard let observationBroker else { return } // Drop cached statements that delete, because the removal of an // observer may change the need for truncate optimization prevention. - publicStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) } - internalStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) } + publicStatementCache.removeAll { $0.isDeleteStatement } + internalStatementCache.removeAll { $0.isDeleteStatement } observationBroker.remove(transactionObserver: transactionObserver) } - /// Registers a closure to be executed after the next or current + /// Registers closures to be executed after the next or current /// transaction completion. /// /// try dbQueue.write { db in - /// db.afterNextTransactionCommit { _ in + /// db.afterNextTransaction { _ in /// print("success") /// } /// ... - /// } // prints "success" + /// } // prints "commit" /// - /// If the transaction is rollbacked, the closure is not executed. + /// Closure are executed in a protected dispatch queue, serialized will all + /// database updates. /// - /// If the transaction is committed, the closure is executed in a protected - /// dispatch queue, serialized will all database updates. - public func afterNextTransactionCommit(_ closure: @escaping (Database) -> Void) { - class CommitHandler: TransactionObserver { - let closure: (Database) -> Void - - init(_ closure: @escaping (Database) -> Void) { - self.closure = closure + /// - precondition: Database is not read-only. + /// - parameter onCommit: A closure execute on transaction commit. + /// - parameter onRollback: A closure execute on transaction rollback. + public func afterNextTransaction( + onCommit: @escaping (Database) -> Void, + onRollback: @escaping (Database) -> Void = { _ in }) + { + class TransactionHandler: TransactionObserver { + let onCommit: (Database) -> Void + let onRollback: (Database) -> Void + + init(onCommit: @escaping (Database) -> Void, onRollback: @escaping (Database) -> Void) { + self.onCommit = onCommit + self.onRollback = onRollback } - // Ignore individual changes and transaction rollbacks + // Ignore changes func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } func databaseDidChange(with event: DatabaseEvent) { } - func databaseDidRollback(_ db: Database) { } - // On commit, run closure func databaseDidCommit(_ db: Database) { - closure(db) + onCommit(db) + } + + func databaseDidRollback(_ db: Database) { + onRollback(db) } } - add(transactionObserver: CommitHandler(closure), extent: .nextTransaction) + // We don't notify read-only transactions to transaction observers + GRDBPrecondition(!isReadOnly, "Read-only transactions are not notified") + + add( + transactionObserver: TransactionHandler(onCommit: onCommit, onRollback: onRollback), + extent: .nextTransaction) } - /// The extent of a transaction observation + /// The extent of a transaction observation. /// - /// See Database.add(transactionObserver:extent:) + /// See ``Database/add(transactionObserver:extent:)``. public enum TransactionObservationExtent { /// Observation lasts until observer is deallocated case observerLifetime @@ -160,7 +178,7 @@ extension Database { /// /// try db.execute(sql: "COMMIT") /// -/// During the statement *execution*, SQlite tells the broker that the +/// During the statement *execution*, SQLite tells the broker that the /// transaction is about to be committed through sqlite3_commit_hook. The broker /// invokes observer.databaseWillCommit(). If the observer throws an error, the /// broker asks SQLite to rollback the transaction. Otherwise, the broker lets @@ -169,20 +187,32 @@ extension Database { /// After the statement *has been executed*, the broker calls /// observer.databaseDidCommit(). class DatabaseObservationBroker { - private unowned var database: Database - private var savepointStack = SavepointStack() - private var transactionState: TransactionState = .none + private unowned let database: Database + + /// The savepoint stack allows us to hold database event notifications until + /// all savepoints are released. The goal is to only tell transaction + /// observers about database changes that have a chance to be committed + /// on disk. + private let savepointStack = SavepointStack() + + /// Tracks the transaction completion, as reported by the + /// `sqlite3_commit_hook` and `sqlite3_rollback_hook` callbacks. + private var transactionCompletion = TransactionCompletion.none + + /// The registered transaction observers. private var transactionObservations: [TransactionObservation] = [] + + /// The observers for an individual statement execution. private var statementObservations: [StatementObservation] = [] { - didSet { observesDatabaseChanges = !statementObservations.isEmpty } - } - private var observesDatabaseChanges = false { didSet { - if observesDatabaseChanges == oldValue { return } - if observesDatabaseChanges { - installUpdateHook() - } else { - uninstallUpdateHook() + let isEmpty = statementObservations.isEmpty + if isEmpty != oldValue.isEmpty { + if isEmpty { + // Avoid processing database changes if nobody is interested + uninstallUpdateHook() + } else { + installUpdateHook() + } } } } @@ -193,25 +223,26 @@ class DatabaseObservationBroker { // MARK: - Transaction observers - func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent) { + func add(transactionObserver: some TransactionObserver, extent: Database.TransactionObservationExtent) { transactionObservations.append(TransactionObservation(observer: transactionObserver, extent: extent)) } - func remove(transactionObserver: TransactionObserver) { + func remove(transactionObserver: some TransactionObserver) { transactionObservations.removeFirst { $0.isWrapping(transactionObserver) } } - func disableUntilNextTransaction(transactionObserver: TransactionObserver) { + /// Called from ``TransactionObserver/stopObservingDatabaseChangesUntilNextTransaction()``. + func disableUntilNextTransaction(transactionObserver: some TransactionObserver) { if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) { - observation.isDisabled = true - statementObservations.removeFirst { $0.0 === observation } + observation.isEnabled = false + statementObservations.removeFirst { $0.transactionObservation === observation } } } // MARK: - Statement execution - /// Returns true if there exists some transaction observers interested in - /// deletions in the given table. + /// Returns true if there exists some transaction observer interested in + /// the deletions in the given table. func observesDeletions(on table: String) -> Bool { transactionObservations.contains { observation in observation.observes(eventsOfKind: .delete(tableName: table)) @@ -230,14 +261,15 @@ class DatabaseObservationBroker { // SchedulingWatchdog.current: SchedulingWatchdog.current!.databaseObservationBroker = self - // Fill statementObservations with observations that are interested in - // the kind of events performed by the statement. + // Fill statementObservations with observations that are interested + // in the kind of database events performed by the statement, as + // reported by `sqlite3_set_authorizer`. // // Those statementObservations will be notified of individual changes // in databaseWillChange() and databaseDidChange(). - let eventKinds = statement.databaseEventKinds + let authorizerEventKinds = statement.authorizerEventKinds - switch eventKinds.count { + switch authorizerEventKinds.count { case 0: // Statement has no effect on any database table. // @@ -250,15 +282,17 @@ class DatabaseObservationBroker { // // For example, if one observes all deletions in the table T, then // all individual deletions of DELETE FROM T are notified: - let eventKind = eventKinds[0] + let eventKind = authorizerEventKinds[0] statementObservations = transactionObservations.compactMap { observation in guard observation.observes(eventsOfKind: eventKind) else { // observation is not interested return nil } - // observation will be notified of all individual events - return (observation, DatabaseEventPredicate.true) + // Observation will be notified of all individual events + return StatementObservation( + transactionObservation: observation, + trackingEvents: .all) } default: // We'll execute a complex statement with side effects performed by @@ -270,39 +304,39 @@ class DatabaseObservationBroker { // by the mean of a foreign key action, then when one only observes // deletions in T1, one must not be notified of deletions in T2: statementObservations = transactionObservations.compactMap { observation in - let observedKinds = eventKinds.filter(observation.observes) - if observedKinds.isEmpty { + let observedEventKinds = authorizerEventKinds.filter(observation.observes) + if observedEventKinds.isEmpty { // observation is not interested return nil } - // observation will only be notified of individual events that - // match one of the observed kinds. - return ( - observation, - DatabaseEventPredicate.matching( - observedKinds: observedKinds, - advertisedKinds: eventKinds)) + // Observation will only be notified of individual events + // it is interested into. + return StatementObservation( + transactionObservation: observation, + trackingEvents: .matching( + observedEventKinds: observedEventKinds, + authorizerEventKinds: authorizerEventKinds)) } } } - transactionState = .none + transactionCompletion = .none } - /// May throw a cancelled commit error, if a transaction observer cancels - /// a transaction. + /// May throw the user-provided cancelled commit error, if a transaction + /// observer has cancelled a transaction. func statementDidFail(_ statement: Statement) throws { // Undo statementWillExecute statementObservations = [] SchedulingWatchdog.current!.databaseObservationBroker = nil - // Reset transactionState before databaseDidRollback eventually + // Reset transactionCompletion before databaseDidRollback eventually // executes other statements. - let transactionState = self.transactionState - self.transactionState = .none + let transactionCompletion = self.transactionCompletion + self.transactionCompletion = .none - switch transactionState { + switch transactionCompletion { case .rollback: // Don't notify observers because we're in a failed implicit // transaction here (like an INSERT which fails with @@ -316,8 +350,9 @@ class DatabaseObservationBroker { } } - /// May throw a cancelled commit error, if a transaction observer cancels - /// an empty transaction. + /// May throw the user-provided cancelled commit error, if the statement + /// commits an empty transaction, and a transaction observer cancels this + /// empty transaction. func statementDidExecute(_ statement: Statement) throws { // Undo statementWillExecute if transactionObservations.isEmpty == false { @@ -332,7 +367,7 @@ class DatabaseObservationBroker { break case .commitTransaction: // 1. A COMMIT statement has been executed - if case .none = self.transactionState { // 2. sqlite3_commit_hook was not triggered + if case .none = transactionCompletion { // 2. sqlite3_commit_hook was not called // 1+2 mean that an empty deferred transaction has been completed: // // BEGIN DEFERRED TRANSACTION; COMMIT @@ -351,7 +386,7 @@ class DatabaseObservationBroker { case .releaseSavepoint(let name): // 1. A RELEASE SAVEPOINT statement has been executed savepointStack.savepointDidRelease(name) - if case .none = self.transactionState, // 2. sqlite3_commit_hook was not triggered + if case .none = transactionCompletion, // 2. sqlite3_commit_hook was not called !database.isInsideTransaction // 3. database is no longer inside a transaction { // 1+2+3 mean that an empty deferred transaction has been completed: @@ -372,12 +407,12 @@ class DatabaseObservationBroker { } } - // Reset transactionState before databaseDidCommit or + // Reset transactionCompletion before databaseDidCommit or // databaseDidRollback eventually execute other statements. - let transactionState = self.transactionState - self.transactionState = .none + let transactionCompletion = self.transactionCompletion + self.transactionCompletion = .none - switch transactionState { + switch transactionCompletion { case .commit: databaseDidCommit() case .rollback: @@ -394,8 +429,8 @@ class DatabaseObservationBroker { if savepointStack.isEmpty { // Notify now - for (observation, predicate) in statementObservations where predicate.evaluate(event) { - observation.databaseWillChange(with: event) + for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) { + statementObservation.transactionObservation.databaseWillChange(with: event) } } else { // Buffer @@ -419,8 +454,8 @@ class DatabaseObservationBroker { if savepointStack.isEmpty { // Notify now - for (observation, predicate) in statementObservations where predicate.evaluate(event) { - observation.databaseDidChange(with: event) + for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) { + statementObservation.transactionObservation.databaseDidChange(with: event) } } else { // Buffer @@ -476,7 +511,7 @@ class DatabaseObservationBroker { // // For example, is the code below expected to print "did commit"? // - // db.afterNextTransactionCommit { _ in print("did commit") } + // db.afterNextTransaction { _ in print("did commit") } // try db.inTransaction { // performSomeTask(db) // return .commit @@ -511,15 +546,19 @@ class DatabaseObservationBroker { databaseDidEndTransaction() } - /// Remove transaction observers that have stopped observing transaction, - /// and uninstall SQLite update hooks if there is no remaining observers. + // Called from both databaseDidCommit() and databaseDidRollback() private func databaseDidEndTransaction() { assert(!database.isInsideTransaction) + + // Remove transaction observations that are no longer observing, because + // a transaction observer registered with the `.observerLifetime` extent + // was deallocated, or because a transaction observer was registered + // with the `.nextTransaction` extent. transactionObservations = transactionObservations.filter(\.isObserving) // Undo disableUntilNextTransaction(transactionObserver:) for observation in transactionObservations { - observation.isDisabled = false + observation.isEnabled = true } } @@ -570,14 +609,13 @@ class DatabaseObservationBroker { } // Now we can safely notify: - let eventsBuffer = savepointStack.eventsBuffer savepointStack.clear() for (event, statementObservations) in eventsBuffer { assert(statementObservations.isEmpty || !database.isReadOnly, "Read-only transactions are not notified") - for (observation, predicate) in statementObservations where predicate.evaluate(event) { - event.send(to: observation) + for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) { + event.send(to: statementObservation.transactionObservation) } } } @@ -591,11 +629,11 @@ class DatabaseObservationBroker { let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() do { try broker.databaseWillCommit() - broker.transactionState = .commit - // Next step: statementDidExecute() + broker.transactionCompletion = .commit + // Next step: statementDidExecute(_:) return 0 } catch { - broker.transactionState = .cancelledCommit(error) + broker.transactionCompletion = .cancelledCommit(error) // Next step: sqlite3_rollback_hook callback return 1 } @@ -603,13 +641,13 @@ class DatabaseObservationBroker { sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() - switch broker.transactionState { + switch broker.transactionCompletion { case .cancelledCommit: - // Next step: statementDidFail() + // Next step: statementDidFail(_:) break default: - broker.transactionState = .rollback - // Next step: statementDidExecute() + broker.transactionCompletion = .rollback + // Next step: statementDidExecute(_:) } }, brokerPointer) } @@ -656,11 +694,20 @@ class DatabaseObservationBroker { #endif } - /// The various states of SQLite transactions - enum TransactionState { + /// The various SQLite transactions completions, as reported by the + /// `sqlite3_commit_hook` and `sqlite3_rollback_hook` callbacks. + fileprivate enum TransactionCompletion { + /// Transaction state is unchanged. case none + + /// Transaction turns committed. case commit + + /// Transaction turns rollbacked. case rollback + + /// Transaction turns rollbacked because a transaction observer has + /// cancelled a commit by throwing an error. case cancelledCommit(Error) } } @@ -737,8 +784,7 @@ public protocol TransactionObserver: AnyObject { /// /// **Availability Info** /// - /// Requires SQLite 3.13.0 + - /// Compiled with option SQLITE_ENABLE_PREUPDATE_HOOK + /// Requires SQLite compiled with option SQLITE_ENABLE_PREUPDATE_HOOK. /// /// 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 @@ -800,19 +846,19 @@ extension TransactionObserver { final class TransactionObservation { let extent: Database.TransactionObservationExtent - // A disabled observation is not interested in individual database changes. - // It is still interested in transactions commits & rollbacks. - var isDisabled = false + /// A disabled observation is not interested in individual database changes. + /// It is still interested in transactions commits & rollbacks. + var isEnabled = true - private weak var weakObserver: TransactionObserver? - private var strongObserver: TransactionObserver? - private var observer: TransactionObserver? { strongObserver ?? weakObserver } + private weak var weakObserver: (any TransactionObserver)? + private var strongObserver: (any TransactionObserver)? + private var observer: (any TransactionObserver)? { strongObserver ?? weakObserver } fileprivate var isObserving: Bool { observer != nil } - init(observer: TransactionObserver, extent: Database.TransactionObservationExtent) { + init(observer: some TransactionObserver, extent: Database.TransactionObservationExtent) { self.extent = extent switch extent { case .observerLifetime: @@ -825,24 +871,23 @@ final class TransactionObservation { } } - func isWrapping(_ observer: TransactionObserver) -> Bool { + func isWrapping(_ observer: some TransactionObserver) -> Bool { self.observer === observer } func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - if isDisabled { return false } - return observer?.observes(eventsOfKind: eventKind) ?? false + observer?.observes(eventsOfKind: eventKind) ?? false } #if SQLITE_ENABLE_PREUPDATE_HOOK func databaseWillChange(with event: DatabasePreUpdateEvent) { - if isDisabled { return } + guard isEnabled else { return } observer?.databaseWillChange(with: event) } #endif func databaseDidChange(with event: DatabaseEvent) { - if isDisabled { return } + guard isEnabled else { return } observer?.databaseDidChange(with: event) } @@ -859,6 +904,7 @@ final class TransactionObservation { // Observer must not get any further notification. // So we "forget" the observer before its `databaseDidCommit` // implementation eventually triggers another database change. + assert(weakObserver == nil, "expected observer to be stored in strongObserver") strongObserver = nil observer.databaseDidCommit(db) } @@ -874,6 +920,7 @@ final class TransactionObservation { // Observer must not get any further notification. // So we "forget" the observer before its `databaseDidRollback` // implementation eventually triggers another database change. + assert(weakObserver == nil, "expected observer to be stored in strongObserver") strongObserver = nil observer.databaseDidRollback(db) } @@ -881,7 +928,19 @@ final class TransactionObservation { } } -typealias StatementObservation = (TransactionObservation, DatabaseEventPredicate) +/// The observation of one particular statement, by a particular +/// transaction observer. +struct StatementObservation { + var transactionObservation: TransactionObservation + + /// Filters database events that should be notified. + var predicate: DatabaseEventPredicate + + init(transactionObservation: TransactionObservation, trackingEvents predicate: DatabaseEventPredicate) { + self.transactionObservation = transactionObservation + self.predicate = predicate + } +} // MARK: - Database events @@ -901,15 +960,15 @@ public enum DatabaseEventKind { var modifiedRegion: DatabaseRegion { switch self { case let .delete(tableName): - return DatabaseRegion.fullTable(tableName) + return DatabaseRegion(table: tableName) case let .insert(tableName): - return DatabaseRegion.fullTable(tableName) + return DatabaseRegion(table: tableName) case let .update(tableName, updatedColumnNames): return DatabaseRegion(table: tableName, columns: updatedColumnNames) } } - /// Returns true iff this is a delete event. + /// Returns whether this is a delete event. var isDelete: Bool { if case .delete = self { return true @@ -939,7 +998,7 @@ protocol DatabaseEventProtocol { public struct DatabaseEvent { /// An event kind - public enum Kind: Int32 { + public enum Kind: CInt { /// SQLITE_INSERT case insert = 18 @@ -950,7 +1009,7 @@ public struct DatabaseEvent { case update = 23 } - private let impl: DatabaseEventImpl + private let impl: any DatabaseEventImpl /// The event kind public let kind: Kind @@ -976,7 +1035,7 @@ public struct DatabaseEvent { impl.copy(self) } - fileprivate init(kind: Kind, rowID: Int64, impl: DatabaseEventImpl) { + fileprivate init(kind: Kind, rowID: Int64, impl: any DatabaseEventImpl) { self.kind = kind self.rowID = rowID self.impl = impl @@ -1046,7 +1105,7 @@ private struct CopiedDatabaseEventImpl: DatabaseEventImpl { public struct DatabasePreUpdateEvent { /// An event kind - public enum Kind: Int32 { + public enum Kind: CInt { /// SQLITE_INSERT case insert = 18 @@ -1142,7 +1201,7 @@ public struct DatabasePreUpdateEvent { impl.copy(self) } - fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) { + fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: any DatabasePreUpdateEventImpl) { self.kind = kind self.initialRowID = (kind == .update || kind == .delete ) ? initialRowID : nil self.finalRowID = (kind == .update || kind == .insert ) ? finalRowID : nil @@ -1168,7 +1227,7 @@ public struct DatabasePreUpdateEvent { tableNameCString: tableNameCString)) } - private let impl: DatabasePreUpdateEventImpl + private let impl: any DatabasePreUpdateEventImpl } extension DatabasePreUpdateEvent: DatabaseEventProtocol { @@ -1234,7 +1293,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { return getValue( connection, column: CInt(index), - sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) in sqlite3_preupdate_old(connection, column, &value) }) } @@ -1244,7 +1303,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { return getValue( connection, column: CInt(index), - sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) in sqlite3_preupdate_new(connection, column, &value) }) } @@ -1298,7 +1357,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? { preupdate_getValues( connection, - sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) in sqlite3_preupdate_old(connection, column, &value) }) } @@ -1306,7 +1365,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? { preupdate_getValues( connection, - sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) in sqlite3_preupdate_new(connection, column, &value) }) } @@ -1329,28 +1388,47 @@ private struct CopiedDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { #endif -// A predicate that filters database events +/// A predicate that filters database events reported by `sqlite3_update_hook`. enum DatabaseEventPredicate { - // Yes filter - case `true` - // Only events that match observedKinds - case matching(observedKinds: [DatabaseEventKind], advertisedKinds: [DatabaseEventKind]) + /// All events. + case all - func evaluate(_ event: DatabaseEventProtocol) -> Bool { + /// Filters events that match `observedEventKinds`, or are not + /// + /// - parameter observedEventKinds: Event kinds observed by + /// the TransactionObserver. + /// - parameter authorizerEventKinds: Event kinds reported by the + /// statement authorizer. + case matching(observedEventKinds: [DatabaseEventKind], authorizerEventKinds: [DatabaseEventKind]) + + func evaluate(_ event: some DatabaseEventProtocol) -> Bool { switch self { - case .true: + case .all: return true - case let .matching(observedKinds: observedKinds, advertisedKinds: advertisedKinds): - if observedKinds.contains(where: { event.matchesKind($0) }) { + + case let .matching(observedEventKinds: observedEventKinds, authorizerEventKinds: authorizerEventKinds): + if observedEventKinds.contains(where: { event.matchesKind($0) }) { return true } - if !advertisedKinds.contains(where: { event.matchesKind($0) }) { - // FTS4 (and maybe other virtual tables) perform unadvertised - // changes. For example, an "INSERT INTO document ..." statement - // advertises an insertion in the `document` table, but the - // actual change events happen in the `document_content` shadow - // table. When such a non-advertised event happens, assume that - // the event has to be notified. + if !authorizerEventKinds.contains(where: { event.matchesKind($0) }) { + // Here, `sqlite3_update_hook` emits an unexpected event, that + // was not advertised by `sqlite3_set_authorizer` when the + // statement was compiled: + // + // 1. Compile "INSERT INTO document ...": the authorizer + // reports an insertion in the `document` table. + // 2. Execute "INSERT INTO document ...": the update hook + // reports an insertion in another table! + // + // Well, FTS4 (and maybe other virtual tables) perform such + // unadvertised changes. Executing the "INSERT INTO document ..." + // statement reports changes in the `document_content` shadow + // table, not the `document` table reported when the + // statement was compiled. + // + // When such a non-advertised event happens, we notify the + // event to the transaction observer. + // // See https://github.com/groue/GRDB.swift/issues/620 return true } @@ -1372,7 +1450,7 @@ enum DatabaseEventPredicate { /// rollbacked. class SavepointStack { /// The buffered events (see DatabaseObservationBroker.databaseDidChange(with:)) - var eventsBuffer: [(event: DatabaseEventProtocol, statementObservations: [StatementObservation])] = [] + var eventsBuffer: [(event: any DatabaseEventProtocol, statementObservations: [StatementObservation])] = [] /// The savepoint stack, as an array of tuples (savepointName, index in the eventsBuffer array). /// Indexes let us drop rollbacked events from the event buffer. diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index 6b2a2f62d..ce1df691d 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -20,7 +20,7 @@ /// /// See . final class WALSnapshot { -#if GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7) +#if GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) init?(_ db: Database) { return nil } @@ -35,33 +35,17 @@ final class WALSnapshot { /// error occurs. init?(_ db: Database) { var snapshot: UnsafeMutablePointer? - let code: CInt = withUnsafeMutablePointer(to: &snapshot) { -#if GRDBCUSTOMSQLITE + let code = withUnsafeMutablePointer(to: &snapshot) { return sqlite3_snapshot_get(db.sqliteConnection, "main", $0) -#else - // iOS 10.0 is always true because our minimum requirement is iOS 11. - if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { - return sqlite3_snapshot_get(db.sqliteConnection, "main", $0) - } else { - return SQLITE_ERROR - } -#endif } - guard code == SQLITE_OK, let s = snapshot else { + guard code == SQLITE_OK, let snapshot else { return nil } - self.snapshot = s + self.snapshot = snapshot } deinit { -#if GRDBCUSTOMSQLITE sqlite3_snapshot_free(snapshot) -#else - // iOS 10.0 is always true because our minimum requirement is iOS 11. - if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { - sqlite3_snapshot_free(snapshot) - } -#endif } /// Compares two WAL snapshots. @@ -70,16 +54,7 @@ final class WALSnapshot { /// /// See . func compare(_ other: WALSnapshot) -> CInt { -#if GRDBCUSTOMSQLITE return sqlite3_snapshot_cmp(snapshot, other.snapshot) -#else - // iOS 10.0 is always true because our minimum requirement is iOS 11. - if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { - return sqlite3_snapshot_cmp(snapshot, other.snapshot) - } else { - preconditionFailure("snapshots are not available") - } -#endif } -#endif // GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7) +#endif // GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) } diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index 3dd31a534..6c14f0cfe 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -43,32 +43,31 @@ public struct FTS3: VirtualTableModule { /// /// For example: /// - /// FTS3.tokenize("SQLite database") // ["sqlite", "database"] - /// FTS3.tokenize("Gustave Doré") // ["gustave", "doré"]) + /// try FTS3.tokenize("SQLite database") // ["sqlite", "database"] + /// try FTS3.tokenize("Gustave Doré") // ["gustave", "doré"]) /// /// Results can be altered with an explicit tokenizer - default is `.simple`. /// See . /// - /// FTS3.tokenize("SQLite database", withTokenizer: .porter) // ["sqlite", "databas"] - /// FTS3.tokenize("Gustave Doré", withTokenizer: .unicode61()) // ["gustave", "dore"]) + /// try FTS3.tokenize("SQLite database", withTokenizer: .porter) // ["sqlite", "databas"] + /// try FTS3.tokenize("Gustave Doré", withTokenizer: .unicode61()) // ["gustave", "dore"]) /// /// Tokenization is performed by the `fts3tokenize` virtual table described /// at . public static func tokenize( _ string: String, withTokenizer tokenizer: FTS3TokenizerDescriptor = .simple) - -> [String] + throws -> [String] { - DatabaseQueue().inDatabase { db in + try DatabaseQueue().inDatabase { db in var tokenizerChunks: [String] = [] tokenizerChunks.append(tokenizer.name) for option in tokenizer.arguments { tokenizerChunks.append("\"\(option)\"") } let tokenizerSQL = tokenizerChunks.joined(separator: ", ") - // Assume fts3tokenize virtual table in an in-memory database always succeeds - try! db.execute(sql: "CREATE VIRTUAL TABLE tokens USING fts3tokenize(\(tokenizerSQL))") - return try! String.fetchAll(db, sql: """ + try db.execute(sql: "CREATE VIRTUAL TABLE tokens USING fts3tokenize(\(tokenizerSQL))") + return try String.fetchAll(db, sql: """ SELECT token FROM tokens WHERE input = ? ORDER BY position """, arguments: [string]) } @@ -79,14 +78,6 @@ 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:) diff --git a/GRDB/FTS/FTS3Pattern.swift b/GRDB/FTS/FTS3Pattern.swift index 8b4e7e5b0..4cf34e82b 100644 --- a/GRDB/FTS/FTS3Pattern.swift +++ b/GRDB/FTS/FTS3Pattern.swift @@ -41,8 +41,9 @@ public struct FTS3Pattern { /// /// - parameter string: The string to turn into an FTS3 pattern public init?(matchingAnyTokenIn string: String) { - let tokens = FTS3.tokenize(string, withTokenizer: .simple) - guard !tokens.isEmpty else { return nil } + guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple), + !tokens.isEmpty + else { return nil } try? self.init(rawPattern: tokens.joined(separator: " OR ")) } @@ -54,8 +55,9 @@ public struct FTS3Pattern { /// /// - parameter string: The string to turn into an FTS3 pattern public init?(matchingAllTokensIn string: String) { - let tokens = FTS3.tokenize(string, withTokenizer: .simple) - guard !tokens.isEmpty else { return nil } + guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple), + !tokens.isEmpty + else { return nil } try? self.init(rawPattern: tokens.joined(separator: " ")) } @@ -67,8 +69,9 @@ public struct FTS3Pattern { /// /// - parameter string: The string to turn into an FTS3 pattern public init?(matchingAllPrefixesIn string: String) { - let tokens = FTS3.tokenize(string, withTokenizer: .simple) - guard !tokens.isEmpty else { return nil } + guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple), + !tokens.isEmpty + else { return nil } try? self.init(rawPattern: tokens.map { "\($0)*" }.joined(separator: " ")) } @@ -80,8 +83,9 @@ public struct FTS3Pattern { /// /// - parameter string: The string to turn into an FTS3 pattern public init?(matchingPhrase string: String) { - let tokens = FTS3.tokenize(string, withTokenizer: .simple) - guard !tokens.isEmpty else { return nil } + guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple), + !tokens.isEmpty + else { return nil } try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"") } } diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index 6166bfad5..e08080082 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -25,14 +25,6 @@ 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 { - preconditionFailure() - } - /// Reserved; part of the VirtualTableModule protocol. /// /// See Database.create(virtualTable:using:) @@ -296,7 +288,7 @@ public final class FTS4ColumnDefinition { return self } - /// Uses the column as the Int32 language id hidden column. + /// Uses the column as the language id hidden column. /// /// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("a") diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 3669a52d4..ec53146b0 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -76,14 +76,6 @@ public struct FTS5: VirtualTableModule { /// The virtual table module name public let moduleName = "fts5" - // TODO: remove when `makeTableDefinition()` is no longer a requirement - /// Reserved; part of the VirtualTableModule protocol. - /// - /// See Database.create(virtualTable:using:) - public func makeTableDefinition() -> FTS5TableDefinition { - preconditionFailure() - } - /// Reserved; part of the VirtualTableModule protocol. /// /// See Database.create(virtualTable:using:) @@ -249,9 +241,9 @@ public struct FTS5: VirtualTableModule { private static func api_v2( _ db: Database, // swiftlint:disable:next line_length - _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer?, Int32, UInt32, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> Int32, + _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer?, CInt, CUnsignedInt, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> CInt, // swiftlint:disable:next line_length - _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, Int32, UnsafeMutableRawPointer?, UnsafePointer?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> Int32) + _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt) -> UnsafePointer { var statement: SQLiteStatement? = nil @@ -267,10 +259,10 @@ public struct FTS5: VirtualTableModule { _ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil) } sqlite3_step(statement) - guard let result = api else { + guard let api else { fatalError("FTS5 is not available") } - return result + return api } } diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index 6caf8814b..313d2e850 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -42,11 +42,11 @@ extension Database { private class FTS5TokenizerConstructor { let db: Database - let constructor: (Database, [String], UnsafeMutablePointer?) -> Int32 + let constructor: (Database, [String], UnsafeMutablePointer?) -> CInt init( db: Database, - constructor: @escaping (Database, [String], UnsafeMutablePointer?) -> Int32) + constructor: @escaping (Database, [String], UnsafeMutablePointer?) -> CInt) { self.db = db self.constructor = constructor @@ -68,7 +68,7 @@ extension Database { let constructor = FTS5TokenizerConstructor( db: self, constructor: { (db, arguments, tokenizerHandle) in - guard let tokenizerHandle = tokenizerHandle else { + guard let tokenizerHandle else { return SQLITE_ERROR } do { @@ -92,18 +92,18 @@ extension Database { let constructorPointer = Unmanaged.passRetained(constructor).toOpaque() func deleteConstructor(constructorPointer: UnsafeMutableRawPointer?) { - guard let constructorPointer = constructorPointer else { return } + guard let constructorPointer else { return } Unmanaged.fromOpaque(constructorPointer).release() } func xCreateTokenizer( constructorPointer: UnsafeMutableRawPointer?, azArg: UnsafeMutablePointer?>?, - nArg: Int32, + nArg: CInt, tokenizerHandle: UnsafeMutablePointer?) - -> Int32 + -> CInt { - guard let constructorPointer = constructorPointer else { + guard let constructorPointer else { return SQLITE_ERROR } let constructor = Unmanaged.fromOpaque(constructorPointer).takeUnretainedValue() @@ -119,27 +119,27 @@ extension Database { } func xDeleteTokenizer(tokenizerPointer: OpaquePointer?) { - guard let tokenizerPointer = tokenizerPointer else { return } + guard let tokenizerPointer else { return } Unmanaged.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).release() } func xTokenize( tokenizerPointer: OpaquePointer?, context: UnsafeMutableRawPointer?, - flags: Int32, + flags: CInt, pText: UnsafePointer?, - nText: Int32, + nText: CInt, // swiftlint:disable:next line_length - tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer?, Int32, Int32, Int32) -> Int32)?) - -> Int32 + tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, CInt, UnsafePointer?, CInt, CInt, CInt) -> CInt)?) + -> CInt { - guard let tokenizerPointer = tokenizerPointer else { + guard let tokenizerPointer else { return SQLITE_ERROR } let object = Unmanaged .fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)) .takeUnretainedValue() - guard let tokenizer = object as? FTS5Tokenizer else { + guard let tokenizer = object as? any FTS5Tokenizer else { return SQLITE_ERROR } return tokenizer.tokenize( diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index 551270802..74d34b6c9 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -6,20 +6,20 @@ import Foundation /// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:) public typealias FTS5TokenCallback = @convention(c) ( _ context: UnsafeMutableRawPointer?, - _ flags: Int32, + _ flags: CInt, _ pToken: UnsafePointer?, - _ nToken: Int32, - _ iStart: Int32, - _ iEnd: Int32) - -> Int32 + _ nToken: CInt, + _ iStart: CInt, + _ iEnd: CInt) + -> CInt /// The reason why FTS5 is requesting tokenization. /// /// See public struct FTS5Tokenization: OptionSet { - public let rawValue: Int32 + public let rawValue: CInt - public init(rawValue: Int32) { + public init(rawValue: CInt) { self.rawValue = rawValue } @@ -56,9 +56,9 @@ public protocol FTS5Tokenizer: AnyObject { context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, - nText: Int32, + nText: CInt, tokenCallback: @escaping FTS5TokenCallback) - -> Int32 + -> CInt } private class TokenizeContext { @@ -118,7 +118,7 @@ extension FTS5Tokenizer { return [] } let pText = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self) - let nText = Int32(buffer.count) + let nText = CInt(buffer.count) var context = TokenizeContext() try withUnsafeMutablePointer(to: &context) { contextPointer in @@ -127,8 +127,8 @@ extension FTS5Tokenizer { tokenization: tokenization, pText: pText, nText: nText, - tokenCallback: { (contextPointer, flags, pToken, nToken, _ /* iStart */, _ /* iEnd */) -> Int32 in - guard let contextPointer = contextPointer else { + tokenCallback: { (contextPointer, flags, pToken, nToken, _ /* iStart */, _ /* iEnd */) in + guard let contextPointer else { return SQLITE_ERROR } @@ -174,7 +174,7 @@ extension Database { self.xTokenizer = xTokenizer var tokenizerPointer: OpaquePointer? = nil - let code: Int32 + let code: CInt if arguments.isEmpty { code = xCreate(contextPointer, nil, 0, &tokenizerPointer) } else { @@ -200,7 +200,7 @@ extension Database { xCreate( contextPointer, UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)), - Int32(cStrings.count), + CInt(cStrings.count), &tokenizerPointer) } } @@ -227,9 +227,9 @@ extension Database { context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, - nText: Int32, + nText: CInt, tokenCallback: @escaping FTS5TokenCallback) - -> Int32 + -> CInt { guard let xTokenize = xTokenizer.xTokenize else { return SQLITE_ERROR @@ -254,7 +254,7 @@ extension Database { /// wrappedTokenizer = try db.makeTokenizer(.unicode61()) /// } /// } - public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> FTS5Tokenizer { + public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> any FTS5Tokenizer { let api = FTS5.api(self) let xTokenizerPointer: UnsafeMutablePointer = .allocate(capacity: 1) diff --git a/GRDB/FTS/FTS5TokenizerDescriptor.swift b/GRDB/FTS/FTS5TokenizerDescriptor.swift index 996c9fdfa..c6eb995ca 100644 --- a/GRDB/FTS/FTS5TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS5TokenizerDescriptor.swift @@ -65,9 +65,10 @@ public struct FTS5TokenizerDescriptor { // TODO: test "=" and "\"", "(" and ")" as separators, with // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) // and Database.create(virtualTable:using:) - let separatorComponents = DatabaseQueue().inDatabase { db in - // Assume quoting a string never fails - try! [ + // + // Assume quoting a string in an in-memory database never fails + let separatorComponents = try! DatabaseQueue().inDatabase { db in + try [ "separators", separators .map { String($0) } @@ -81,9 +82,10 @@ public struct FTS5TokenizerDescriptor { // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) // and Database.create(virtualTable:using:) - let tokenCharactersComponents = DatabaseQueue().inDatabase { db in - // Assume quoting a string never fails - try! [ + // + // Assume quoting a string in an in-memory database never fails + let tokenCharactersComponents = try! DatabaseQueue().inDatabase { db in + try [ "tokenchars", tokenCharacters .sorted() @@ -156,9 +158,10 @@ public struct FTS5TokenizerDescriptor { // TODO: test "=" and "\"", "(" and ")" as separators, with // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) // and Database.create(virtualTable:using:) - let separatorComponents = DatabaseQueue().inDatabase { db in - // Assume quoting a string never fails - try! [ + // + // Assume quoting a string in an in-memory database never fails + let separatorComponents = try! DatabaseQueue().inDatabase { db in + try [ "separators", separators .sorted() @@ -174,9 +177,10 @@ public struct FTS5TokenizerDescriptor { // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) // and Database.create(virtualTable:using:) - let tokenCharactersComponents = DatabaseQueue().inDatabase { db in - // Assume quoting a string never fails - try! [ + // + // Assume quoting a string in an in-memory database never fails + let tokenCharactersComponents = try! DatabaseQueue().inDatabase { db in + try [ "tokenchars", tokenCharacters .sorted() diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index dfee9e0bd..4f804dc5e 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -5,9 +5,9 @@ import Foundation /// /// See the `FTS5_TOKEN_*` flags in . public struct FTS5TokenFlags: OptionSet { - public let rawValue: Int32 + public let rawValue: CInt - public init(rawValue: Int32) { + public init(rawValue: CInt) { self.rawValue = rawValue } @@ -50,7 +50,7 @@ public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5Token /// } public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer { /// The wrapped tokenizer - var wrappedTokenizer: FTS5Tokenizer { get } + var wrappedTokenizer: any FTS5Tokenizer { get } /// Given a token produced by the wrapped tokenizer, notifies customized /// tokens to the `tokenCallback` function. @@ -92,7 +92,7 @@ public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer { } private struct FTS5WrapperContext { - let tokenizer: FTS5WrapperTokenizer + let tokenizer: any FTS5WrapperTokenizer let context: UnsafeMutableRawPointer? let tokenization: FTS5Tokenization let tokenCallback: FTS5TokenCallback @@ -104,9 +104,9 @@ extension FTS5WrapperTokenizer { context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, - nText: Int32, + nText: CInt, tokenCallback: @escaping FTS5TokenCallback) - -> Int32 + -> CInt { // `tokenCallback` is @convention(c). This requires a little setup // in order to transfer context. @@ -155,7 +155,7 @@ extension FTS5WrapperTokenizer { } let pToken = UnsafeMutableRawPointer(mutating: addr) .assumingMemoryBound(to: Int8.self) - let nToken = Int32(buffer.count) + let nToken = CInt(buffer.count) // Inject token bytes into SQLite let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd) diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift deleted file mode 100644 index e8f8f36ce..000000000 --- a/GRDB/Fixit/GRDB-5.0.swift +++ /dev/null @@ -1,542 +0,0 @@ -// Fixits for changes introduced by GRDB 5.0.0 -// swiftlint:disable all - -import Dispatch -#if os(iOS) -import UIKit -#endif - -extension AnyFetchRequest { - @available(*, unavailable, renamed: "RowDecoder") - typealias T = RowDecoder - - @available(*, unavailable, message: "Use AnyFetchRequest(request).asRequest(of: SomeType.self) instead.") - public init(_ request: Request) - { preconditionFailure() } - - @available(*, unavailable, message: "Define your own FetchRequest type instead.") - public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (Statement, RowAdapter?)) - { preconditionFailure() } -} - -@available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") -public struct AnyValueReducer: ValueReducer { - public init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?) - { preconditionFailure() } - - public init(_ reducer: Base) where Base.Fetched == Fetched, Base.Value == Value - { preconditionFailure() } - - public func _fetch(_ db: Database) throws -> Fetched - { preconditionFailure() } - - public func _value(_ fetched: Fetched) -> Value? - { preconditionFailure() } -} - -extension AssociationAggregate { - @available(*, unavailable, renamed: "forKey(_:)") - public func aliased(_ name: String) -> AssociationAggregate - { preconditionFailure() } - - @available(*, unavailable, renamed: "forKey(_:)") - public func aliased(_ key: CodingKey) -> AssociationAggregate - { preconditionFailure() } -} - -extension Configuration { - @available(*, unavailable, message: "Replace the assignment with a method call: prepareDatabase { db in ... }") - public var prepareDatabase: ((Database) throws -> Void)? { - get { preconditionFailure() } - set { preconditionFailure() } - } - - @available(*, unavailable, message: "Use Database.trace(options:_:) in Configuration.prepareDatabase instead.") - public var trace: TraceFunction? { - get { preconditionFailure() } - set { preconditionFailure() } - } -} - -extension DatabaseFunction { - @available(*, unavailable, renamed: "callAsFunction(_:)") - public func apply(_ arguments: SQLExpressible...) -> SQLExpression - { preconditionFailure() } -} - -extension DatabaseMigrator { - @available(*, unavailable, renamed: "registerMigration(_:migrate:)") - public mutating func registerMigrationWithDeferredForeignKeyCheck( - _ identifier: String, - migrate: @escaping (Database) throws -> Void) - { preconditionFailure() } - - @available(*, unavailable, message: "Wrap this method: reader.read(migrator.appliedMigrations) }") - public func appliedMigrations(in reader: DatabaseReader) throws -> Set - { preconditionFailure() } - - @available(*, unavailable, message: "Wrap this method: reader.read(migrator.hasCompletedMigrations) }") - public func hasCompletedMigrations(in reader: DatabaseReader) throws -> Bool - { preconditionFailure() } - - @available(*, unavailable, message: "Prefer reader.read(migrator.completedMigrations).contains(targetIdentifier)") - public func hasCompletedMigrations(in reader: DatabaseReader, through targetIdentifier: String) throws -> Bool - { preconditionFailure() } - - @available(*, unavailable, message: "Prefer reader.read(migrator.completedMigrations).last") - public func lastCompletedMigration(in reader: DatabaseReader) throws -> String? - { preconditionFailure() } -} - -extension DatabasePool { - @available(*, unavailable, message: "Use pool.writeWithoutTransaction { $0.checkpoint() } instead") - public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws { preconditionFailure() } - - #if os(iOS) - @available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.") - public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() } - #endif -} - -extension DatabaseQueue { - #if os(iOS) - @available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.") - public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() } - #endif -} - -extension DatabaseReader { - @available(*, unavailable, message: "Use Database.add(collation:) in Configuration.prepareDatabase instead.") - public func add(collation: DatabaseCollation) { preconditionFailure() } - - @available(*, unavailable) - public func remove(collation: DatabaseCollation) { preconditionFailure() } - - @available(*, unavailable, message: "Use Database.add(function:) in Configuration.prepareDatabase instead.") - public func add(function: DatabaseFunction) { preconditionFailure() } - - @available(*, unavailable) - public func remove(function: DatabaseFunction) { preconditionFailure() } - - #if SQLITE_ENABLE_FTS5 - @available(*, unavailable, message: "Use Database.add(tokenizer:) in Configuration.prepareDatabase instead.") - public func add(tokenizer: Tokenizer.Type) { preconditionFailure() } - #endif -} - -extension FetchRequest { - @available(*, unavailable, message: "Use makePreparedRequest(_:forSingleResult:) instead.") - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (Statement, RowAdapter?) - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchCount) instead") - public func observationForCount() -> ValueObservation> - { preconditionFailure() } -} - -extension FetchRequest where RowDecoder: DatabaseValueConvertible { - @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchAll) instead") - public func observationForAll() -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchOne) instead") - public func observationForFirst() -> ValueObservation> - { preconditionFailure() } -} - -extension FetchRequest where RowDecoder: FetchableRecord { - @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchAll) instead") - public func observationForAll() -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchOne) instead") - public func observationForFirst() -> ValueObservation> - { preconditionFailure() } -} - -extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible { - @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchAll) instead") - public func observationForAll() -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchOne) instead") - public func observationForFirst() -> ValueObservation> - { preconditionFailure() } -} - -extension FetchRequest where RowDecoder == Row { - @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchAll) instead") - public func observationForAll() -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchOne) instead") - public func observationForFirst() -> ValueObservation> - { preconditionFailure() } -} - -extension QueryInterfaceRequest { - @available(*, unavailable, renamed: "RowDecoder") - typealias T = RowDecoder -} - -extension SQLExpression { - @available(*, unavailable, message: "Use SQL initializer instead") - public var sqlLiteral: SQL - { preconditionFailure() } -} - -extension FilteredRequest { - @available(*, unavailable, message: "The expectingSingleResult() hint is no longer available.") - func expectingSingleResult() -> Self - { preconditionFailure() } -} - -@available(*, deprecated, renamed: "SQL") -public typealias SQLLiteral = SQL - -/// :nodoc: -@available(*, unavailable, message: "Build literal expressions with SQL.sqlExpression instead.") -struct SQLExpressionLiteral: SQLSpecificExpressible { - var sqlExpression: SQLExpression { preconditionFailure() } - - @available(*, unavailable, message: "Build literal expressions with SQL.sqlExpression instead.") - public var sql: String { preconditionFailure() } - - @available(*, unavailable, message: "Build literal expressions with SQL.sqlExpression instead.") - public var arguments: StatementArguments { preconditionFailure() } - - @available(*, unavailable, message: "Build literal expressions with SQL.sqlExpression instead.") - public init(sql: String, arguments: StatementArguments = StatementArguments()) - { preconditionFailure() } - - @available(*, unavailable, message: "Build literal expressions with SQL.sqlExpression instead.") - public init(literal sqlLiteral: SQL) - { preconditionFailure() } -} - -@available(*, deprecated, renamed: "SQL") -public typealias SQLiteral = SQL - -extension SQL { - @available(*, unavailable, message: "Use SQL interpolation instead.") - public func mapSQL(_ transform: @escaping (String) -> String) -> SQL - { preconditionFailure() } - - @available(*, unavailable, message: "Use the build(_:) method instead.") - public var sql: String { preconditionFailure() } - - @available(*, unavailable, message: "Use the build(_:) method instead.") - public var arguments: StatementArguments { preconditionFailure() } -} - -@available(*, unavailable, renamed: "SQLExpression.AssociativeBinaryOperator") -typealias SQLLogicalBinaryOperator = SQLExpression.AssociativeBinaryOperator - -@available(*, deprecated, renamed: "SQLExpression") -typealias SQLCollatedExpression = SQLExpression - -extension SQLRequest { - @available(*, unavailable, renamed: "RowDecoder") - typealias T = RowDecoder - - @available(*, unavailable, message: "Turning a request into SQLRequest is no longer supported.") - public init( - _ db: Database, - request: Request, - cached: Bool = false) - throws - where Request: FetchRequest, Request.RowDecoder == RowDecoder - { preconditionFailure() } - - @available(*, unavailable, message: "Use makePreparedRequest(db).statement.sql instead") - public var sql: String { preconditionFailure() } - - @available(*, unavailable, message: "Use makePreparedRequest(db).statement.arguments instead") - public var arguments: StatementArguments { preconditionFailure() } -} - -extension SQLSpecificExpressible { - @available(*, unavailable, renamed: "forKey(_:)") - public func aliased(_ name: String) -> SQLSelectable - { preconditionFailure() } - - @available(*, unavailable, renamed: "forKey(_:)") - public func aliased(_ key: CodingKey) -> SQLSelectable - { preconditionFailure() } -} - -extension Statement { - @available(*, unavailable, renamed: "setUncheckedArguments(_:)") - public func unsafeSetArguments(_ arguments: StatementArguments) - { preconditionFailure() } - - @available(*, unavailable, renamed: "validateArguments(_:)") - public func validate(arguments: StatementArguments) throws - { preconditionFailure() } -} - -extension TableRecord { - @available(*, unavailable, message: "Use ValueObservation.tracking(MyRecord.fetchCount) instead") - public static func observationForCount() -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "Use SQL interpolation instead") - public static func selectionSQL(alias: String? = nil) -> String - { preconditionFailure() } -} - -extension TableRecord where Self: FetchableRecord { - @available(*, unavailable, message: "Use ValueObservation.tracking(MyRecord.fetchAll) instead") - public static func observationForAll() -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(MyRecord.fetchOne) instead") - public static func observationForFirst() -> ValueObservation> - { preconditionFailure() } -} - -@available(*, unavailable) -public typealias TraceFunction = (String) -> Void - -extension ValueObservation { - @available(*, unavailable, message: "ValueObservation now schedules its values asynchronously on the main queue by default. See ValueObservation.start() for possible configuration") - var scheduling: ValueScheduling { - get { preconditionFailure() } - set { preconditionFailure() } - } - - @available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: @escaping (Database) throws -> Reducer) -> ValueObservation - { preconditionFailure() } - - @available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public static func tracking(_ regions: [DatabaseRegionConvertible], reducer: @escaping (Database) throws -> Reducer) -> ValueObservation - { preconditionFailure() } - - @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public func combine( - _ other: ValueObservation, - _ transform: @escaping (Reducer.Value, R1.Value) -> Combined) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public func combine( - _ observation1: ValueObservation, - _ observation2: ValueObservation, - _ transform: @escaping (Reducer.Value, R1.Value, R2.Value) -> Combined) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public func combine( - _ observation1: ValueObservation, - _ observation2: ValueObservation, - _ observation3: ValueObservation, - _ transform: @escaping (Reducer.Value, R1.Value, R2.Value, R3.Value) -> Combined) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public func combine( - _ observation1: ValueObservation, - _ observation2: ValueObservation, - _ observation3: ValueObservation, - _ observation4: ValueObservation, - _ transform: @escaping (Reducer.Value, R1.Value, R2.Value, R3.Value, R4.Value) -> Combined) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "compactMap is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public func compactMap(_ transform: @escaping (Reducer.Value) -> T?) -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "Use start(in:onError:onChange:) instead.") - public func start( - in reader: DatabaseReader, - onChange: @escaping (Reducer.Value) -> Void) throws -> TransactionObserver - { preconditionFailure() } -} - -extension ValueObservation where Reducer == ValueReducers.Auto { - @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public static func combine( - _ o1: ValueObservation, - _ o2: ValueObservation) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public static func combine( - _ o1: ValueObservation, - _ o2: ValueObservation, - _ o3: ValueObservation) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public static func combine( - _ o1: ValueObservation, - _ o2: ValueObservation, - _ o3: ValueObservation, - _ o4: ValueObservation) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public static func combine( - _ o1: ValueObservation, - _ o2: ValueObservation, - _ o3: ValueObservation, - _ o4: ValueObservation, - _ o5: ValueObservation) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public static func combine( - _ o1: ValueObservation, - _ o2: ValueObservation, - _ o3: ValueObservation, - _ o4: ValueObservation, - _ o5: ValueObservation, - _ o6: ValueObservation) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public static func combine( - _ o1: ValueObservation, - _ o2: ValueObservation, - _ o3: ValueObservation, - _ o4: ValueObservation, - _ o5: ValueObservation, - _ o6: ValueObservation, - _ o7: ValueObservation) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") - public static func combine( - _ o1: ValueObservation, - _ o2: ValueObservation, - _ o3: ValueObservation, - _ o4: ValueObservation, - _ o5: ValueObservation, - _ o6: ValueObservation, - _ o7: ValueObservation, - _ o8: ValueObservation) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") - public static func trackingCount(_ request: Request) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: DatabaseValueConvertible - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") - public static func trackingOne(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: DatabaseValueConvertible - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: _OptionalProtocol, - Request.RowDecoder.Wrapped: DatabaseValueConvertible - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: FetchableRecord - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") - public static func trackingOne(_ request: Request) -> - ValueObservation> - where Request.RowDecoder: FetchableRecord - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder == Row - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") - public static func trackingOne(_ request: Request) - -> ValueObservation> - where Request.RowDecoder == Row - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") - public static func tracking( - _ regions: DatabaseRegionConvertible..., - fetch: @escaping (Database) throws -> Value) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") - public static func tracking( - _ regions: [DatabaseRegionConvertible], - fetch: @escaping (Database) throws -> Value) - -> ValueObservation> - { preconditionFailure() } - - @available(*, unavailable, renamed: "tracking(_:)") - public static func tracking( - value: @escaping (Database) throws -> Value) - -> ValueObservation> - { preconditionFailure() } -} - -extension ValueObservation where Reducer.Value: Equatable { - @available(*, unavailable, renamed: "removeDuplicates") - public func distinctUntilChanged() -> ValueObservation> - { preconditionFailure() } -} - -extension ValueReducers { - @available(*, unavailable) - public enum Unavailable: ValueReducer { - public func _fetch(_ db: Database) throws -> Never - { preconditionFailure() } - - public mutating func _value(_ fetched: Never) -> T? { } - } -} - -@available(*, unavailable, message: "ValueObservation now schedules its values asynchronously on the main queue by default. See ValueObservation.start() for possible configuration") -enum ValueScheduling { - case mainQueue - case async(onQueue: DispatchQueue, startImmediately: Bool) - case unsafe(startImmediately: Bool) -} - -#if SQLITE_HAS_CODEC -extension Configuration { - @available(*, unavailable, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.") - public var passphrase: String? { - get { preconditionFailure() } - set { preconditionFailure() } - } -} - -extension DatabasePool { - @available(*, unavailable, message: "Use Database.changePassphrase(_:) instead") - public func change(passphrase: String) throws { preconditionFailure() } -} - -extension DatabaseQueue { - @available(*, unavailable, message: "Use Database.changePassphrase(_:) instead") - public func change(passphrase: String) throws { preconditionFailure() } -} -#endif diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift new file mode 100644 index 000000000..1de2ffb34 --- /dev/null +++ b/GRDB/Fixits.swift @@ -0,0 +1,142 @@ +// Fixits for changes introduced by GRDB 6.0.0 +// swiftlint:disable all + +extension Association { + @available(*, unavailable, message: "limit(_:offset:) was not working properly, and was removed.") + public func limit(_ limit: Int, offset: Int? = nil) -> Self { preconditionFailure() } +} + +extension Database { + @available(*, unavailable, renamed: "cachedStatement(sql:)") + public func cachedSelectStatement(sql: String) throws -> Statement { preconditionFailure() } + + @available(*, unavailable, renamed: "cachedStatement(literal:)") + public func cachedSelectStatement(literal sqlLiteral: SQL) throws -> Statement { preconditionFailure() } + + @available(*, unavailable, renamed: "cachedStatement(sql:)") + public func cachedUpdateStatement(sql: String) throws -> Statement { preconditionFailure() } + + @available(*, unavailable, renamed: "cachedStatement(sql:)") + public func cachedUpdateStatement(literal sqlLiteral: SQL) throws -> Statement { preconditionFailure() } + + @available(*, unavailable, message: "Use Database.isSQLiteInternalTable(_:) static method instead.") + public func isSQLiteInternalTable(_ tableName: String) -> Bool { preconditionFailure() } + + @available(*, unavailable, message: "Use Database.isGRDBInternalTable(_:) static method instead.") + public func isGRDBInternalTable(_ tableName: String) -> Bool { preconditionFailure() } + + @available(*, unavailable, renamed: "makeStatement(sql:)") + public func makeSelectStatement(sql: String) throws -> Statement { preconditionFailure() } + + @available(*, unavailable, renamed: "makeStatement(literal:)") + public func makeSelectStatement(literal sqlLiteral: SQL) throws -> Statement { preconditionFailure() } + + @available(*, unavailable, renamed: "makeStatement(sql:)") + public func makeUpdateStatement(sql: String) throws -> Statement { preconditionFailure() } + + @available(*, unavailable, renamed: "makeStatement(literal:)") + public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> Statement { preconditionFailure() } + + @available(*, unavailable, renamed: "afterNextTransaction(onCommit:)") + public func afterNextTransactionCommit(_ closure: @escaping (Database) -> Void) { preconditionFailure() } +} + +extension DatabaseCursor { + @available(*, unavailable, message: "statement has been removed. You may use other cursor properties instead.") + public var statement: Statement { preconditionFailure() } +} + +extension DatabaseMigrator { + @available(*, unavailable, message: "The completion function now accepts one Result argument") + public func asyncMigrate( + _ writer: DatabaseWriter, + completion: @escaping (Database, Error?) -> Void) + { preconditionFailure() } +} + +extension DatabaseRegionObservation { + @available(*, unavailable, message: "The extent of the observation is now controlled by the cancellable returned by DatabaseRegionObservation.start().") + public var extent: Database.TransactionObservationExtent { + get { preconditionFailure() } + set { preconditionFailure() } + } +} + +extension DatabaseUUIDEncodingStrategy { + @available(*, unavailable, renamed: "uppercaseString") + public static var string: Self { preconditionFailure() } +} + +@available(*, unavailable, message: "FastNullableDatabaseValueCursor has been replaced with FastDatabaseValueCursor") +typealias FastNullableDatabaseValueCursor = FastDatabaseValueCursor + +extension MutablePersistableRecord { + @available(*, unavailable, message: "Use persistence callbacks instead.") + public mutating func performInsert(_ db: Database) throws { preconditionFailure() } + + @available(*, unavailable, message: "Use persistence callbacks instead.") + public func performUpdate(_ db: Database, columns: Set) throws { preconditionFailure() } + + @available(*, unavailable, message: "Use persistence callbacks instead.") + public mutating func performSave(_ db: Database) throws { preconditionFailure() } + + @available(*, unavailable, message: "Use persistence callbacks instead.") + public func performDelete(_ db: Database) throws -> Bool { preconditionFailure() } + + @available(*, unavailable, message: "performExists(_:) was removed without any replacement.") + public func performExists(_ db: Database) throws -> Bool { preconditionFailure() } + + @available(*, unavailable, renamed: "updateChanges(_:modify:)") + public mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool { preconditionFailure() } +} + +@available(*, unavailable, message: "NullableDatabaseValueCursor has been replaced with DatabaseValueCursor") +typealias NullableDatabaseValueCursor = DatabaseValueCursor + +extension PersistableRecord { + @available(*, unavailable, message: "Use persistence callbacks instead.") + public func performInsert(_ db: Database) throws { preconditionFailure() } + + @available(*, unavailable, message: "Use persistence callbacks instead.") + public func performSave(_ db: Database) throws { preconditionFailure() } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension QueryInterfaceRequest where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { + @available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.") + public func selectID() -> QueryInterfaceRequest { preconditionFailure() } +} + +extension Record { + @available(*, unavailable, message: "Record.copy() was removed without any replacement.") + final func copy() -> Self { preconditionFailure() } +} + +@available(*, unavailable, renamed: "Statement") +public typealias SelectStatement = Statement + +@available(*, unavailable, renamed: "SQLExpression.AssociativeBinaryOperator") +public typealias SQLAssociativeBinaryOperator = SQLExpression.AssociativeBinaryOperator + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { + @available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.") + public func selectID() -> QueryInterfaceRequest { preconditionFailure() } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { + @available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.") + public static func selectID() -> QueryInterfaceRequest { preconditionFailure() } +} + +@available(*, unavailable, renamed: "Statement") +public typealias UpdateStatement = Statement + +extension ValueObservation { + @available(*, unavailable, renamed: "tracking(_:)") + public static func trackingVaryingRegion( + _ fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + { preconditionFailure() } +} diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 13ae52339..c2f1472e5 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -197,7 +197,7 @@ public struct DatabaseMigrator { /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) /// where migrations should apply. /// - throws: An eventual error thrown by the registered migration blocks. - public func migrate(_ writer: DatabaseWriter) throws { + public func migrate(_ writer: some DatabaseWriter) throws { guard let lastMigration = _migrations.last else { return } @@ -212,7 +212,7 @@ public struct DatabaseMigrator { /// where migrations should apply. /// - parameter targetIdentifier: The identifier of a registered migration. /// - throws: An eventual error thrown by the registered migration blocks. - public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws { + public func migrate(_ writer: some DatabaseWriter, upTo targetIdentifier: String) throws { try writer.barrierWriteWithoutTransaction { db in try migrate(db, upTo: targetIdentifier) } @@ -224,21 +224,22 @@ public struct DatabaseMigrator { /// /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) /// where migrations should apply. - /// - parameter completion: A closure that is called in a protected dispatch - /// queue that can write in the database, with the eventual - /// migration error. + /// - parameter completion: A function that can access the database. Its + /// argument is a `Result` that provides a connection to the migrated + /// database, or the failure that would prevent the migration to complete. public func asyncMigrate( - _ writer: DatabaseWriter, - completion: @escaping (Database, Error?) -> Void) + _ writer: some DatabaseWriter, + completion: @escaping (Result) -> Void) { - writer.asyncBarrierWriteWithoutTransaction { db in + writer.asyncBarrierWriteWithoutTransaction { dbResult in do { + let db = try dbResult.get() if let lastMigration = self._migrations.last { try self.migrate(db, upTo: lastMigration.identifier) } - completion(db, nil) + completion(.success(db)) } catch { - completion(db, error) + completion(.failure(error)) } } } @@ -388,7 +389,7 @@ public struct DatabaseMigrator { // Let's migrate a temporary database up to the same // level, and compare the database schemas. If they // differ, we'll erase the database. - let tmpSchema: SchemaInfo = try { + let tmpSchema = try { // Make sure the temporary database is configured // just as the migrated database var tmpConfig = db.configuration @@ -455,7 +456,7 @@ extension DatabaseMigrator { /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) /// where migrations should apply. @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func migratePublisher(_ writer: DatabaseWriter) -> DatabasePublishers.Migrate { + public func migratePublisher(_ writer: some DatabaseWriter) -> DatabasePublishers.Migrate { migratePublisher(writer, receiveOn: DispatchQueue.main) } @@ -471,23 +472,16 @@ extension DatabaseMigrator { /// where migrations should apply. /// - parameter scheduler: A Combine Scheduler. @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func migratePublisher(_ writer: DatabaseWriter, receiveOn scheduler: S) + public func migratePublisher(_ writer: some DatabaseWriter, receiveOn scheduler: some Scheduler) -> DatabasePublishers.Migrate - where S: Scheduler { DatabasePublishers.Migrate( upstream: OnDemandFuture { promise in - self.asyncMigrate(writer) { _, error in - if let error = error { - promise(.failure(error)) - } else { - promise(.success(())) - } + self.asyncMigrate(writer) { dbResult in + promise(dbResult.map { _ in }) } } - .eraseToAnyPublisher() .receiveValues(on: scheduler) - .eraseToAnyPublisher() ) } } @@ -502,7 +496,7 @@ extension DatabasePublishers { public typealias Output = Void public typealias Failure = Error - fileprivate let upstream: AnyPublisher + fileprivate let upstream: any Publisher public func receive(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input { upstream.receive(subscriber: subscriber) diff --git a/GRDB/QueryInterface/FTS3+QueryInterface.swift b/GRDB/QueryInterface/FTS3+QueryInterface.swift index 948ec113e..fcc2b520d 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterface.swift @@ -12,7 +12,7 @@ extension TableRequest where Self: FilteredRequest { /// If the search pattern is nil, the request does not match any /// database row. public func matching(_ pattern: FTS3Pattern?) -> Self { - guard let pattern = pattern else { + guard let pattern else { return none() } let alias = TableAlias() diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index dcf0272ee..242085fdd 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -17,7 +17,7 @@ extension TableRequest where Self: FilteredRequest { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public func matching(_ pattern: FTS5Pattern?) -> Self { - guard let pattern = pattern else { + guard let pattern else { return none() } let alias = TableAlias() diff --git a/GRDB/QueryInterface/ForeignKey.swift b/GRDB/QueryInterface/ForeignKey.swift index a27a55d36..9a4e407a7 100644 --- a/GRDB/QueryInterface/ForeignKey.swift +++ b/GRDB/QueryInterface/ForeignKey.swift @@ -102,7 +102,7 @@ public struct ForeignKey: Equatable { /// - parameter destinationColumns: The columns at the destination of the /// foreign key. When nil (the default), GRDB automatically uses the /// primary key. - public init(_ originColumns: [ColumnExpression], to destinationColumns: [ColumnExpression]? = nil) { + public init(_ originColumns: [any ColumnExpression], to destinationColumns: [any ColumnExpression]? = nil) { self.init(originColumns.map(\.name), to: destinationColumns?.map(\.name)) } } diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 7ec25bfa7..f89a9e13d 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -145,7 +145,7 @@ extension Association { /// /// let playerInfos = PlayerInfo.all().fetchAll(db) /// print(playerInfos.first?.team) - public func forKey(_ codingKey: CodingKey) -> Self { + public func forKey(_ codingKey: some CodingKey) -> Self { forKey(codingKey.stringValue) } @@ -208,7 +208,7 @@ extension Association { /// .select { db in [Column("id")] } /// .select { db in [Column("color") } /// var request = Player.including(required: association) - public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { + public func select(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self { withDestinationRelation { relation in relation = relation.select { db in try selection(db).map(\.sqlSelection) @@ -229,7 +229,7 @@ extension Association { /// .select([Column("color")]) /// .annotated(with: { db in [Column("name")] }) /// var request = Player.including(required: association) - public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { + public func annotated(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self { withDestinationRelation { relation in relation = relation.annotated { db in try selection(db).map(\.sqlSelection) @@ -252,7 +252,7 @@ extension Association { /// // JOIN team ON team.id = player.teamId AND 1 /// let association = Player.team.filter { db in true } /// var request = Player.including(required: association) - public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { + public func filter(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self { withDestinationRelation { relation in relation = relation.filter { db in try predicate(db).sqlExpression @@ -287,7 +287,7 @@ extension Association { /// .reversed() /// .order{ _ in [Column("name")] } /// var request = Player.including(required: association) - public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self { + public func order(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self { withDestinationRelation { relation in relation = relation.order { db in try orderings(db).map(\.sqlOrdering) @@ -349,7 +349,7 @@ extension Association { // AggregatingRequest conformance extension Association { /// Creates an association grouped according to *expressions promise*. - public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self { + public func group(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self { withDestinationRelation { relation in relation = relation.group { db in try expressions(db).map(\.sqlExpression) @@ -359,7 +359,7 @@ extension Association { /// 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 { + public func having(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self { withDestinationRelation { relation in relation = relation.having { db in try predicate(db).sqlExpression @@ -377,20 +377,6 @@ extension Association { } } - /// Creates an association that fetches *limit* rows, starting at *offset*. - /// - /// Any previous limit is replaced. - /// - /// - warning: Avoid this method: it is unlikely it does what you expect it - /// to do. It will be removed in a future GRDB version. - /// - /// :nodoc: - public func limit(_ limit: Int, offset: Int? = nil) -> Self { - 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. diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index b442506ae..e827c8adb 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -34,12 +34,12 @@ extension AssociationToMany { /// var team: Team /// var hasNoPlayer: Bool /// } - /// let request = Team.annotated(with: Team.players.isEmpty()) + /// let request = Team.annotated(with: Team.players.isEmpty) /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// - /// let teams: [Team] = try Team.having(Team.players.isEmpty()).fetchAll(db) - /// let teams: [Team] = try Team.having(!Team.players.isEmpty()) - /// let teams: [Team] = try Team.having(Team.players.isEmpty() == false) + /// let teams: [Team] = try Team.having(Team.players.isEmpty).fetchAll(db) + /// let teams: [Team] = try Team.having(!Team.players.isEmpty) + /// let teams: [Team] = try Team.having(Team.players.isEmpty == false) public var isEmpty: AssociationAggregate { makeAggregate(.isEmpty(.countDistinct(.fastPrimaryKey))) .forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") @@ -62,37 +62,9 @@ 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 { + public func average(_ expression: some 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 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 { + if let column = expression as? any ColumnExpression { let name = key.singularizedName return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { @@ -117,37 +89,9 @@ 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 { + public func max(_ expression: some 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 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 { + if let column = expression as? any ColumnExpression { let name = key.singularizedName return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { @@ -172,37 +116,9 @@ 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 { + public func min(_ expression: some 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 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 { + if let column = expression as? any ColumnExpression { let name = key.singularizedName return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { @@ -230,40 +146,9 @@ extension AssociationToMany { /// /// This aggregate invokes the `SUM` SQL function. See also `total(_:)`, and /// . - @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 { + public func sum(_ expression: some 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 - } - } - - /// 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) - /// - /// This aggregate invokes the `SUM` SQL function. See also `total(_:)`, and - /// . - public func sum(_ expression: SQLSpecificExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression])) - if let column = expression as? ColumnExpression { + if let column = expression as? any ColumnExpression { let name = key.singularizedName return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") } else { @@ -291,9 +176,9 @@ extension AssociationToMany { /// /// This aggregate invokes the `TOTAL` SQL function. See also `sum(_:)`, and /// . - public func total(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + public func total(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("TOTAL", [expression.sqlExpression])) - if let column = expression as? ColumnExpression { + if let column = expression as? any ColumnExpression { let name = key.singularizedName // Yes we use the `Sum` suffix instead of `Total`. Both `total(_:)` // and `sum(_:)` compute sums. @@ -364,9 +249,7 @@ public struct AssociationAggregate { /// - We don't know yet if the aggregated expression will be used in the /// SQL selection, or in the HAVING clause. /// - It helps implementing aggregate operators such as `&&`, `+`, etc. - func prepare(_ request: inout Request) -> SQLExpression - where Request: DerivableRequest, Request.RowDecoder == RowDecoder - { + func prepare(_ request: inout some DerivableRequest) -> SQLExpression { preparation.prepare(&request) } } @@ -402,7 +285,7 @@ extension AssociationAggregate: Refinable { /// return try AuthorInfo.fetchAll(db, request) /// } /// } - public func forKey(_ key: CodingKey) -> Self { + public func forKey(_ key: some CodingKey) -> Self { forKey(key.stringValue) } } @@ -420,9 +303,7 @@ extension AssociationAggregate: Refinable { /// We could have used a generic closure instead of this class... if only Swift /// would support generic closures. private class AssociationAggregatePreparation { - func prepare(_ request: inout Request) -> SQLExpression - where Request: DerivableRequest, Request.RowDecoder == RowDecoder - { + func prepare(_ request: inout some DerivableRequest) -> SQLExpression { fatalError("subclass must override") } } @@ -439,9 +320,7 @@ private class BasePreparation: self.expression = expression } - override func prepare(_ request: inout Request) -> SQLExpression - where Request: DerivableRequest, Request.RowDecoder == Association.OriginRowDecoder - { + override func prepare(_ request: inout some DerivableRequest) -> SQLExpression { // The fundamental request that supports association aggregate: // // SELECT parent.* @@ -472,9 +351,7 @@ private class MapPreparation: AssociationAggregatePreparation(_ request: inout Request) -> SQLExpression - where Request: DerivableRequest, Request.RowDecoder == RowDecoder - { + override func prepare(_ request: inout some DerivableRequest) -> SQLExpression { transform(base.prepare(&request)) } } @@ -502,9 +379,7 @@ private class CombinePreparation: AssociationAggregatePreparation(_ request: inout Request) -> SQLExpression - where Request: DerivableRequest, Request.RowDecoder == RowDecoder - { + override func prepare(_ request: inout some DerivableRequest) -> SQLExpression { let lhsExpression = lhs.prepare(&request) let rhsExpression = rhs.prepare(&request) return combine(lhsExpression, rhsExpression) @@ -549,7 +424,7 @@ public func && ( /// :nodoc: public func && ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 && rhs } @@ -558,7 +433,7 @@ public func && ( // TODO: test /// :nodoc: public func && ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -583,7 +458,7 @@ public func || ( /// :nodoc: public func || ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 || rhs } @@ -592,7 +467,7 @@ public func || ( // TODO: test /// :nodoc: public func || ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -621,7 +496,7 @@ public func == ( /// Author.having(Author.books.count == 3) public func == ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 == rhs } @@ -633,7 +508,7 @@ public func == ( /// /// Author.having(3 == Author.books.count) public func == ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -678,7 +553,7 @@ public func != ( /// Author.having(Author.books.count != 3) public func != ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 != rhs } @@ -690,7 +565,7 @@ public func != ( /// /// Author.having(3 != Author.books.count) public func != ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -735,7 +610,7 @@ public func === ( /// Author.having(Author.books.count === 3) public func === ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 === rhs } @@ -747,7 +622,7 @@ public func === ( /// /// Author.having(3 === Author.books.count) public func === ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -774,7 +649,7 @@ public func !== ( /// Author.having(Author.books.count !== 3) public func !== ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 !== rhs } @@ -786,7 +661,7 @@ public func !== ( /// /// Author.having(3 !== Author.books.count) public func !== ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -815,7 +690,7 @@ public func <= ( /// Author.having(Author.books.count <= 3) public func <= ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 <= rhs } @@ -827,7 +702,7 @@ public func <= ( /// /// Author.having(3 <= Author.books.count) public func <= ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -854,7 +729,7 @@ public func < ( /// Author.having(Author.books.count < 3) public func < ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 < rhs } @@ -866,7 +741,7 @@ public func < ( /// /// Author.having(3 < Author.books.count) public func < ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -893,7 +768,7 @@ public func > ( /// Author.having(Author.books.count > 3) public func > ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 > rhs } @@ -905,7 +780,7 @@ public func > ( /// /// Author.having(3 > Author.books.count) public func > ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -932,7 +807,7 @@ public func >= ( /// Author.having(Author.books.count >= 3) public func >= ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 >= rhs } @@ -944,7 +819,7 @@ public func >= ( /// /// Author.having(3 >= Author.books.count) public func >= ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -982,7 +857,7 @@ public func + ( /// Author.annotated(with: Author.books.count + 1) public func + ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 + rhs } @@ -994,7 +869,7 @@ public func + ( /// /// Author.annotated(with: 1 + Author.books.count) public func + ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -1021,7 +896,7 @@ public func - ( /// Author.annotated(with: Author.books.count - 1) public func - ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 - rhs } @@ -1033,7 +908,7 @@ public func - ( /// /// Author.annotated(with: 1 - Author.books.count) public func - ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -1060,7 +935,7 @@ public func * ( /// Author.annotated(with: Author.books.count * 2) public func * ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 * rhs } @@ -1072,7 +947,7 @@ public func * ( /// /// Author.annotated(with: 2 * Author.books.count) public func * ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -1099,7 +974,7 @@ public func / ( /// Author.annotated(with: Author.books.count / 2) public func / ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 / rhs } @@ -1111,7 +986,7 @@ public func / ( /// /// Author.annotated(with: 2 / Author.books.count) public func / ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -1125,7 +1000,7 @@ public func / ( /// Team.annotated(with: Team.players.min(Column("score")) ?? 0) public func ?? ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs diff --git a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift index 51eda18de..7a9068c4b 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift @@ -50,4 +50,16 @@ public struct HasManyThroughAssociation: AssociationToMany /// :nodoc: public var _sqlAssociation: _SQLAssociation + + init( + through pivot: Pivot, + using target: Target) + where Pivot: Association, + Target: Association, + Pivot.OriginRowDecoder == Origin, + Pivot.RowDecoder == Target.OriginRowDecoder, + Target.RowDecoder == Destination + { + _sqlAssociation = target._sqlAssociation.through(pivot._sqlAssociation) + } } diff --git a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift index b77569198..29a9bbac8 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift @@ -30,4 +30,16 @@ public struct HasOneThroughAssociation: AssociationToOne { /// :nodoc: public var _sqlAssociation: _SQLAssociation + + init( + through pivot: Pivot, + using target: Target) + where Pivot: AssociationToOne, + Target: AssociationToOne, + Pivot.OriginRowDecoder == Origin, + Pivot.RowDecoder == Target.OriginRowDecoder, + Target.RowDecoder == Destination + { + _sqlAssociation = target._sqlAssociation.through(pivot._sqlAssociation) + } } diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index 293a7b9a0..26392b01e 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -36,11 +36,11 @@ public struct CommonTableExpression { /// - parameter columns: The columns of the common table expression. If nil, /// the columns are the columns of the request. /// - parameter request: A request. - private init( + private init( recursive: Bool = false, named tableName: String, columns: [String]? = nil, - request: Request, + request: some SQLSubqueryable, type: RowDecoder.Type) { self.tableName = tableName @@ -72,11 +72,11 @@ extension CommonTableExpression { /// - parameter columns: The columns of the common table expression. If nil, /// the columns are the columns of the request. /// - parameter request: A request. - public init( + public init( recursive: Bool = false, named tableName: String, columns: [String]? = nil, - request: Request) + request: some SQLSubqueryable) { self.init( recursive: recursive, @@ -151,7 +151,7 @@ extension CommonTableExpression { } } -extension CommonTableExpression where RowDecoder == Row { +extension CommonTableExpression { /// Creates a common table expression from a request. /// /// For example: @@ -172,11 +172,11 @@ extension CommonTableExpression where RowDecoder == Row { /// - parameter columns: The columns of the common table expression. If nil, /// the columns are the columns of the request. /// - parameter request: A request. - public init( + public init( recursive: Bool = false, named tableName: String, columns: [String]? = nil, - request: Request) + request: some SQLSubqueryable) { self.init( recursive: recursive, @@ -296,7 +296,7 @@ extension CommonTableExpression { /// /// // name IN playerName /// playerNameCTE.contains(Column("name")) - public func contains(_ element: SQLExpressible) -> SQLExpression { + public func contains(_ element: some SQLExpressible) -> SQLExpression { SQLCollection.table(tableName).contains(element.sqlExpression) } } @@ -352,7 +352,7 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( @@ -388,7 +388,7 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to destination: Destination.Type, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation where Destination: TableRecord { @@ -425,7 +425,7 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to destination: Table, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 83f22d3a3..d7d7663ec 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -76,7 +76,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// request /// .select { db in [Column("id")] } /// .select { db in [Column("email")] } - public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { + public func select(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> QueryInterfaceRequest { with { $0.relation = $0.relation.select { db in try selection(db).map(\.sqlSelection) @@ -92,7 +92,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// let request = Player.all().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) + public func select(_ selection: [any SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { select(selection).asRequest(of: RowDecoder.self) @@ -106,7 +106,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// let request = Player.all().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) + public func select(_ selection: any SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { select(selection, as: type) @@ -149,6 +149,30 @@ extension QueryInterfaceRequest: SelectionRequest { select(sqlLiteral, as: type) } + /// Creates a request which selects the primary key. + /// + /// All primary keys are supported: + /// + /// // SELECT id FROM player WHERE ... + /// let request = try Player.filter(...).selectPrimaryKey(as: Int64.self) + /// + /// // SELECT code FROM country WHERE ... + /// let request = try Country.filter(...).selectPrimaryKey(as: String.self) + /// + /// // SELECT citizenId, countryCode FROM citizenship WHERE ... + /// let request = try Citizenship.filter(...).selectPrimaryKey(as: Row.self) + public func selectPrimaryKey(as type: PrimaryKey.Type = PrimaryKey.self) + -> QueryInterfaceRequest + { + with { request in + let tableName = request.relation.source.tableName + request.relation = request.relation.select { db in + try db.primaryKey(tableName).columns.map { Column($0).sqlSelection } + } + } + .asRequest(of: PrimaryKey.self) + } + /// Creates a request which appends *selection promise*. /// /// // SELECT id, email, name FROM player @@ -156,7 +180,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// request = request /// .select([Column("id"), Column("email")]) /// .annotated(with: { db in [Column("name")] }) - public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { + public func annotated(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> QueryInterfaceRequest { with { $0.relation = $0.relation.annotated { db in try selection(db).map(\.sqlSelection) @@ -165,47 +189,6 @@ extension QueryInterfaceRequest: SelectionRequest { } } -@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) - } -} - extension QueryInterfaceRequest: FilteredRequest { /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. @@ -213,7 +196,7 @@ extension QueryInterfaceRequest: FilteredRequest { /// // SELECT * FROM player WHERE 1 /// var request = Player.all() /// request = request.filter { db in true } - public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { + public func filter(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> QueryInterfaceRequest { with { $0.relation = $0.relation.filter { db in try predicate(db).sqlExpression @@ -236,7 +219,7 @@ extension QueryInterfaceRequest: OrderedRequest { /// .order{ _ in [Column("email")] } /// .reversed() /// .order{ _ in [Column("name")] } - public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest { + public func order(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> QueryInterfaceRequest { with { $0.relation = $0.relation.order { db in try orderings(db).map(\.sqlOrdering) @@ -275,7 +258,7 @@ extension QueryInterfaceRequest: OrderedRequest { extension QueryInterfaceRequest: AggregatingRequest { /// Creates a request grouped according to *expressions promise*. - public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest { + public func group(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> QueryInterfaceRequest { with { $0.relation = $0.relation.group { db in try expressions(db).map(\.sqlExpression) @@ -285,7 +268,7 @@ extension QueryInterfaceRequest: AggregatingRequest { /// 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 { + public func having(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> QueryInterfaceRequest { with { $0.relation = $0.relation.having { db in try predicate(db).sqlExpression @@ -378,7 +361,7 @@ extension QueryInterfaceRequest: DerivableRequest { /// request = request.limit(10, offset: 20) /// /// Any previous limit is replaced. - public func limit(_ limit: Int, offset: Int?) -> QueryInterfaceRequest { + public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { with { $0.relation.limit = SQLLimit(limit: limit, offset: offset) } @@ -427,18 +410,231 @@ extension QueryInterfaceRequest { // MARK: - Batch Delete extension QueryInterfaceRequest { - /// Deletes matching rows; returns the number of deleted rows. + /// Deletes matching rows, and 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 SQLQueryGenerator(relation: relation).makeDeleteStatement(db).execute() + let statement = try SQLQueryGenerator(relation: relation).makeDeleteStatement(db) + try statement.execute() return db.changesCount } } +// MARK: - Batch Delete and Fetch + +extension QueryInterfaceRequest { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Returns a `DELETE ... RETURNING ...` prepared statement. + /// + /// For example: + /// + /// // Delete all players and return their names + /// // DELETE FROM player RETURNING name + /// let request = Player.all() + /// let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")]) + /// let deletedNames = try String.fetchSet(statement) + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter selection: The returned columns (must not be empty). + /// - returns: A prepared statement. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - precondition: `selection` is not empty. + public func deleteAndFetchStatement( + _ db: Database, + selection: [any SQLSelectable]) + throws -> Statement + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection) + } + + /// Returns a cursor over a `DELETE ... RETURNING ...` statement. + /// + /// For example: + /// + /// // Fetch all deleted players + /// // DELETE FROM player RETURNING * + /// let request = Player.all() + /// let cursor = try request.deleteAndFetchCursor(db) + /// let deletedPlayers = try Array(cursor) // [Player] + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - returns: A cursor over the deleted records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func deleteAndFetchCursor(_ db: Database) + throws -> RecordCursor + where RowDecoder: FetchableRecord & TableRecord + { + let statement = try deleteAndFetchStatement(db, selection: RowDecoder.databaseSelection) + return try RowDecoder.fetchCursor(statement) + } + + /// Executes a `DELETE ... RETURNING ...` statement and returns the + /// deleted records. + /// + /// For example: + /// + /// // Fetch all deleted players + /// // DELETE FROM player RETURNING * + /// let request = Player.all() + /// let deletedPlayers = try request.deleteAndFetchAll(db) + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - returns: An array of deleted records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func deleteAndFetchAll(_ db: Database) + throws -> [RowDecoder] + where RowDecoder: FetchableRecord & TableRecord + { + try Array(deleteAndFetchCursor(db)) + } + + /// Executes a `DELETE ... RETURNING ...` statement and returns the + /// deleted records. + /// + /// For example: + /// + /// // Fetch all deleted players + /// // DELETE FROM player RETURNING * + /// let request = Player.all() + /// let deletedPlayers = try request.deleteAndFetchSet(db) + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - returns: A set of deleted records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func deleteAndFetchSet(_ db: Database) + throws -> Set + where RowDecoder: FetchableRecord & TableRecord & Hashable + { + try Set(deleteAndFetchCursor(db)) + } +#else + /// Returns a `DELETE ... RETURNING ...` prepared statement. + /// + /// For example: + /// + /// // Delete all players and return their names + /// // DELETE FROM player RETURNING name + /// let request = Player.all() + /// let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")]) + /// let deletedNames = try String.fetchSet(statement) + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter selection: The returned columns (must not be empty). + /// - returns: A prepared statement. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - precondition: `selection` is not empty. + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func deleteAndFetchStatement( + _ db: Database, + selection: [any SQLSelectable]) + throws -> Statement + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection) + } + + /// Returns a cursor over a `DELETE ... RETURNING ...` statement. + /// + /// For example: + /// + /// // Fetch all deleted players + /// // DELETE FROM player RETURNING * + /// let request = Player.all() + /// let cursor = try request.deleteAndFetchCursor(db) + /// let deletedPlayers = try Array(cursor) // [Player] + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - returns: A cursor over the deleted records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func deleteAndFetchCursor(_ db: Database) + throws -> RecordCursor + where RowDecoder: FetchableRecord & TableRecord + { + let statement = try deleteAndFetchStatement(db, selection: RowDecoder.databaseSelection) + return try RowDecoder.fetchCursor(statement) + } + + /// Executes a `DELETE ... RETURNING ...` statement and returns the + /// deleted records. + /// + /// For example: + /// + /// // Fetch all deleted players + /// // DELETE FROM player RETURNING * + /// let request = Player.all() + /// let deletedPlayers = try request.deleteAndFetchAll(db) + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - returns: An array of deleted records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func deleteAndFetchAll(_ db: Database) + throws -> [RowDecoder] + where RowDecoder: FetchableRecord & TableRecord + { + try Array(deleteAndFetchCursor(db)) + } + + /// Executes a `DELETE ... RETURNING ...` statement and returns the + /// deleted records. + /// + /// For example: + /// + /// // Fetch all deleted players + /// // DELETE FROM player RETURNING * + /// let request = Player.all() + /// let deletedPlayers = try request.deleteAndFetchSet(db) + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - returns: A set of deleted records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func deleteAndFetchSet(_ db: Database) + throws -> Set + where RowDecoder: FetchableRecord & TableRecord & Hashable + { + try Set(deleteAndFetchCursor(db)) + } +#endif +} + // MARK: - Batch Update extension QueryInterfaceRequest { @@ -448,20 +644,21 @@ extension QueryInterfaceRequest { // 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 { + if let recordType = RowDecoder.self as? any MutablePersistableRecord.Type { return recordType.persistenceConflictPolicy.conflictResolutionForUpdate } else { return .abort } } - /// Updates matching rows; returns the number of updated rows. + /// Updates matching rows, and returns the number of updated rows. /// /// For example: /// /// try dbQueue.write { db in /// // UPDATE player SET score = 0 - /// try Player.all().updateAll(db, [Column("score").set(to: 0)]) + /// let request = Player.all() + /// try request.updateAll(db, [Column("score").set(to: 0)]) /// } /// /// - parameter db: A database connection. @@ -477,9 +674,9 @@ extension QueryInterfaceRequest { { let conflictResolution = conflictResolution ?? defaultConflictResolutionForUpdate guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement( - db, - conflictResolution: conflictResolution, - assignments: assignments) else + db, + conflictResolution: conflictResolution, + assignments: assignments) else { // database not hit return 0 @@ -488,33 +685,324 @@ extension QueryInterfaceRequest { return db.changesCount } - /// Updates matching rows; returns the number of updated rows. + /// Updates matching rows, and returns the number of updated rows. /// /// For example: /// /// try dbQueue.write { db in /// // UPDATE player SET score = 0 - /// try Player.all().updateAll(db, Column("score").set(to: 0)) + /// let request = Player.all() + /// try request.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. + /// - parameter assignments: 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...) + _ assignments: ColumnAssignment...) throws -> Int { - try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments) + try updateAll(db, onConflict: conflictResolution, assignments) } } +// MARK: - Batch Update and Fetch + +extension QueryInterfaceRequest { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Returns an `UPDATE ... RETURNING ...` prepared statement. + /// + /// For example: + /// + /// // Fetch all updated scores + /// // UPDATE player SET score = score + 10 RETURNING score + /// let request = Player.all() + /// let statement = try request.updateAndFetchStatement( + /// db, [Column("score") += 10], + /// select: [Column("score")]) + /// let updatedScores = try Int.fetchAll(statement) + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: An array of column assignments + /// (must not be empty). + /// - parameter selection: The returned columns (must not be empty). + /// - returns: A prepared statement. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - precondition: `selection` and `assignments` are not empty. + public func updateAndFetchStatement( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignments: [ColumnAssignment], + selection: [any SQLSelectable]) + throws -> Statement + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + + let conflictResolution = conflictResolution ?? defaultConflictResolutionForUpdate + guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement( + db, + conflictResolution: conflictResolution, + assignments: assignments, + selection: selection) + else { + fatalError("Invalid empty assignments") + } + + return updateStatement + } + + /// Returns a cursor over an `UPDATE ... RETURNING ...` statement. + /// + /// For example: + /// + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let cursor = try request.updateAndFetchCursor(db, [Column("score") += 10]) + /// let updatedPlayers = try Array(cursor) // [Player] + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: An array of column assignments. + /// - returns: A cursor over the updated records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - precondition: `assignments` is not empty. + public func updateAndFetchCursor( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignments: [ColumnAssignment]) + throws -> RecordCursor + where RowDecoder: FetchableRecord & TableRecord + { + let statement = try updateAndFetchStatement( + db, + onConflict: conflictResolution, + assignments, + selection: RowDecoder.databaseSelection) + return try RowDecoder.fetchCursor(statement) + } + + /// Execute an `UPDATE ... RETURNING ...` statement and returns the + /// updated records. + /// + /// For example: + /// + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let updatedPlayers = try request.updateAndFetchAll(db, [Column("score") += 10]) + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: An array of column assignments. + /// - returns: An array of updated records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - precondition: `assignments` is not empty. + public func updateAndFetchAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignments: [ColumnAssignment]) + throws -> [RowDecoder] + where RowDecoder: FetchableRecord & TableRecord + { + try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments)) + } + + /// Execute an `UPDATE ... RETURNING ...` statement and returns the + /// updated records. + /// + /// For example: + /// + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let updatedPlayers = try request.updateAndFetchSet(db, [Column("score") += 10]) + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: An array of column assignments. + /// - returns: A set of updated records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - precondition: `assignments` is not empty. + public func updateAndFetchSet( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignments: [ColumnAssignment]) + throws -> Set + where RowDecoder: FetchableRecord & TableRecord & Hashable + { + try Set(updateAndFetchCursor(db, onConflict: conflictResolution, assignments)) + } +#else + /// Returns an `UPDATE ... RETURNING ...` prepared statement. + /// + /// For example: + /// + /// // Fetch all updated scores + /// // UPDATE player SET score = score + 10 RETURNING score + /// let request = Player.all() + /// let statement = try request.updateAndFetchStatement( + /// db, [Column("score") += 10], + /// select: [Column("score")]) + /// let updatedScores = try Int.fetchAll(statement) + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: An array of column assignments + /// (must not be empty). + /// - parameter selection: The returned columns (must not be empty). + /// - returns: A prepared statement. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - precondition: `selection` and `assignments` are not empty. + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func updateAndFetchStatement( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignments: [ColumnAssignment], + selection: [any SQLSelectable]) + throws -> Statement + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + + let conflictResolution = conflictResolution ?? defaultConflictResolutionForUpdate + guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement( + db, + conflictResolution: conflictResolution, + assignments: assignments, + selection: selection) + else { + fatalError("Invalid empty assignments") + } + + return updateStatement + } + + /// Returns a cursor over an `UPDATE ... RETURNING ...` statement. + /// + /// For example: + /// + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let cursor = try request.updateAndFetchCursor(db, [Column("score") += 10]) + /// let updatedPlayers = try Array(cursor) // [Player] + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: An array of column assignments. + /// - returns: A cursor over the updated records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - precondition: `assignments` is not empty. + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func updateAndFetchCursor( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignments: [ColumnAssignment]) + throws -> RecordCursor + where RowDecoder: FetchableRecord & TableRecord + { + let statement = try updateAndFetchStatement( + db, + onConflict: conflictResolution, + assignments, + selection: RowDecoder.databaseSelection) + return try RowDecoder.fetchCursor(statement) + } + + /// Execute an `UPDATE ... RETURNING ...` statement and returns the + /// updated records. + /// + /// For example: + /// + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let updatedPlayers = try request.updateAndFetchAll(db, [Column("score") += 10]) + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: An array of column assignments. + /// - returns: An array of updated records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - precondition: `assignments` is not empty. + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func updateAndFetchAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignments: [ColumnAssignment]) + throws -> [RowDecoder] + where RowDecoder: FetchableRecord & TableRecord + { + try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments)) + } + + /// Execute an `UPDATE ... RETURNING ...` statement and returns the + /// updated records. + /// + /// For example: + /// + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let updatedPlayers = try request.updateAndFetchSet(db, [Column("score") += 10]) + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: An array of column assignments. + /// - returns: A set of updated records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - precondition: `assignments` is not empty. + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func updateAndFetchSet( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignments: [ColumnAssignment]) + throws -> Set + where RowDecoder: FetchableRecord & TableRecord & Hashable + { + try Set(updateAndFetchCursor(db, onConflict: conflictResolution, assignments)) + } +#endif +} + // MARK: - ColumnAssignment /// A ColumnAssignment can update rows in the database. @@ -528,11 +1016,11 @@ extension QueryInterfaceRequest { /// try Player.updateAll(db, assignment) /// } public struct ColumnAssignment { - var column: ColumnExpression + var columnName: String var value: SQLExpression func sql(_ context: SQLGenerationContext) throws -> String { - try column.sqlExpression.sql(context) + " = " + value.sql(context) + try Column(columnName).sqlExpression.sql(context) + " = " + value.sql(context) } } @@ -548,8 +1036,8 @@ extension ColumnExpression { /// // UPDATE player SET score = 0 /// try Player.updateAll(db, Column("score").set(to: 0)) /// } - public func set(to value: SQLExpressible?) -> ColumnAssignment { - ColumnAssignment(column: self, value: value?.sqlExpression ?? .null) + public func set(to value: (any SQLExpressible)?) -> ColumnAssignment { + ColumnAssignment(columnName: name, value: value?.sqlExpression ?? .null) } } @@ -562,7 +1050,7 @@ extension ColumnExpression { /// // UPDATE player SET score = score + 1 /// try Player.updateAll(db, Column("score") += 1) /// } -public func += (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { +public func += (column: some ColumnExpression, value: some SQLExpressible) -> ColumnAssignment { column.set(to: column + value) } @@ -575,7 +1063,7 @@ public func += (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign /// // UPDATE player SET score = score - 1 /// try Player.updateAll(db, Column("score") -= 1) /// } -public func -= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { +public func -= (column: some ColumnExpression, value: some SQLExpressible) -> ColumnAssignment { column.set(to: column - value) } @@ -588,7 +1076,7 @@ public func -= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign /// // UPDATE player SET score = score * 2 /// try Player.updateAll(db, Column("score") *= 2) /// } -public func *= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { +public func *= (column: some ColumnExpression, value: some SQLExpressible) -> ColumnAssignment { column.set(to: column * value) } @@ -601,7 +1089,7 @@ public func *= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign /// // UPDATE player SET score = score / 2 /// try Player.updateAll(db, Column("score") /= 2) /// } -public func /= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { +public func /= (column: some ColumnExpression, value: some SQLExpressible) -> ColumnAssignment { column.set(to: column / value) } @@ -656,15 +1144,7 @@ private func prefetch( // WITH grdb_base AS (SELECT a, b FROM parent) // SELECT * FROM child // WHERE (a, b) IN grdb_base - // - // This technique works well, but there is one precondition: row - // values must be available (https://www.sqlite.org/rowvalue.html). - // This is the case of almost all our target platforms. - // - // Otherwise, we fallback to the `(a = ? AND b = ?) OR ...` - // condition (the one that may fail if there are too many - // base rows). - let usesCommonTableExpression = pivotMapping.count > 1 && SQLExpression.rowValuesAreAvailable + let usesCommonTableExpression = pivotMapping.count > 1 let prefetchRequest: QueryInterfaceRequest if usesCommonTableExpression { @@ -830,7 +1310,7 @@ throws -> DatabaseRegion .databaseRegion // contains region of nested associations } -extension Array where Element == Row { +extension [Row] { /// - precondition: Columns all exist in all rows. All rows have the same /// columnns, in the same order. fileprivate func grouped(byDatabaseValuesOnColumns columns: [String]) -> [[DatabaseValue]: [Row]] { @@ -847,7 +1327,7 @@ extension Array where Element == Row { extension Row { /// - precondition: Columns all exist in the row. fileprivate func indexes(forColumns columns: [String]) -> [Int] { - columns.map { column -> Int in + columns.map { column in guard let index = index(forColumn: column) else { fatalError("Column \(column) is not selected") } diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 44df8aa24..e1826761a 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -4,7 +4,7 @@ import Foundation /// The protocol for all requests that know how database rows should /// be interpreted. -public protocol TypedRequest { +public protocol TypedRequest { /// The type that can decode database rows. /// /// In the request below, it is Player: @@ -29,7 +29,7 @@ public protocol SelectionRequest { /// request /// .select { db in [Column("id")] } /// .select { db in [Column("email")] } - func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self + func select(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self /// Creates a request which appends *selection promise*. /// @@ -38,7 +38,7 @@ public protocol SelectionRequest { /// request = request /// .select([Column("id"), Column("email")]) /// .annotated(with: { db in [Column("name")] }) - func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self + func annotated(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self } extension SelectionRequest { @@ -54,7 +54,7 @@ extension SelectionRequest { /// request /// .select([Column("id")]) /// .select([Column("email")]) - public func select(_ selection: [SQLSelectable]) -> Self { + public func select(_ selection: [any SQLSelectable]) -> Self { select { _ in selection } } @@ -70,7 +70,7 @@ extension SelectionRequest { /// request /// .select(Column("id")) /// .select(Column("email")) - public func select(_ selection: SQLSelectable...) -> Self { + public func select(_ selection: any SQLSelectable...) -> Self { select(selection) } @@ -120,7 +120,7 @@ extension SelectionRequest { /// request = request /// .select([Column("id"), Column("email")]) /// .annotated(with: [Column("name")]) - public func annotated(with selection: [SQLSelectable]) -> Self { + public func annotated(with selection: [any SQLSelectable]) -> Self { annotated(with: { _ in selection }) } @@ -131,7 +131,7 @@ extension SelectionRequest { /// request = request /// .select([Column("id"), Column("email")]) /// .annotated(with: Column("name")) - public func annotated(with selection: SQLSelectable...) -> Self { + public func annotated(with selection: any SQLSelectable...) -> Self { annotated(with: selection) } } @@ -146,21 +146,10 @@ public protocol FilteredRequest { /// // SELECT * FROM player WHERE 1 /// var request = Player.all() /// request = request.filter { db in true } - func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self + func filter(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self } extension FilteredRequest { - /// Creates a request with the provided *predicate* added to the - /// eventual set of already applied predicates. - /// - /// // SELECT * FROM player WHERE 0 - /// var request = Player.all() - /// request = request.filter(false) - @available(*, deprecated, message: "Did you mean filter(id:) or filter(key:)? If not, prefer filter(value.databaseValue) instead. See also none().") // swiftlint:disable:this line_length - public func filter(_ predicate: SQLExpressible) -> Self { - filter { _ in predicate } - } - // Accept SQLSpecificExpressible instead of SQLExpressible, so that we // prevent the `Player.filter(42)` misuse. // See https://github.com/groue/GRDB.swift/pull/864 @@ -170,7 +159,7 @@ extension FilteredRequest { /// // SELECT * FROM player WHERE email = 'arthur@example.com' /// var request = Player.all() /// request = request.filter(Column("email") == "arthur@example.com") - public func filter(_ predicate: SQLSpecificExpressible) -> Self { + public func filter(_ predicate: some SQLSpecificExpressible) -> Self { filter { _ in predicate } } @@ -244,8 +233,8 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// let request = try Player...filter(key: 1) /// /// - parameter key: A primary key - public func filter(key: PrimaryKeyType?) -> Self { - guard let key = key else { + public func filter(key: some DatabaseValueConvertible) -> Self { + if key.databaseValue.isNull { return none() } return filter(keys: [key]) @@ -267,14 +256,14 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { // (customizing TableRequest where RowDecoder: EncodableRecord) would // make it impractical to define `filter(id:)`, `fetchOne(_:key:)`, // `deleteAll(_:ids:)` etc. - if let recordType = RowDecoder.self as? EncodableRecord.Type { - if Sequence.Element.self == Date.self { + if let recordType = RowDecoder.self as? any EncodableRecord.Type { + if Sequence.Element.self == Date.self || Sequence.Element.self == Optional.self { let strategy = recordType.databaseDateEncodingStrategy - let keys = keys.compactMap { strategy.encode($0 as! Date)?.databaseValue } + let keys = keys.compactMap { ($0 as! Date?).flatMap(strategy.encode)?.databaseValue } return filter(rawKeys: keys) - } else if Sequence.Element.self == UUID.self { + } else if Sequence.Element.self == UUID.self || Sequence.Element.self == Optional.self { let strategy = recordType.databaseUUIDEncodingStrategy - let keys = keys.map { strategy.encode($0 as! UUID).databaseValue } + let keys = keys.map { ($0 as! UUID?).map(strategy.encode)?.databaseValue } return filter(rawKeys: keys) } } @@ -285,15 +274,18 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// Creates a request filtered by primary key. /// /// // SELECT * FROM player WHERE ... id IN (1, 2, 3) - /// let request = try Player...filter(encodedKeys: [1, 2, 3]) + /// let request = try Player...filter(rawKeys: [1, 2, 3]) /// /// - parameter keys: A collection of primary keys - func filter(rawKeys: Sequence) - -> Self - where Sequence.Element: DatabaseValueConvertible - { - let keys = Array(rawKeys) - if keys.isEmpty { + func filter(rawKeys: some Sequence) -> Self { + // Don't bother removing NULLs. We'd lose CPU cycles, and this does not + // change the SQLite results anyway. + let expressions = rawKeys.map { + $0.databaseValue.sqlExpression + } + + if expressions.isEmpty { + // Don't hit the database return none() } @@ -303,7 +295,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { GRDBPrecondition( primaryKey.columns.count == 1, "Requesting by key requires a single-column primary key in the table \(databaseTableName)") - return keys.contains(Column(primaryKey.columns[0])) + return SQLCollection.array(expressions).contains(Column(primaryKey.columns[0]).sqlExpression) } } @@ -316,8 +308,8 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// index on the key columns. /// /// - parameter key: A unique key - public func filter(key: [String: DatabaseValueConvertible?]?) -> Self { - guard let key = key else { + public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> Self { + guard let key else { return none() } return filter(keys: [key]) @@ -332,7 +324,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// index on the key columns. /// /// - parameter keys: A collection of unique keys - public func filter(keys: [[String: DatabaseValueConvertible?]]) -> Self { + public func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> Self { if keys.isEmpty { return none() } @@ -342,11 +334,11 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { try keys .map { key in // Prevent filter(keys: [["foo": 1, "bar": 2]]) where - // ("foo", "bar") is not a unique key (primary key or columns of a - // unique index) + // ("foo", "bar") do not contain a unique key (primary key + // or unique index). guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { fatalError(""" - table \(databaseTableName) has no unique index on column(s) \ + table \(databaseTableName) has no unique key on column(s) \ \(key.keys.sorted().joined(separator: ", ")) """) } @@ -398,42 +390,7 @@ where Self: FilteredRequest, /// let request = try Player...filter(ids: [1, 2, 3]) /// /// - parameter ids: A collection of primary keys - public func filter(ids: Collection) - -> Self - where Collection.Element == RowDecoder.ID - { - filter(keys: ids) - } -} - -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) -extension TableRequest -where Self: FilteredRequest, - Self: TypedRequest, - RowDecoder: Identifiable, - RowDecoder.ID: _OptionalProtocol, - RowDecoder.ID.Wrapped: DatabaseValueConvertible -{ - /// Creates a request filtered by primary key. - /// - /// // SELECT * FROM player WHERE ... id = 1 - /// let request = try Player...filter(id: 1) - /// - /// - parameter id: A primary key - public func filter(id: RowDecoder.ID.Wrapped) -> Self { - filter(key: id) - } - - /// Creates a request filtered by primary key. - /// - /// // SELECT * FROM player WHERE ... id IN (1, 2, 3) - /// let request = try Player...filter(ids: [1, 2, 3]) - /// - /// - parameter ids: A collection of primary keys - public func filter(ids: Collection) - -> Self - where Collection.Element == RowDecoder.ID.Wrapped - { + public func filter(ids: some Collection) -> Self { filter(keys: ids) } } @@ -455,17 +412,25 @@ extension TableRequest where Self: AggregatingRequest { return group { db in let primaryKey = try db.primaryKey(tableName) if let rowIDColumn = primaryKey.rowIDColumn { - // Prefer the user-provided name of the rowid + // Prefer the user-provided name of the rowid: + // + // // CREATE TABLE player (id INTEGER PRIMARY KEY, ...) + // // SELECT * FROM player GROUP BY id + // Player.all().groupByPrimaryKey() return [Column(rowIDColumn)] } else if primaryKey.tableHasRowID { // Prefer the rowid - #if compiler(>=5.5) + // + // // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...) + // // SELECT * FROM player GROUP BY rowid + // Player.all().groupByPrimaryKey() return [.rowID] - #else - return [Column.rowID] - #endif } else { // WITHOUT ROWID table: group by primary key columns + // + // // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...) WITHOUT ROWID + // // SELECT * FROM player GROUP BY uuid + // Player.all().groupByPrimaryKey() return primaryKey.columns.map { Column($0) } } } @@ -477,21 +442,21 @@ extension TableRequest where Self: AggregatingRequest { /// The protocol for all requests that can aggregate. public protocol AggregatingRequest { /// Creates a request grouped according to *expressions promise*. - func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self + func group(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. - func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self + func having(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self } extension AggregatingRequest { /// Creates a request grouped according to *expressions*. - public func group(_ expressions: [SQLExpressible]) -> Self { + public func group(_ expressions: [any SQLExpressible]) -> Self { group { _ in expressions } } /// Creates a request grouped according to *expressions*. - public func group(_ expressions: SQLExpressible...) -> Self { + public func group(_ expressions: any SQLExpressible...) -> Self { group(expressions) } @@ -508,7 +473,7 @@ extension AggregatingRequest { /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. - public func having(_ predicate: SQLExpressible) -> Self { + public func having(_ predicate: some SQLExpressible) -> Self { having { _ in predicate } } @@ -543,7 +508,7 @@ public protocol OrderedRequest { /// .order{ _ in [Column("email")] } /// .reversed() /// .order{ _ in [Column("name")] } - func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self + func order(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self /// Creates a request that reverses applied orderings. /// @@ -580,7 +545,7 @@ extension OrderedRequest { /// .order(Column("email")) /// .reversed() /// .order(Column("name")) - public func order(_ orderings: SQLOrderingTerm...) -> Self { + public func order(_ orderings: any SQLOrderingTerm...) -> Self { order { _ in orderings } } @@ -597,7 +562,7 @@ extension OrderedRequest { /// .order(Column("email")) /// .reversed() /// .order(Column("name")) - public func order(_ orderings: [SQLOrderingTerm]) -> Self { + public func order(_ orderings: [any SQLOrderingTerm]) -> Self { order { _ in orderings } } @@ -666,7 +631,7 @@ public protocol _JoinableRequest { } /// The protocol for all requests that can be associated. -public protocol JoinableRequest: TypedRequest, _JoinableRequest { } +public protocol JoinableRequest: TypedRequest, _JoinableRequest { } extension JoinableRequest { /// Creates a request that prefetches an association. @@ -794,9 +759,9 @@ extension JoinableRequest where Self: SelectionRequest { // MARK: - DerivableRequest /// The base protocol for all requests that can be refined. -public protocol DerivableRequest: AggregatingRequest, FilteredRequest, - JoinableRequest, OrderedRequest, - SelectionRequest, TableRequest +public protocol DerivableRequest: AggregatingRequest, FilteredRequest, + JoinableRequest, OrderedRequest, + SelectionRequest, TableRequest { /// Creates a request which returns distinct rows. /// @@ -809,20 +774,6 @@ public protocol DerivableRequest: AggregatingRequest, FilteredRequest, /// request = request.distinct() func distinct() -> Self - /// Creates a request which fetches *limit* rows, starting at *offset*. - /// - /// // SELECT * FROM player LIMIT 10 OFFSET 20 - /// var request = Player.all() - /// request = request.limit(10, offset: 20) - /// - /// Any previous limit is replaced. - /// - /// - warning: Avoid to call this method on associations: it is unlikely it - /// does what you expect it to do. Only call it on requests. - /// - /// :nodoc: - func limit(_ limit: Int, offset: Int?) -> Self - /// Returns a request which embeds the common table expression. /// /// If a common table expression with the same table name had already been @@ -856,23 +807,18 @@ public protocol DerivableRequest: AggregatingRequest, FilteredRequest, func with(_ cte: CommonTableExpression) -> Self } +// Association aggregates don't require all DerivableRequest abilities. The +// minimum set of requirements is: +// +// - AggregatingRequest, for the GROUP BY and HAVING clauses +// - TableRequest, for grouping by primary key +// - JoinableRequest, for joining associations +// - SelectionRequest, for annotating the selection +// +// It is just that extending DerivableRequest is simpler. We want the user to +// use aggregates on QueryInterfaceRequest and associations: both conform to +// DerivableRequest already. extension DerivableRequest { - /// Creates a request which fetches *limit* rows. - /// - /// // SELECT * FROM player LIMIT 1 - /// var request = Player.all() - /// request = request.limit(1) - /// - /// Any previous limit is replaced. - /// - /// - warning: Avoid to call this method on associations: it is unlikely it - /// does what you expect it to do. Only call it on requests. - /// - /// :nodoc: - public func limit(_ limit: Int) -> Self { - self.limit(limit, offset: nil) - } - private func annotated(with aggregate: AssociationAggregate) -> Self { var request = self let expression = aggregate.prepare(&request) diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index 4bb52256d..1bc67c9cf 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -52,12 +52,10 @@ extension ColumnExpression { } } -#if compiler(>=5.5) extension ColumnExpression where Self == Column { /// The hidden rowID column public static var rowID: Self { Column.rowID } } -#endif /// A column in a database table. /// @@ -78,7 +76,7 @@ public struct Column: ColumnExpression, Equatable { } /// Creates a column given a CodingKey. - public init(_ codingKey: CodingKey) { + public init(_ codingKey: some CodingKey) { self.name = codingKey.stringValue } diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index 84c75974f..c6d5fb2a2 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -120,7 +120,7 @@ public struct _SQLAssociation { // via: Pivot.belongsTo(Destination.self)) // Origin(id: 1).request(for: association) let reversedSteps = zip(steps, steps.dropFirst()) - .map { (step, nextStep) -> SQLAssociationStep in + .map { (step, nextStep) in // Intermediate steps are not selected, and including(all:) // children are useless: let relation = step.relation diff --git a/GRDB/QueryInterface/SQL/SQLCollection.swift b/GRDB/QueryInterface/SQL/SQLCollection.swift index 817d61366..98435bc02 100644 --- a/GRDB/QueryInterface/SQL/SQLCollection.swift +++ b/GRDB/QueryInterface/SQL/SQLCollection.swift @@ -101,6 +101,7 @@ extension SQLCollection { case let .array(expressions): guard let expression = expressions.first else { + // [].contains(...) -> false return false.sqlExpression } diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index a0fb30551..04fe96e7c 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -370,17 +370,9 @@ public struct SQLExpression { } } -@available(*, deprecated, renamed: "SQLExpression.AssociativeBinaryOperator") -public typealias SQLAssociativeBinaryOperator = SQLExpression.AssociativeBinaryOperator - // MARK: - Creating Expressions -extension SQLExpression { - - /// SQLite row values were shipped in SQLite 3.15: - /// - static let rowValuesAreAvailable = (sqlite3_libversion_number() >= 3015000) - +extension SQLExpression { // MARK: Basic Expressions /// A column. @@ -1667,12 +1659,10 @@ public protocol SQLExpressible { var sqlExpression: SQLExpression { get } } -#if compiler(>=5.5) extension SQLExpressible where Self == Column { /// The hidden rowID column public static var rowID: Self { Column.rowID } } -#endif /// `SQLSpecificExpressible` is a protocol for all database-specific types that /// can be turned into an SQL expression. Types whose existence is not purely @@ -1699,9 +1689,9 @@ public protocol SQLSpecificExpressible: SQLExpressible, SQLSelectable, SQLOrderi // spill out. The three declarations below have no chance overloading a // Swift-defined operator, or a user-defined operator: // - // - ==(SQLExpressible, SQLSpecificExpressible) - // - ==(SQLSpecificExpressible, SQLExpressible) - // - ==(SQLSpecificExpressible, SQLSpecificExpressible) + // - ==(some SQLExpressible, some SQLSpecificExpressible) + // - ==(some SQLSpecificExpressible, some SQLExpressible) + // - ==(some SQLSpecificExpressible, some SQLSpecificExpressible) } extension SQLSpecificExpressible { @@ -1744,7 +1734,7 @@ extension Sequence where Element: SQLSpecificExpressible { } } -extension Sequence where Element == SQLSpecificExpressible { +extension Sequence { /// Returns an expression by joining all elements with an associative SQL /// binary operator. /// @@ -1858,7 +1848,7 @@ extension SQLSpecificExpressible { /// let height: Int /// let area: Int /// - /// static let databaseSelection: [SQLSelectable] = [ + /// static let databaseSelection: [any SQLSelectable] = [ /// Column(CodingKeys.width), /// Column(CodingKeys.height), /// (Column(CodingKeys.width) * Column(CodingKeys.height)).forKey(CodingKeys.area), @@ -1869,7 +1859,7 @@ extension SQLSpecificExpressible { /// let shapes: [Shape] = try Shape.fetchAll(db) /// /// See `forKey(_ key: String)` for more information. - public func forKey(_ key: CodingKey) -> SQLSelection { + public func forKey(_ key: some CodingKey) -> SQLSelection { forKey(key.stringValue) } } diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 55fc2d5c6..d5c94b195 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -4,7 +4,7 @@ /// /// // ABS(amount) /// abs(Column("amount")) -public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { +public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression { .function("ABS", [value.sqlExpression]) } @@ -15,7 +15,7 @@ public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { /// /// // AVG(length) /// average(Column("length")) -public func average(_ value: SQLSpecificExpressible) -> SQLExpression { +public func average(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("AVG", [value.sqlExpression]) } @@ -26,18 +26,7 @@ public func average(_ value: SQLSpecificExpressible) -> SQLExpression { /// /// // COUNT(email) /// count(Column("email")) -/// -/// :nodoc: -@available(*, deprecated) -public func count(_ counted: SQLSelectable) -> SQLExpression { - counted.sqlSelection.countExpression -} - -/// Returns an expression that evaluates the `COUNT` SQL function. -/// -/// // COUNT(email) -/// count(Column("email")) -public func count(_ counted: SQLSpecificExpressible) -> SQLExpression { +public func count(_ counted: some SQLSpecificExpressible) -> SQLExpression { .count(counted.sqlExpression) } @@ -48,7 +37,7 @@ public func count(_ counted: SQLSpecificExpressible) -> SQLExpression { /// /// // COUNT(DISTINCT email) /// count(distinct: Column("email")) -public func count(distinct value: SQLSpecificExpressible) -> SQLExpression { +public func count(distinct value: some SQLSpecificExpressible) -> SQLExpression { .countDistinct(value.sqlExpression) } @@ -59,7 +48,7 @@ public func count(distinct value: SQLSpecificExpressible) -> SQLExpression { /// /// // IFNULL(name, 'Anonymous') /// Column("name") ?? "Anonymous" -public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func ?? (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .function("IFNULL", [lhs.sqlExpression, rhs.sqlExpression]) } @@ -70,7 +59,7 @@ public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// /// // LENGTH(name) /// length(Column("name")) -public func length(_ value: SQLSpecificExpressible) -> SQLExpression { +public func length(_ value: some SQLSpecificExpressible) -> SQLExpression { .function("LENGTH", [value.sqlExpression]) } @@ -81,7 +70,7 @@ public func length(_ value: SQLSpecificExpressible) -> SQLExpression { /// /// // MAX(score) /// max(Column("score")) -public func max(_ value: SQLSpecificExpressible) -> SQLExpression { +public func max(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("MAX", [value.sqlExpression]) } @@ -92,7 +81,7 @@ public func max(_ value: SQLSpecificExpressible) -> SQLExpression { /// /// // MIN(score) /// min(Column("score")) -public func min(_ value: SQLSpecificExpressible) -> SQLExpression { +public func min(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("MIN", [value.sqlExpression]) } @@ -107,7 +96,7 @@ public func min(_ value: SQLSpecificExpressible) -> SQLExpression { /// /// // SUM(amount) /// sum(Column("amount")) -public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { +public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("SUM", [value.sqlExpression]) } @@ -122,7 +111,7 @@ public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { /// /// // TOTAL(amount) /// total(Column("amount")) -public func total(_ value: SQLSpecificExpressible) -> SQLExpression { +public func total(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("TOTAL", [value.sqlExpression]) } @@ -170,7 +159,6 @@ extension SQLSpecificExpressible { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.localizedCapitalized) /// let names = try String.fetchAll(dbQueue, request) // [String] - @available(OSX 10.11, watchOS 3.0, *) public var localizedCapitalized: SQLExpression { DatabaseFunction.localizedCapitalize(sqlExpression) } @@ -181,7 +169,6 @@ extension SQLSpecificExpressible { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.localizedLowercased) /// let names = try String.fetchAll(dbQueue, request) // [String] - @available(OSX 10.11, watchOS 3.0, *) public var localizedLowercased: SQLExpression { DatabaseFunction.localizedLowercase(sqlExpression) } @@ -192,7 +179,6 @@ extension SQLSpecificExpressible { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.localizedUppercased) /// let names = try String.fetchAll(dbQueue, request) // [String] - @available(OSX 10.11, watchOS 3.0, *) public var localizedUppercased: SQLExpression { DatabaseFunction.localizedUppercase(sqlExpression) } @@ -291,7 +277,7 @@ public enum SQLDateModifier: SQLSpecificExpressible { /// julianDay(Column("date"), .day(1)) /// /// For more information, see -public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { +public func julianDay(_ value: some SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { .function("JULIANDAY", [value.sqlExpression] + modifiers.map(\.sqlExpression)) } @@ -306,6 +292,6 @@ public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModif /// dateTime(Column("date"), .day(1)) /// /// For more information, see -public func dateTime(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { +public func dateTime(_ value: some SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { .function("DATETIME", [value.sqlExpression] + modifiers.map(\.sqlExpression)) } diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index 257cfc83e..af367909c 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -9,7 +9,7 @@ /// /// // name IS NULL /// Column("name") == nil -public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { +public func == (lhs: some SQLSpecificExpressible, rhs: (any SQLExpressible)?) -> SQLExpression { .equal(lhs.sqlExpression, rhs?.sqlExpression ?? .null) } @@ -22,7 +22,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpress /// /// // NOT validated /// Column("validated") == false -public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { +public func == (lhs: some SQLSpecificExpressible, rhs: Bool) -> SQLExpression { if rhs { return lhs.sqlExpression.is(.true) } else { @@ -39,7 +39,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { /// /// // name IS NULL /// nil == Column("name") -public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { +public func == (lhs: (any SQLExpressible)?, rhs: some SQLSpecificExpressible) -> SQLExpression { .equal(lhs?.sqlExpression ?? .null, rhs.sqlExpression) } @@ -52,7 +52,7 @@ public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpress /// /// // NOT validated /// false == Column("validated") -public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { +public func == (lhs: Bool, rhs: some SQLSpecificExpressible) -> SQLExpression { if lhs { return rhs.sqlExpression.is(.true) } else { @@ -64,7 +64,7 @@ public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { /// /// // email = login /// Column("email") == Column("login") -public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func == (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .equal(lhs.sqlExpression, rhs.sqlExpression) } @@ -77,7 +77,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// /// // name IS NOT NULL /// Column("name") != nil -public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { +public func != (lhs: some SQLSpecificExpressible, rhs: (any SQLExpressible)?) -> SQLExpression { !(lhs == rhs) } @@ -90,7 +90,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpress /// /// // validated /// Column("validated") != false -public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { +public func != (lhs: some SQLSpecificExpressible, rhs: Bool) -> SQLExpression { !(lhs == rhs) } @@ -103,7 +103,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { /// /// // name IS NOT NULL /// nil != Column("name") -public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { +public func != (lhs: (any SQLExpressible)?, rhs: some SQLSpecificExpressible) -> SQLExpression { !(lhs == rhs) } @@ -116,7 +116,7 @@ public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpress /// /// // validated /// false != Column("validated") -public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { +public func != (lhs: Bool, rhs: some SQLSpecificExpressible) -> SQLExpression { !(lhs == rhs) } @@ -124,7 +124,7 @@ public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { /// /// // email <> login /// Column("email") != Column("login") -public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func != (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { !(lhs == rhs) } @@ -132,7 +132,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// /// // name IS 'Arthur' /// Column("name") === "Arthur" -public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { +public func === (lhs: some SQLSpecificExpressible, rhs: (any SQLExpressible)?) -> SQLExpression { .compare(.is, lhs.sqlExpression, rhs?.sqlExpression ?? .null) } @@ -140,7 +140,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpres /// /// // name IS 'Arthur' /// "Arthur" === Column("name") -public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { +public func === (lhs: (any SQLExpressible)?, rhs: some SQLSpecificExpressible) -> SQLExpression { if let lhs = lhs { return .compare(.is, lhs.sqlExpression, rhs.sqlExpression) } else { @@ -152,7 +152,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres /// /// // email IS login /// Column("email") === Column("login") -public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func === (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .compare(.is, lhs.sqlExpression, rhs.sqlExpression) } @@ -160,7 +160,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ /// /// // name IS NOT 'Arthur' /// Column("name") !== "Arthur" -public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { +public func !== (lhs: some SQLSpecificExpressible, rhs: (any SQLExpressible)?) -> SQLExpression { !(lhs === rhs) } @@ -168,7 +168,7 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpres /// /// // name IS NOT 'Arthur' /// "Arthur" !== Column("name") -public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { +public func !== (lhs: (any SQLExpressible)?, rhs: some SQLSpecificExpressible) -> SQLExpression { !(lhs === rhs) } @@ -176,7 +176,7 @@ public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres /// /// // email IS NOT login /// Column("email") !== Column("login") -public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func !== (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { !(lhs === rhs) } @@ -186,7 +186,7 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ /// /// // score < 18 /// Column("score") < 18 -public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func < (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } @@ -194,7 +194,7 @@ public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// /// // 18 < score /// 18 < Column("score") -public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func < (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } @@ -202,7 +202,7 @@ public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// /// // width < height /// Column("width") < Column("height") -public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func < (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } @@ -210,7 +210,7 @@ public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// /// // score <= 18 /// Column("score") <= 18 -public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func <= (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } @@ -218,7 +218,7 @@ public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// /// // 18 <= score /// 18 <= Column("score") -public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func <= (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } @@ -226,7 +226,7 @@ public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// /// // width <= height /// Column("width") <= Column("height") -public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func <= (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } @@ -234,7 +234,7 @@ public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// /// // score > 18 /// Column("score") > 18 -public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func > (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } @@ -242,7 +242,7 @@ public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// /// // 18 > score /// 18 > Column("score") -public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func > (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } @@ -250,7 +250,7 @@ public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// /// // width > height /// Column("width") > Column("height") -public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func > (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } @@ -258,7 +258,7 @@ public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// /// // score >= 18 /// Column("score") >= 18 -public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func >= (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } @@ -266,7 +266,7 @@ public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// /// // 18 >= score /// 18 >= Column("score") -public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func >= (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } @@ -274,7 +274,7 @@ public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// /// // width >= height /// Column("width") >= Column("height") -public func >= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func >= (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } @@ -285,7 +285,7 @@ extension Range where Bound: SQLExpressible { /// /// // email >= 'A' AND email < 'B' /// ("A"..<"B").contains(Column("email")) - public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { (element >= lowerBound) && (element < upperBound) } } @@ -295,7 +295,7 @@ extension ClosedRange where Bound: SQLExpressible { /// /// // email BETWEEN 'A' AND 'B' /// ("A"..."B").contains(Column("email")) - public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { .between( expression: element.sqlExpression, lowerBound: lowerBound.sqlExpression, @@ -308,7 +308,7 @@ extension CountableRange where Bound: SQLExpressible { /// /// // id BETWEEN 1 AND 9 /// (1..<10).contains(Column("id")) - public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { (element >= lowerBound) && (element < upperBound) } } @@ -318,7 +318,7 @@ extension CountableClosedRange where Bound: SQLExpressible { /// /// // id BETWEEN 1 AND 10 /// (1...10).contains(Column("id")) - public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { .between( expression: element.sqlExpression, lowerBound: lowerBound.sqlExpression, @@ -326,24 +326,24 @@ extension CountableClosedRange where Bound: SQLExpressible { } } -extension Sequence where Self.Iterator.Element: SQLExpressible { +extension Sequence where Element: SQLExpressible { /// An SQL expression that checks the inclusion of an expression in /// a sequence. /// /// // id IN (1,2,3) /// [1, 2, 3].contains(Column("id")) - public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) } } -extension Sequence where Self.Iterator.Element == SQLExpressible { +extension Sequence { /// An SQL expression that checks the inclusion of an expression in /// a sequence. /// /// // id IN (1,2,3) /// [1, 2, 3].contains(Column("id")) - public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) } } @@ -355,7 +355,7 @@ extension Sequence where Self.Iterator.Element == SQLExpressible { /// /// // width * 2 /// Column("width") * 2 -public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func * (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -363,7 +363,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// /// // 2 * width /// 2 * Column("width") -public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func * (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -371,7 +371,7 @@ public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// /// // width * height /// Column("width") * Column("height") -public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func * (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -379,7 +379,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// /// // width / 2 /// Column("width") / 2 -public func / (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func / (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) } @@ -387,7 +387,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// /// // 2 / width /// 2 / Column("width") -public func / (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func / (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) } @@ -395,7 +395,7 @@ public func / (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// /// // width / height /// Column("width") / Column("height") -public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func / (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) } @@ -403,7 +403,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// /// // width + 2 /// Column("width") + 2 -public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func + (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -411,7 +411,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// /// // 2 + width /// 2 + Column("width") -public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func + (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -419,7 +419,7 @@ public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// /// // width + height /// Column("width") + Column("height") -public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func + (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -427,7 +427,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// /// // -width /// -Column("width") -public prefix func - (value: SQLSpecificExpressible) -> SQLExpression { +public prefix func - (value: some SQLSpecificExpressible) -> SQLExpression { .unary(.minus, value.sqlExpression) } @@ -435,7 +435,7 @@ public prefix func - (value: SQLSpecificExpressible) -> SQLExpression { /// /// // width - 2 /// Column("width") - 2 -public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func - (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } @@ -443,7 +443,7 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// /// // 2 - width /// 2 - Column("width") -public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func - (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } @@ -451,7 +451,7 @@ public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// /// // width - height /// Column("width") - Column("height") -public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func - (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } @@ -462,7 +462,7 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// /// // favorite AND 0 /// Column("favorite") && false -public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func && (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -470,7 +470,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// /// // 0 AND favorite /// false && Column("favorite") -public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func && (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -478,7 +478,7 @@ public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// /// // email IS NOT NULL AND favorite /// Column("email") != nil && Column("favorite") -public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func && (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -486,7 +486,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// /// // favorite OR 1 /// Column("favorite") || true -public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func || (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -494,7 +494,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// /// // 0 OR favorite /// true || Column("favorite") -public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func || (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -502,7 +502,7 @@ public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// /// // email IS NULL OR hidden /// Column("email") == nil || Column("hidden") -public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func || (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -515,14 +515,13 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// /// // id NOT BETWEEN 1 AND 10 /// !((1...10).contains(Column("id"))) -public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression { +public prefix func ! (value: some SQLSpecificExpressible) -> SQLExpression { value.sqlExpression.is(.falsey) } // MARK: - Like Operator extension SQLSpecificExpressible { - /// An SQL expression with the `LIKE` SQL operator. /// /// // email LIKE '%@example.com" @@ -530,7 +529,7 @@ extension SQLSpecificExpressible { /// /// // title LIKE '%10\%%' ESCAPE '\' /// Column("title").like("%10\\%%", escape: "\\") - public func like(_ pattern: SQLExpressible, escape: SQLExpressible? = nil) -> SQLExpression { + public func like(_ pattern: some SQLExpressible, escape: (any SQLExpressible)? = nil) -> SQLExpression { .escapableBinary(.like, sqlExpression, pattern.sqlExpression, escape: escape?.sqlExpression) } } diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index 6c4785ab9..c7d61e574 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -1,5 +1,9 @@ /// The type that can be used as an SQL ordering term, as described at /// +/// +/// It is illegal for `SQLOrdering` to represent several ordering terms: +/// +/// SQL("score DESC, name").sqlOrdering // illegal public struct SQLOrdering { private var impl: Impl diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 0bf05666d..f5dd75410 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -107,15 +107,23 @@ struct SQLRelation { var condition: SQLAssociationCondition var relation: SQLRelation - /// Returns true iff this child can change the parent count. + /// Returns whether this child can change the parent count. /// /// Record.including(required: association) // true /// Record.including(all: association) // false var impactsParentCount: Bool { switch kind { - case .oneOptional, .oneRequired: + case .oneRequired: + // INNER JOIN can clearly reduce the number of rows + return true + case .oneOptional: + // LEFT JOIN does not itself reduce the number of rows, but + // maybe the joined table is used somewhere in the relation, in + // a way that can reduce the number of rows. return true case .all, .bridge: + // HasMany associations are prefetched in another SQL request: + // they have no impact on this relation. return false } } @@ -893,7 +901,7 @@ extension JoinMapping { fatalError("Provide at least one left row, or this method can't generate SQL that can be observed.") } - let mappings: [(leftIndex: Rows.Element.ColumnIndex, rightColumn: Column)] = map { mapping in + let mappings = map { mapping in guard let leftIndex = firstLeftRow.index(forColumn: mapping.left) else { fatalError("Missing column: \(mapping.left)") } diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index cd6655582..d546e9682 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -1,5 +1,8 @@ /// The type that can be selected, as described at /// +/// +/// It is legal for `SQLSelection` to represent several columns. The most basic +/// example of such a multi-column selection is the SQL `*`. public struct SQLSelection { private var impl: Impl @@ -74,25 +77,6 @@ extension SQLSelection { } } - /// TODO: remove when `count(_ counted: SQLSelectable)` is removed. - var countExpression: SQLExpression { - switch impl { - case .allColumns: - return .countAll - - case .qualifiedAllColumns: - // COUNT(player.*) is not valid SQL - fatalError("Uncountable selection") - - case let .expression(expression), - let .aliasedExpression(expression, _): - return .count(expression) - - case let .literal(sqlLiteral): - return .count(sqlLiteral.sqlExpression) - } - } - /// If the selection can be counted, return how to count it. func count(distinct: Bool) -> SQLCount? { switch impl { @@ -250,7 +234,7 @@ extension SQLSelection { } } -extension Array where Element == SQLSelection { +extension [SQLSelection] { /// Returns the number of columns in the selection. /// /// This method raises a fatal error if the selection contains a literal, @@ -307,7 +291,7 @@ extension SQLSelection: SQLSelectable { /// /// struct Player : TableRecord { /// static var databaseTableName = "player" -/// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] +/// static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] /// } /// /// // SELECT *, rowid FROM player diff --git a/GRDB/QueryInterface/SQL/SQLSubquery.swift b/GRDB/QueryInterface/SQL/SQLSubquery.swift index f7d91a98a..093b1812d 100644 --- a/GRDB/QueryInterface/SQL/SQLSubquery.swift +++ b/GRDB/QueryInterface/SQL/SQLSubquery.swift @@ -110,7 +110,7 @@ extension SQLSubqueryable { /// // 1000 IN (SELECT score FROM player) /// let request = Player.select(Column("score"), as: Int.self) /// let condition = request.contains(1000) - public func contains(_ element: SQLExpressible) -> SQLExpression { + public func contains(_ element: some SQLExpressible) -> SQLExpression { SQLCollection.subquery(sqlSubquery).contains(element.sqlExpression) } diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index b17dcdfd4..b4b0b5518 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -35,7 +35,7 @@ extension Table where RowDecoder == Row { extension Table: DatabaseRegionConvertible { public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - DatabaseRegion.fullTable(tableName) + DatabaseRegion(table: tableName) } } @@ -71,7 +71,7 @@ extension Table { /// // SELECT id, email FROM player /// let table = Table("player") /// let request = table.select(Column("id"), Column("email")) - public func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { + public func select(_ selection: any SQLSelectable...) -> QueryInterfaceRequest { all().select(selection) } @@ -80,7 +80,7 @@ extension Table { /// // SELECT id, email FROM player /// let table = Table("player") /// let request = table.select([Column("id"), Column("email")]) - public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { + public func select(_ selection: [any SQLSelectable]) -> QueryInterfaceRequest { all().select(selection) } @@ -122,7 +122,7 @@ extension Table { /// let maxScore: Int? = try request.fetchOne(db) /// } public func select( - _ selection: [SQLSelectable], + _ selection: [any SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { @@ -139,7 +139,7 @@ extension Table { /// let maxScore: Int? = try request.fetchOne(db) /// } public func select( - _ selection: SQLSelectable..., + _ selection: any SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { @@ -192,7 +192,7 @@ extension Table { /// let request = table /// .select([Column("id"), Column("email")]) /// .annotated(with: [Column("name")]) - public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { + public func annotated(with selection: [any SQLSelectable]) -> QueryInterfaceRequest { all().annotated(with: selection) } @@ -203,7 +203,7 @@ extension Table { /// let request = table /// .select([Column("id"), Column("email")]) /// .annotated(with: Column("name")) - public func annotated(with selection: SQLSelectable...) -> QueryInterfaceRequest { + public func annotated(with selection: any SQLSelectable...) -> QueryInterfaceRequest { all().annotated(with: selection) } @@ -212,7 +212,7 @@ extension Table { /// // 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 { + public func filter(_ predicate: some SQLSpecificExpressible) -> QueryInterfaceRequest { all().filter(predicate) } @@ -221,10 +221,7 @@ extension Table { /// // 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 - { + public func filter(key: some DatabaseValueConvertible) -> QueryInterfaceRequest { all().filter(key: key) } @@ -233,9 +230,8 @@ extension Table { /// // 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) + public func filter(keys: some Sequence) -> QueryInterfaceRequest - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { all().filter(keys: keys) } @@ -248,7 +244,7 @@ extension Table { /// /// 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 { + public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> QueryInterfaceRequest { all().filter(key: key) } @@ -260,7 +256,7 @@ extension Table { /// /// 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 { + public func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> QueryInterfaceRequest { all().filter(keys: keys) } @@ -297,7 +293,7 @@ extension Table { /// // SELECT * FROM player ORDER BY name /// let table = Table("player") /// let request = table.order(Column("name")) - public func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { + public func order(_ orderings: any SQLOrderingTerm...) -> QueryInterfaceRequest { all().order(orderings) } @@ -307,7 +303,7 @@ extension Table { /// // SELECT * FROM player ORDER BY name /// let table = Table("player") /// let request = table.order([Column("name")]) - public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { + public func order(_ orderings: [any SQLOrderingTerm]) -> QueryInterfaceRequest { all().order(orderings) } @@ -394,61 +390,31 @@ extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConv /// 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 - { + public func filter(ids: some Collection) -> QueryInterfaceRequest { 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) - } - +extension Table { /// Creates a request which selects the primary key. /// + /// All primary keys are supported: + /// /// // SELECT id FROM player /// let table = Table("player") - /// let request = try table.selectID() - public func selectID() -> QueryInterfaceRequest { - all().selectID() + /// let request = try table.selectPrimaryKey(as: Int64.self) + /// + /// // SELECT code FROM country + /// let table = Table("country") + /// let request = try table.selectPrimaryKey(as: String.self) + /// + /// // SELECT citizenId, countryCode FROM citizenship + /// let table = Table("citizenship") + /// let request = try table.selectPrimaryKey(as: Row.self) + public func selectPrimaryKey(as type: PrimaryKey.Type = PrimaryKey.self) + -> QueryInterfaceRequest + { + all().selectPrimaryKey(as: type) } } @@ -657,72 +623,6 @@ extension Table where RowDecoder: DatabaseValueConvertible & Hashable { } } -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 { @@ -788,78 +688,6 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv } } -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 { @@ -1042,7 +870,7 @@ extension Table { /// - returns: An association to the common table expression. public func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( @@ -1092,8 +920,7 @@ extension Table { Pivot.OriginRowDecoder == RowDecoder, Pivot.RowDecoder == Target.OriginRowDecoder { - let association = HasManyThroughAssociation( - _sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + let association = HasManyThroughAssociation(through: pivot, using: target) if let key = key { return association.forKey(key) @@ -1125,8 +952,7 @@ extension Table { Pivot.OriginRowDecoder == RowDecoder, Pivot.RowDecoder == Target.OriginRowDecoder { - let association = HasOneThroughAssociation( - _sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + let association = HasOneThroughAssociation(through: pivot, using: target) if let key = key { return association.forKey(key) @@ -1313,7 +1139,7 @@ extension Table { // MARK: - Batch Delete extension Table { - /// Deletes all rows; returns the number of deleted rows. + /// Deletes all rows, and returns the number of deleted rows. /// /// - parameter db: A database connection. /// - returns: The number of deleted rows @@ -1341,10 +1167,7 @@ extension Table { /// - db: A database connection. /// - key: A primary key value. /// - returns: Whether a row exists for this primary key. - public func exists(_ db: Database, key: PrimaryKeyType) - throws -> Bool - where PrimaryKeyType: DatabaseValueConvertible - { + public func exists(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { try !filter(key: key).isEmpty(db) } } @@ -1369,32 +1192,11 @@ where RowDecoder: Identifiable, /// - id: A primary key value. /// - returns: Whether a row exists for this primary key. public func exists(_ db: Database, id: RowDecoder.ID) throws -> Bool { - try !filter(id: id).isEmpty(db) - } -} - -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) -extension Table -where RowDecoder: Identifiable, - RowDecoder.ID: _OptionalProtocol, - RowDecoder.ID.Wrapped: DatabaseValueConvertible -{ - /// Returns whether a row exists for this primary key. - /// - /// try Table("player").exists(db, id: 123) - /// try Table("country").exists(db, id: "FR") - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// try Table("document").exists(db, id: 1) - /// - /// - parameters: - /// - db: A database connection. - /// - id: A primary key value. - /// - returns: Whether a row exists for this primary key. - public func exists(_ db: Database, id: RowDecoder.ID.Wrapped) throws -> Bool { - try !filter(id: id).isEmpty(db) + if id.databaseValue.isNull { + // Don't hit the database + return false + } + return try !filter(id: id).isEmpty(db) } } @@ -1410,7 +1212,7 @@ extension Table { /// - db: A database connection. /// - key: A dictionary of values. /// - returns: Whether a row exists for this key. - public func exists(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + public func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try !filter(key: key).isEmpty(db) } } @@ -1418,7 +1220,7 @@ extension Table { // MARK: - Deleting by Single-Column Primary Key extension Table { - /// Delete rows identified by their primary keys; returns the number of + /// Delete rows identified by their primary keys, and returns the number of /// deleted rows. /// /// // DELETE FROM player WHERE id IN (1, 2, 3) @@ -1438,9 +1240,8 @@ extension Table { /// - keys: A sequence of primary keys. /// - returns: The number of deleted rows @discardableResult - public func deleteAll(_ db: Database, keys: Sequence) + public func deleteAll(_ db: Database, keys: some Sequence) throws -> Int - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { @@ -1450,7 +1251,7 @@ extension Table { return try filter(keys: keys).deleteAll(db) } - /// Delete a row, identified by its primary key; returns whether a + /// Delete a row, identified by its primary key, and returns whether a /// database row was deleted. /// /// // DELETE FROM player WHERE id = 123 @@ -1470,12 +1271,9 @@ extension Table { /// - 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 + public func deleteOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { + if key.databaseValue.isNull { + // Don't hit the database return false } return try deleteAll(db, keys: [key]) > 0 @@ -1487,7 +1285,7 @@ extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { - /// Delete rows identified by their primary keys; returns the number of + /// Delete rows identified by their primary keys, and returns the number of /// deleted rows. /// /// // DELETE FROM player WHERE id IN (1, 2, 3) @@ -1507,10 +1305,7 @@ where RowDecoder: Identifiable, /// - 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 - { + public func deleteAll(_ db: Database, ids: some Collection) throws -> Int { if ids.isEmpty { // Avoid hitting the database return 0 @@ -1518,7 +1313,7 @@ where RowDecoder: Identifiable, return try filter(ids: ids).deleteAll(db) } - /// Delete a row, identified by its primary key; returns whether a + /// Delete a row, identified by its primary key, and returns whether a /// database row was deleted. /// /// // DELETE FROM player WHERE id = 123 @@ -1539,69 +1334,11 @@ where RowDecoder: Identifiable, /// - 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 + if id.databaseValue.isNull { + // Don't hit the database + return false } - 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 + return try deleteAll(db, ids: [id]) > 0 } } @@ -1609,7 +1346,8 @@ where RowDecoder: Identifiable, 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. + /// any key with a unique index on it), and returns the number of + /// deleted rows. /// /// try Table("player").deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) /// @@ -1618,7 +1356,7 @@ extension Table { /// - keys: An array of key dictionaries. /// - returns: The number of deleted rows @discardableResult - public func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int { + public func deleteAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Int { if keys.isEmpty { // Avoid hitting the database return 0 @@ -1627,7 +1365,8 @@ extension Table { } /// 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. + /// with a unique index on it), and returns whether a database row + /// was deleted. /// /// Table("player").deleteOne(db, key: ["name": Arthur"]) /// @@ -1636,7 +1375,7 @@ extension Table { /// - key: A dictionary of values. /// - returns: Whether a database row was deleted. @discardableResult - public func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + public func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try deleteAll(db, keys: [key]) > 0 } } @@ -1644,7 +1383,7 @@ extension Table { // MARK: - Batch Update extension Table { - /// Updates all rows; returns the number of updated rows. + /// Updates all rows, and returns the number of updated rows.. /// /// For example: /// @@ -1668,7 +1407,7 @@ extension Table { try all().updateAll(db, onConflict: conflictResolution, assignments) } - /// Updates all rows; returns the number of updated rows. + /// Updates all rows, and returns the number of updated rows.. /// /// For example: /// @@ -1679,18 +1418,16 @@ extension Table { /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. - /// - parameter assignment: A column assignment. - /// - parameter otherAssignments: Eventual other column assignments. + /// - parameter assignments: 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...) + _ assignments: ColumnAssignment...) throws -> Int { - try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments) + try updateAll(db, onConflict: conflictResolution, assignments) } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 633a4edea..81edac4d0 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -88,7 +88,27 @@ final class SQLGenerationContext { /// Returns whether arguments could be appended. /// /// A false result means that the generation context does not support - /// SQL arguments. + /// SQL arguments, and `?` placeholders are not supported. + /// This happens, for example, when we are creating tables: + /// + /// // CREATE TABLE player ( + /// // name TEXT DEFAULT 'Anonymous' -- String literal instead of ? + /// // ) + /// let defaultName = "Anonymous" + /// try db.create(table: "player") { t in + /// t.column(literal: "name TEXT DEFAULT \(defaultName)") + /// } + /// + /// A false result is turned into a fatal error when the user uses + /// SQL arguments at unsupported locations: + /// + /// // Fatal error: + /// // Not implemented: turning an SQL parameter into an SQL literal value + /// let defaultName = "Anonymous" + /// let literal = SQL(sql: "name TEXT DEFAULT ?", arguments: [defaultName]) + /// try db.create(table: "player") { t in + /// t.column(literal: literal) + /// } func append(arguments: StatementArguments) -> Bool { argumentsSink.append(arguments: arguments) } @@ -399,23 +419,23 @@ public class TableAlias: Hashable { /// Returns a qualified value that is able to resolve ambiguities in /// joined queries. - public subscript(_ selectable: SQLSelectable) -> SQLSelection { + public subscript(_ selectable: some SQLSelectable) -> SQLSelection { selectable.sqlSelection.qualified(with: self) } /// Returns a qualified expression that is able to resolve ambiguities in /// joined queries. - public subscript(_ expression: SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression { + public subscript(_ expression: some SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression { expression.sqlExpression.qualified(with: self) } /// Returns a qualified ordering that is able to resolve ambiguities in /// joined queries. - public subscript(_ ordering: SQLOrderingTerm) -> SQLOrdering { + public subscript(_ ordering: some SQLOrderingTerm) -> SQLOrdering { ordering.sqlOrdering.qualified(with: self) } - /// Returns a qualified columnn that is able to resolve ambiguities in + /// Returns a qualified column that is able to resolve ambiguities in /// joined queries. public subscript(_ column: String) -> SQLExpression { .qualifiedColumn(column, self) @@ -451,7 +471,7 @@ public class TableAlias: Hashable { } } -extension Array where Element == TableAlias { +extension [TableAlias] { /// Resolve ambiguities in aliases' names. fileprivate var resolvedNames: [TableAlias: String] { // It is a programmer error to reuse the same TableAlias for diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index dbe6271c0..1455793e8 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -145,23 +145,31 @@ struct SQLQueryGenerator: Refinable { return statement } + /// Returns an optimized database region, when possible. + /// + /// The optimized region allows us to track individual rowids, and also + /// discard some provably empty requests such as `Player.none()`. private func optimizedSelectedRegion(_ db: Database, _ selectedRegion: DatabaseRegion) throws -> DatabaseRegion { - // Can we intersect the region with rowIds? - // - // Give up unless request feeds from a single database table + var optimizedRegion = selectedRegion + + // Give up unless request feeds from a database table let tableName = relation.source.tableName guard try db.tableExists(tableName) else { // skip views - return selectedRegion + return optimizedRegion } - // The filter knows better - guard let filter = try relation.filterPromise?.resolve(db), - let rowIDs = try filter.identifyingRowIDs(db, for: relation.source.alias) - else { - return selectedRegion + // If the request is filtered on rowIds, we can optimize the region: + // + // - Player.filter(Column("id") == 1) // region "player(*)[1]" + // - Player.filter(ids: [1, 2, 3]) // region "player(*)[1, 2, 3]" + // - Player.none() // region "empty" + if let filter = try relation.filterPromise?.resolve(db), + let rowIDs = try filter.identifyingRowIDs(db, for: relation.source.alias) + { + optimizedRegion = optimizedRegion.tableIntersection(tableName, rowIds: rowIDs) } - return selectedRegion.tableIntersection(tableName, rowIds: rowIDs) + return optimizedRegion } /// If true, executing this query yields at most one row. @@ -197,11 +205,13 @@ struct SQLQueryGenerator: Refinable { return false } - func makeDeleteStatement(_ db: Database) throws -> Statement { + /// Returns a `DELETE` statement, with `RETURNING` clause if `selection` + /// is not empty. + func makeDeleteStatement(_ db: Database, selection: [any SQLSelectable] = []) throws -> Statement { switch try grouping(db) { case .none: guard relation.joins.isEmpty else { - return try makeTrivialDeleteStatement(db) + return try makeTrivialDeleteStatement(db, selection: selection) } let context = SQLGenerationContext(db, aliases: relation.allAliases, ctes: relation.ctes) @@ -225,12 +235,10 @@ struct SQLQueryGenerator: Refinable { sql += " LIMIT " + limit.sql } - let statement = try db.makeStatement(sql: sql) - statement.arguments = context.arguments - return statement + return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection) case .unique: - return try makeTrivialDeleteStatement(db) + return try makeTrivialDeleteStatement(db, selection: selection) case .nonUnique: // Programmer error @@ -239,7 +247,8 @@ struct SQLQueryGenerator: Refinable { } /// DELETE FROM table WHERE id IN (SELECT id FROM table ...) - private func makeTrivialDeleteStatement(_ db: Database) throws -> Statement { + /// DELETE FROM table WHERE id IN (SELECT id FROM table ...) RETURNING ... + private func makeTrivialDeleteStatement(_ db: Database, selection: [any SQLSelectable]) throws -> Statement { let tableName = relation.source.tableName let alias = TableAlias(tableName: tableName) let context = SQLGenerationContext(db, aliases: [alias]) @@ -255,16 +264,18 @@ struct SQLQueryGenerator: Refinable { sql += try selectPrimaryKey.requestSQL(subqueryContext) sql += ")" - let statement = try db.makeStatement(sql: sql) - statement.arguments = context.arguments - return statement + return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection) } - /// Returns nil if assignments is empty + /// Returns an `UPDATE` statement, with `RETURNING` clause if `selection` + /// is not empty. + /// + /// Returns nil if assignments is empty. func makeUpdateStatement( _ db: Database, conflictResolution: Database.ConflictResolution, - assignments: [ColumnAssignment]) + assignments: [ColumnAssignment], + selection: [any SQLSelectable] = []) throws -> Statement? { switch try grouping(db) { @@ -273,7 +284,8 @@ struct SQLQueryGenerator: Refinable { return try makeTrivialUpdateStatement( db, conflictResolution: conflictResolution, - assignments: assignments) + assignments: assignments, + selection: selection) } // Check for empty assignments after all programmer errors have @@ -314,12 +326,14 @@ struct SQLQueryGenerator: Refinable { sql += " LIMIT " + limit.sql } - let statement = try db.makeStatement(sql: sql) - statement.arguments = context.arguments - return statement + return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection) case .unique: - return try makeTrivialUpdateStatement(db, conflictResolution: conflictResolution, assignments: assignments) + return try makeTrivialUpdateStatement( + db, + conflictResolution: conflictResolution, + assignments: assignments, + selection: selection) case .nonUnique: // Programmer error @@ -328,11 +342,13 @@ struct SQLQueryGenerator: Refinable { } /// UPDATE table SET ... WHERE id IN (SELECT id FROM table ...) + /// UPDATE table SET ... WHERE id IN (SELECT id FROM table ...) RETURNING ... /// Returns nil if assignments is empty private func makeTrivialUpdateStatement( _ db: Database, conflictResolution: Database.ConflictResolution, - assignments: [ColumnAssignment]) + assignments: [ColumnAssignment], + selection: [any SQLSelectable]) throws -> Statement? { // Check for empty assignments after all programmer errors have @@ -370,9 +386,34 @@ struct SQLQueryGenerator: Refinable { sql += try selectPrimaryKey.requestSQL(subqueryContext) sql += ")" - let statement = try db.makeStatement(sql: sql) - statement.arguments = context.arguments - return statement + return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection) + } + + // Support for the RETURNING clause + private func makeStatement( + _ db: Database, + sql: String, + arguments: StatementArguments, + returning selection: [any SQLSelectable]) + throws -> Statement + { + if selection.isEmpty { + let statement = try db.makeStatement(sql: sql) + statement.arguments = arguments + return statement + } else { + let context = SQLGenerationContext(db) + var sql = sql + var arguments = arguments + sql += " RETURNING " + sql += try selection + .map { try $0.sqlSelection.sql(context) } + .joined(separator: ", ") + arguments += context.arguments + let statement = try db.makeStatement(sql: sql) + statement.arguments = arguments + return statement + } } private func commonTableExpressionsPrefix(_ context: SQLGenerationContext) throws -> String { @@ -458,7 +499,7 @@ struct SQLQueryGenerator: Refinable { /// let request = Book.all() /// for row in try Row.fetchAll(db, request) { /// row // [id:1, title:"Moby-Dick"] - /// let book = Book(row: row) + /// let book = try Book(row: row) /// } /// /// But as soon as the selection includes columns of a included relation, @@ -468,12 +509,12 @@ struct SQLQueryGenerator: Refinable { /// let request = Book.including(required: Book.author) /// for row in try Row.fetchAll(db, request) { /// row // [id:1, title:"Moby-Dick"] - /// let book = Book(row: row) + /// let book = try Book(row: row) /// /// row.scopes["author"] // [id:12, name:"Herman Melville"] /// let author: Author = row["author"] /// } - private func rowAdapter(_ context: SQLGenerationContext) throws -> RowAdapter? { + private func rowAdapter(_ context: SQLGenerationContext) throws -> (any RowAdapter)? { try relation.rowAdapter(context, fromIndex: 0, rootRelation: true)?.adapter } } @@ -605,7 +646,7 @@ private struct SQLQualifiedRelation { _ context: SQLGenerationContext, fromIndex startIndex: Int, rootRelation: Bool) throws - -> (adapter: RowAdapter, endIndex: Int)? + -> (adapter: any RowAdapter, endIndex: Int)? { // Root relation && no join => no need for any adapter if rootRelation && joins.isEmpty { @@ -619,7 +660,7 @@ private struct SQLQualifiedRelation { // Recursively build adapters for each joined relation with a selection. // Name them according to the join keys. var endIndex = startIndex + sourceSelectionWidth - var scopes: [String: RowAdapter] = [:] + var scopes: [String: any RowAdapter] = [:] for (key, join) in joins { if let (joinAdapter, joinEndIndex) = try join .relation @@ -644,7 +685,7 @@ private struct SQLQualifiedRelation { // The RangeRowAdapter hides the columns appended by joined relations: // // row // [id:1, title:"Moby-Dick"] - // let book = Book(row: row) + // let book = try Book(row: row) // // Scopes give access to those joined relations: // diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index a8334fb76..a68dda642 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -7,9 +7,7 @@ extension SQLInterpolation { /// /// // SELECT * FROM player /// let request: SQLRequest = "SELECT * FROM \(Player.self)" - public mutating func appendInterpolation(_ table: T.Type) - where T: TableRecord - { + public mutating func appendInterpolation(_ table: (some TableRecord).Type) { appendLiteral(table.databaseTableName.quotedDatabaseIdentifier) } @@ -18,7 +16,7 @@ extension SQLInterpolation { /// // SELECT * FROM player /// let request: SQLRequest = "SELECT * FROM \(Player.self)" @_disfavoredOverload - public mutating func appendInterpolation(_ table: TableRecord.Type) { + public mutating func appendInterpolation(_ table: any TableRecord.Type) { appendLiteral(table.databaseTableName.quotedDatabaseIdentifier) } @@ -27,9 +25,7 @@ extension SQLInterpolation { /// // INSERT INTO player ... /// let player: Player = ... /// let request: SQLRequest = "INSERT INTO \(tableOf: player) ..." - public mutating func appendInterpolation(tableOf record: T) - where T: TableRecord - { + public mutating func appendInterpolation(tableOf record: some TableRecord) { appendInterpolation(type(of: record)) } @@ -39,7 +35,7 @@ extension SQLInterpolation { /// let player: Player = ... /// let request: SQLRequest = "INSERT INTO \(tableOf: player) ..." @_disfavoredOverload - public mutating func appendInterpolation(tableOf record: TableRecord) { + public mutating func appendInterpolation(tableOf record: any TableRecord) { appendInterpolation(type(of: record)) } @@ -52,11 +48,9 @@ extension SQLInterpolation { /// // SELECT p.* FROM player p /// let player: Player = ... /// let request: SQLRequest = "SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p" - public mutating func appendInterpolation(columnsOf record: T.Type, tableAlias: String? = nil) - where T: TableRecord - { - let alias = TableAlias(name: tableAlias ?? T.databaseTableName) - elements.append(contentsOf: T.databaseSelection + public mutating func appendInterpolation(columnsOf recordType: (some TableRecord).Type, tableAlias: String? = nil) { + let alias = TableAlias(name: tableAlias ?? recordType.databaseTableName) + elements.append(contentsOf: recordType.databaseSelection .map { CollectionOfOne(.selection($0.sqlSelection.qualified(with: alias))) } .joined(separator: CollectionOfOne(.sql(", ")))) } @@ -69,9 +63,7 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT \(AllColumns()) FROM player /// """ - public mutating func appendInterpolation(_ selection: T) - where T: SQLSelectable - { + public mutating func appendInterpolation(_ selection: some SQLSelectable) { elements.append(.selection(selection.sqlSelection)) } @@ -82,7 +74,7 @@ extension SQLInterpolation { /// SELECT \(AllColumns()) FROM player /// """ @_disfavoredOverload - public mutating func appendInterpolation(_ selection: SQLSelectable?) { + public mutating func appendInterpolation(_ selection: (any SQLSelectable)?) { if let selection = selection { elements.append(.selection(selection.sqlSelection)) } else { @@ -98,9 +90,7 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT * FROM player ORDER BY \(Column("name").desc) /// """ - public mutating func appendInterpolation(_ orderingTerm: T) - where T: SQLOrderingTerm - { + public mutating func appendInterpolation(_ orderingTerm: some SQLOrderingTerm) { elements.append(.ordering(orderingTerm.sqlOrdering)) } @@ -111,7 +101,7 @@ extension SQLInterpolation { /// SELECT * FROM player ORDER BY \(Column("name").desc) /// """ @_disfavoredOverload - public mutating func appendInterpolation(_ orderingTerm: SQLOrderingTerm) { + public mutating func appendInterpolation(_ orderingTerm: any SQLOrderingTerm) { elements.append(.ordering(orderingTerm.sqlOrdering)) } @@ -123,8 +113,9 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT \(Column("name")) FROM player /// """ - public mutating func appendInterpolation(_ expressible: T) - where T: SQLExpressible & SQLSelectable & SQLOrderingTerm + public mutating func appendInterpolation(_ expressible: some SQLExpressible + & SQLSelectable + & SQLOrderingTerm) { elements.append(.expression(expressible.sqlExpression)) } @@ -136,7 +127,7 @@ extension SQLInterpolation { /// SELECT \(Column("name")) FROM player /// """ @_disfavoredOverload - public mutating func appendInterpolation(_ expressible: SQLExpressible?) { + public mutating func appendInterpolation(_ expressible: (any SQLExpressible)?) { if let expressible = expressible { elements.append(.expression(expressible.sqlExpression)) } else { @@ -152,9 +143,7 @@ extension SQLInterpolation { /// let request: SQLRequest = " /// SELECT \(CodingKey.name) FROM player /// """ - public mutating func appendInterpolation(_ key: T) - where T: CodingKey - { + public mutating func appendInterpolation(_ key: some CodingKey) { appendInterpolation(Column(key.stringValue)) } @@ -164,8 +153,10 @@ extension SQLInterpolation { /// let request: SQLRequest = " /// SELECT \(CodingKey.name) FROM player /// """ - public mutating func appendInterpolation(_ key: T) - where T: CodingKey & SQLExpressible & SQLSelectable & SQLOrderingTerm + public mutating func appendInterpolation(_ key: some CodingKey + & SQLExpressible + & SQLSelectable + & SQLOrderingTerm) { appendInterpolation(Column(key.stringValue)) } @@ -177,7 +168,7 @@ extension SQLInterpolation { /// SELECT \(CodingKey.name) FROM player /// """ @_disfavoredOverload - public mutating func appendInterpolation(_ key: CodingKey) { + public mutating func appendInterpolation(_ key: any CodingKey) { appendInterpolation(Column(key.stringValue)) } @@ -193,8 +184,10 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT * FROM player WHERE score = (\(subquery)) /// """ - public mutating func appendInterpolation(_ subquery: T) - where T: SQLSubqueryable & SQLExpressible & SQLSelectable & SQLOrderingTerm + public mutating func appendInterpolation(_ subquery: some SQLSubqueryable + & SQLExpressible + & SQLSelectable + & SQLOrderingTerm) { elements.append(.subquery(subquery.sqlSubquery)) } @@ -216,9 +209,7 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT * FROM player WHERE id IN \(ids) /// """ - public mutating func appendInterpolation(_ sequence: T) - where T: Sequence, T.Element: SQLExpressible - { + public mutating func appendInterpolation(_ sequence: some Sequence) { let e: [SQL.Element] = sequence.map { .expression($0.sqlExpression) } if e.isEmpty { appendLiteral("(SELECT NULL WHERE NULL)") @@ -244,18 +235,14 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT * FROM player WHERE a IN \(expressions) /// """ - public mutating func appendInterpolation(_ sequence: T) - where T: Sequence, T.Element == SQLExpressible - { + public mutating func appendInterpolation(_ sequence: some Sequence){ appendInterpolation(sequence.lazy.map(\.sqlExpression)) } // When a value is both an expression and a sequence of expressions, // favor the expression side. Use case: Foundation.Data interpolation. /// :nodoc: - public mutating func appendInterpolation(_ expressible: T) - where T: Sequence, T: SQLExpressible, T.Element: SQLExpressible - { + public mutating func appendInterpolation(_ expressible: some SQLExpressible & Sequence) { elements.append(.expression(expressible.sqlExpression)) } @@ -268,7 +255,7 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// WITH \(definitionFor: cte) SELECT * FROM \(cte) /// """ - public mutating func appendInterpolation(_ cte: CommonTableExpression) { + public mutating func appendInterpolation(_ cte: CommonTableExpression) { elements.append(.sql(cte.tableName.quotedDatabaseIdentifier)) } @@ -279,7 +266,7 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// WITH \(definitionFor: cte) SELECT * FROM \(cte) /// """ - public mutating func appendInterpolation(definitionFor cte: CommonTableExpression) { + public mutating func appendInterpolation(definitionFor cte: CommonTableExpression) { elements.append(.sql(cte.tableName.quotedDatabaseIdentifier)) if let columns = cte.cte.columns, !columns.isEmpty { diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 820d45278..d09e3183b 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -144,7 +144,7 @@ extension Database { columns: [String], unique: Bool = false, ifNotExists: Bool = false, - condition: SQLExpressible? = nil) + condition: (any SQLExpressible)? = nil) throws { var options: IndexOptions = [] @@ -177,7 +177,7 @@ extension Database { on table: String, columns: [String], options: IndexOptions = [], - condition: SQLExpressible? = nil) + condition: (any SQLExpressible)? = nil) throws { let definition = IndexDefinition( @@ -477,7 +477,7 @@ public final class TableDefinition { /// See /// /// - parameter condition: The checked condition - public func check(_ condition: SQLExpressible) { + public func check(_ condition: some SQLExpressible) { checkConstraints.append(condition.sqlExpression) } @@ -789,7 +789,7 @@ public final class TableAlteration { /// See /// /// - Parameter name: the column name to drop. - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func drop(column name: String) { _drop(column: name) } @@ -1003,7 +1003,7 @@ public final class ColumnDefinition { /// represents the defined column, and returns the expression to check. /// - returns: Self so that you can further refine the column definition. @discardableResult - public func check(_ condition: (Column) -> SQLExpressible) -> Self { + public func check(_ condition: (Column) -> any SQLExpressible) -> Self { checkConstraints.append(condition(Column(name)).sqlExpression) return self } @@ -1035,7 +1035,7 @@ public final class ColumnDefinition { /// - parameter value: A DatabaseValueConvertible value. /// - returns: Self so that you can further refine the column definition. @discardableResult - public func defaults(to value: DatabaseValueConvertible) -> Self { + public func defaults(to value: some DatabaseValueConvertible) -> Self { defaultExpression = value.sqlExpression return self } @@ -1138,7 +1138,7 @@ public final class ColumnDefinition { /// - returns: Self so that you can further refine the column definition. @discardableResult public func generatedAs( - _ expression: SQLExpressible, + _ expression: some SQLExpressible, _ qualification: GeneratedColumnQualification = .virtual) -> Self { diff --git a/GRDB/QueryInterface/Schema/VirtualTableModule.swift b/GRDB/QueryInterface/Schema/VirtualTableModule.swift index cb6c53f90..3b34dc29d 100644 --- a/GRDB/QueryInterface/Schema/VirtualTableModule.swift +++ b/GRDB/QueryInterface/Schema/VirtualTableModule.swift @@ -21,18 +21,6 @@ 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: /// @@ -49,14 +37,6 @@ 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.) diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 98b49fa7d..189ac2034 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -336,7 +336,7 @@ extension TableRecord { /// - returns: An association to the common table expression. public static func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( @@ -435,8 +435,7 @@ extension TableRecord { Pivot.OriginRowDecoder == Self, Pivot.RowDecoder == Target.OriginRowDecoder { - let association = HasManyThroughAssociation( - _sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + let association = HasManyThroughAssociation(through: pivot, using: target) if let key = key { return association.forKey(key) @@ -517,8 +516,7 @@ extension TableRecord { Pivot.OriginRowDecoder == Self, Pivot.RowDecoder == Target.OriginRowDecoder { - let association = HasOneThroughAssociation( - _sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + let association = HasOneThroughAssociation(through: pivot, using: target) if let key = key { return association.forKey(key) diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 78ce4f920..35b5c1d55 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -23,7 +23,7 @@ extension TableRecord { /// /// // SELECT id, email FROM player /// let request = Player.select(Column("id"), Column("email")) - public static func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { + public static func select(_ selection: any SQLSelectable...) -> QueryInterfaceRequest { all().select(selection) } @@ -31,7 +31,7 @@ extension TableRecord { /// /// // SELECT id, email FROM player /// let request = Player.select([Column("id"), Column("email")]) - public static func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { + public static func select(_ selection: [any SQLSelectable]) -> QueryInterfaceRequest { all().select(selection) } @@ -70,7 +70,7 @@ extension TableRecord { /// let maxScore: Int? = try request.fetchOne(db) /// } public static func select( - _ selection: [SQLSelectable], + _ selection: [any SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { @@ -86,7 +86,7 @@ extension TableRecord { /// let maxScore: Int? = try request.fetchOne(db) /// } public static func select( - _ selection: SQLSelectable..., + _ selection: any SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { @@ -130,13 +130,31 @@ extension TableRecord { all().select(sqlLiteral, as: type) } + /// Creates a request which selects the primary key. + /// + /// All primary keys are supported: + /// + /// // SELECT id FROM player + /// let request = try Player.selectPrimaryKey(as: Int64.self) + /// + /// // SELECT code FROM country + /// let request = try Country.selectPrimaryKey(as: String.self) + /// + /// // SELECT citizenId, countryCode FROM citizenship + /// let request = try Citizenship.selectPrimaryKey(as: Row.self) + public static func selectPrimaryKey(as type: PrimaryKey.Type = PrimaryKey.self) + -> QueryInterfaceRequest + { + all().selectPrimaryKey(as: type) + } + /// Creates a request which appends *selection*. /// /// // SELECT id, email, name FROM player /// let request = Player /// .select([Column("id"), Column("email")]) /// .annotated(with: [Column("name")]) - public static func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { + public static func annotated(with selection: [any SQLSelectable]) -> QueryInterfaceRequest { all().annotated(with: selection) } @@ -146,19 +164,10 @@ extension TableRecord { /// let request = Player /// .select([Column("id"), Column("email")]) /// .annotated(with: Column("name")) - public static func annotated(with selection: SQLSelectable...) -> QueryInterfaceRequest { + public static func annotated(with selection: any SQLSelectable...) -> QueryInterfaceRequest { all().annotated(with: selection) } - /// Creates a request with the provided *predicate*. - /// - /// // SELECT * FROM player WHERE email = 'arthur@example.com' - /// let request = Player.filter(Column("email") == "arthur@example.com") - @available(*, deprecated, message: "Did you mean filter(id:) or filter(key:)? If not, prefer filter(value.databaseValue) instead. See also none().") // swiftlint:disable:this line_length - public static func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest { - all().filter(predicate.sqlExpression) - } - // Accept SQLSpecificExpressible instead of SQLExpressible, so that we // prevent the `Player.filter(42)` misuse. // See https://github.com/groue/GRDB.swift/pull/864 @@ -166,7 +175,7 @@ extension TableRecord { /// /// // SELECT * FROM player WHERE email = 'arthur@example.com' /// let request = Player.filter(Column("email") == "arthur@example.com") - public static func filter(_ predicate: SQLSpecificExpressible) -> QueryInterfaceRequest { + public static func filter(_ predicate: some SQLSpecificExpressible) -> QueryInterfaceRequest { all().filter(predicate) } @@ -174,10 +183,7 @@ extension TableRecord { /// /// // SELECT * FROM player WHERE id = 1 /// let request = Player.filter(key: 1) - public static func filter(key: PrimaryKeyType?) - -> QueryInterfaceRequest - where PrimaryKeyType: DatabaseValueConvertible - { + public static func filter(key: some DatabaseValueConvertible) -> QueryInterfaceRequest { all().filter(key: key) } @@ -185,9 +191,8 @@ extension TableRecord { /// /// // SELECT * FROM player WHERE id IN (1, 2, 3) /// let request = Player.filter(keys: [1, 2, 3]) - public static func filter(keys: Sequence) + public static func filter(keys: some Sequence) -> QueryInterfaceRequest - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { all().filter(keys: keys) } @@ -199,7 +204,7 @@ extension TableRecord { /// /// When executed, this request raises a fatal error if there is no unique /// index on the key columns. - public static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { + public static func filter(key: [String: (any DatabaseValueConvertible)?]?) -> QueryInterfaceRequest { all().filter(key: key) } @@ -210,7 +215,7 @@ extension TableRecord { /// /// When executed, this request raises a fatal error if there is no unique /// index on the key columns. - public static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { + public static func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> QueryInterfaceRequest { all().filter(keys: keys) } @@ -245,7 +250,7 @@ extension TableRecord { /// /// // SELECT * FROM player ORDER BY name /// let request = Player.order(Column("name")) - public static func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { + public static func order(_ orderings: any SQLOrderingTerm...) -> QueryInterfaceRequest { all().order(orderings) } @@ -254,7 +259,7 @@ extension TableRecord { /// /// // SELECT * FROM player ORDER BY name /// let request = Player.order([Column("name")]) - public static func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { + public static func order(_ orderings: [any SQLOrderingTerm]) -> QueryInterfaceRequest { all().order(orderings) } @@ -374,52 +379,7 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// let request = Player.filter(ids: [1, 2, 3]) /// /// - parameter ids: A collection of primary keys - public static func filter(ids: Collection) - -> QueryInterfaceRequest - where Collection: Swift.Collection, Collection.Element == ID - { + public static func filter(ids: some Collection) -> QueryInterfaceRequest { 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, *) -extension TableRecord where Self: Identifiable, ID: _OptionalProtocol, ID.Wrapped: DatabaseValueConvertible { - /// Creates a request filtered by primary key. - /// - /// // SELECT * FROM player WHERE id = 1 - /// let request = Player.filter(id: 1) - /// - /// - parameter id: A primary key - public static func filter(id: ID.Wrapped) -> QueryInterfaceRequest { - all().filter(id: id) - } - - /// Creates a request filtered by primary key. - /// - /// // SELECT * FROM player WHERE id IN (1, 2, 3) - /// let request = Player.filter(ids: [1, 2, 3]) - /// - /// - parameter ids: A collection of primary keys - public static func filter(ids: Collection) - -> QueryInterfaceRequest - where Collection: Swift.Collection, Collection.Element == ID.Wrapped - { - 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 06c1e133c..a73d7bdf1 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -1,9 +1,9 @@ import Foundation extension EncodableRecord where Self: Encodable { - public func encode(to container: inout PersistenceContainer) { + public func encode(to container: inout PersistenceContainer) throws { let encoder = RecordEncoder(persistenceContainer: container) - try! encode(to: encoder) + try encode(to: encoder) container = encoder.persistenceContainer } } @@ -12,7 +12,7 @@ extension EncodableRecord where Self: Encodable { /// The encoder that encodes a record into GRDB's PersistenceContainer private class RecordEncoder: Encoder { - var codingPath: [CodingKey] { [] } + var codingPath: [any CodingKey] { [] } var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } private var _persistenceContainer: PersistenceContainer var persistenceContainer: PersistenceContainer { _persistenceContainer } @@ -49,7 +49,7 @@ private class RecordEncoder: Encoder { private struct KeyedContainer: KeyedEncodingContainerProtocol { var recordEncoder: RecordEncoder var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } - var codingPath: [CodingKey] { [] } + var codingPath: [any CodingKey] { [] } // swiftlint:disable comma func encode(_ value: Bool, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } @@ -121,16 +121,16 @@ private class RecordEncoder: Encoder { } /// Helper methods - fileprivate func persist(_ value: DatabaseValueConvertible?, forKey key: CodingKey) { + fileprivate func persist(_ value: (any DatabaseValueConvertible)?, forKey key: any CodingKey) { _persistenceContainer[keyEncodingStrategy.column(forKey: key)] = value } - fileprivate func encode(_ value: T, forKey key: CodingKey) throws where T: Encodable { + fileprivate func encode(_ value: T, forKey key: any CodingKey) throws where T: Encodable { if let date = value as? Date { persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key) } else if let uuid = value as? UUID { persist(Record.databaseUUIDEncodingStrategy.encode(uuid), forKey: key) - } else if let value = value as? DatabaseValueConvertible { + } else if let value = value as? any DatabaseValueConvertible { // Prefer DatabaseValueConvertible encoding over Decodable. persist(value.databaseValue, forKey: key) } else { @@ -170,12 +170,12 @@ private class RecordEncoder: Encoder { /// The encoder that encodes into a database column private class ColumnEncoder: Encoder { var recordEncoder: RecordEncoder - var key: CodingKey - var codingPath: [CodingKey] { [key] } + var key: any CodingKey + var codingPath: [any CodingKey] { [key] } var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } var requiresJSON = false - init(recordEncoder: RecordEncoder, key: CodingKey) { + init(recordEncoder: RecordEncoder, key: some CodingKey) { self.recordEncoder = recordEncoder self.key = key } diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 1a02fe384..72c2d6784 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -22,7 +22,10 @@ public protocol EncodableRecord { /// It is undefined behavior to set different values for the same column. /// Column names are case insensitive, so defining both "name" and "NAME" /// is considered undefined behavior. - func encode(to container: inout PersistenceContainer) + /// + /// - throws: An error is thrown if the record can't be encoded to its + /// database representation. + func encode(to container: inout PersistenceContainer) throws // MARK: - Customizing the Format of Database Columns @@ -67,7 +70,7 @@ public protocol EncodableRecord { /// - dataEncodingStrategy: .base64 /// - dateEncodingStrategy: .millisecondsSince1970 /// - nonConformingFloatEncodingStrategy: .throw - /// - outputFormatting: .sortedKeys (iOS 11.0+, macOS 10.13+, tvOS 11.0+, watchOS 4.0+) + /// - outputFormatting: .sortedKeys /// /// You can override those defaults: /// @@ -144,10 +147,8 @@ extension EncodableRecord { 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 record comparison - encoder.outputFormatting = .sortedKeys - } + // guarantee some stability in order to ease record comparison + encoder.outputFormatting = .sortedKeys encoder.userInfo = databaseEncodingUserInfo return encoder } @@ -167,8 +168,13 @@ extension EncodableRecord { extension EncodableRecord { /// A dictionary whose keys are the columns encoded in the `encode(to:)` method. + /// + /// - throws: An error is thrown if the record can't be encoded to its + /// database representation. public var databaseDictionary: [String: DatabaseValue] { - Dictionary(PersistenceContainer(self).storage).mapValues { $0?.databaseValue ?? .null } + get throws { + try Dictionary(PersistenceContainer(self).storage).mapValues { $0?.databaseValue ?? .null } + } } } @@ -179,7 +185,12 @@ extension EncodableRecord { /// Returns a boolean indicating whether this record and the other record /// have the same database representation. public func databaseEquals(_ record: Self) -> Bool { - PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)).next() == nil + do { + return try PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)).next() == nil + } catch { + // one record can't be encoded: they can't be identical in the database + return false + } } /// A dictionary of values changed from the other record. @@ -190,8 +201,13 @@ extension EncodableRecord { /// but also in terms of columns. When the two records don't define the /// same set of columns in their `encode(to:)` method, only the columns /// defined by the receiver record are considered. - public func databaseChanges(from record: Record) -> [String: DatabaseValue] { - let changes = PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)) + /// + /// - throws: An error is thrown if one record can't be encoded to its + /// database representation. + public func databaseChanges(from record: Record) + throws -> [String: DatabaseValue] + { + let changes = try PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)) return Dictionary(uniqueKeysWithValues: changes) } } @@ -214,15 +230,15 @@ public struct PersistenceContainer { // fileprivate for Row(_:PersistenceContainer) // The ordering of the OrderedDictionary helps generating always the same // SQL queries, and hit the statement cache. - fileprivate var storage: OrderedDictionary + fileprivate var storage: OrderedDictionary /// Accesses the value associated with the given column. /// /// It is undefined behavior to set different values for the same column. /// Column names are case insensitive, so defining both "name" and "NAME" /// is considered undefined behavior. - public subscript(_ column: String) -> DatabaseValueConvertible? { - get { storage[column] ?? nil } + public subscript(_ column: String) -> (any DatabaseValueConvertible)? { + get { self[caseInsensitive: column] } set { storage.updateValue(newValue, forKey: column) } } @@ -231,7 +247,7 @@ public struct PersistenceContainer { /// It is undefined behavior to set different values for the same column. /// Column names are case insensitive, so defining both "name" and "NAME" /// is considered undefined behavior. - public subscript(_ column: Column) -> DatabaseValueConvertible? { + public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? { get { self[column.name] } set { self[column.name] = newValue } } @@ -245,22 +261,31 @@ public struct PersistenceContainer { } /// Convenience initializer from a record - init(_ record: Record) { + init(_ record: Record) throws { self.init() - record.encode(to: &self) + try record.encode(to: &self) + } + + /// Convenience initializer from a database connection and a record + @usableFromInline + init(_ db: Database, _ record: some EncodableRecord & TableRecord) throws { + let databaseTableName = type(of: record).databaseTableName + let columnCount = try db.columns(in: databaseTableName).count + self.init(minimumCapacity: columnCount) // Optimization + try record.encode(to: &self) } /// Columns stored in the container, ordered like values. var columns: [String] { Array(storage.keys) } /// Values stored in the container, ordered like columns. - var values: [DatabaseValueConvertible?] { Array(storage.values) } + var values: [(any DatabaseValueConvertible)?] { Array(storage.values) } /// Accesses the value associated with the given column, in a /// case-insensitive fashion. /// /// :nodoc: - subscript(caseInsensitive column: String) -> DatabaseValueConvertible? { + subscript(caseInsensitive column: String) -> (any DatabaseValueConvertible)? { get { if let value = storage[column] { return value @@ -298,10 +323,11 @@ public struct PersistenceContainer { var isEmpty: Bool { storage.isEmpty } /// An iterator over the (column, value) pairs - func makeIterator() -> IndexingIterator> { + func makeIterator() -> IndexingIterator> { storage.makeIterator() } + @usableFromInline func changesIterator(from container: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> { var newValueIterator = makeIterator() return AnyIterator { @@ -320,8 +346,8 @@ public struct PersistenceContainer { } extension Row { - convenience init(_ record: Record) { - self.init(PersistenceContainer(record)) + convenience init(_ record: Record) throws { + try self.init(PersistenceContainer(record)) } convenience init(_ container: PersistenceContainer) { @@ -366,44 +392,38 @@ public enum DatabaseDateEncodingStrategy { case millisecondsSince1970 /// Encodes dates according to the ISO 8601 and RFC 3339 standards - @available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Encodes a String, according to the provided formatter case formatted(DateFormatter) /// Encodes the result of the user-provided function - case custom((Date) -> DatabaseValueConvertible?) + case custom((Date) -> (any DatabaseValueConvertible)?) - @available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private static let iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter }() - func encode(_ date: Date) -> DatabaseValueConvertible? { + func encode(_ date: Date) -> DatabaseValue { switch self { case .deferredToDate: return date.databaseValue case .timeIntervalSinceReferenceDate: - return date.timeIntervalSinceReferenceDate + return date.timeIntervalSinceReferenceDate.databaseValue case .timeIntervalSince1970: - return date.timeIntervalSince1970 + return date.timeIntervalSince1970.databaseValue case .millisecondsSince1970: - return Int64(floor(1000.0 * date.timeIntervalSince1970)) + return Int64(floor(1000.0 * date.timeIntervalSince1970)).databaseValue case .secondsSince1970: - return Int64(floor(date.timeIntervalSince1970)) + return Int64(floor(date.timeIntervalSince1970)).databaseValue case .iso8601: - if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { - return Self.iso8601Formatter.string(from: date) - } else { - fatalError("ISO8601DateFormatter is unavailable on this platform.") - } + return Self.iso8601Formatter.string(from: date).databaseValue case .formatted(let formatter): - return formatter.string(from: date) + return formatter.string(from: date).databaseValue case .custom(let format): - return format(date) + return format(date)?.databaseValue ?? .null } } } @@ -433,18 +453,14 @@ public enum DatabaseUUIDEncodingStrategy { /// Encodes UUIDs as lowercased strings such as "e621e1f8-c36c-495a-93fc-0c247a3e6e5f" case lowercaseString - /// Encodes UUIDs as uppercased strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" - @available(*, deprecated, renamed: "uppercaseString") - public static var string: Self { .uppercaseString } - - func encode(_ uuid: UUID) -> DatabaseValueConvertible { + func encode(_ uuid: UUID) -> DatabaseValue { switch self { case .deferredToUUID: return uuid.databaseValue case .uppercaseString: - return uuid.uuidString + return uuid.uuidString.databaseValue case .lowercaseString: - return uuid.uuidString.lowercased() + return uuid.uuidString.lowercased().databaseValue } } } @@ -471,9 +487,9 @@ public enum DatabaseColumnEncodingStrategy { case convertToSnakeCase /// A key encoding strategy defined by the closure you supply. - case custom((CodingKey) -> String) + case custom((any CodingKey) -> String) - func column(forKey key: CodingKey) -> String { + func column(forKey key: some CodingKey) -> String { switch self { case .useDefaultKeys: return key.stringValue diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 1932faf37..9be222aec 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -1,10 +1,8 @@ import Foundation extension FetchableRecord where Self: Decodable { - public init(row: Row) { - // Intended force-try. FetchableRecord is designed for records that - // reliably decode from rows. - self = try! RowDecoder().decode(from: row) + public init(row: Row) throws { + self = try RowDecoder().decode(from: row) } } @@ -150,7 +148,7 @@ private struct _RowDecoder: Decoder { // swiftlint:enable comma private func decodeColumn(forKey key: Key) throws -> String { - guard let _columnForKey = _columnForKey else { + guard let _columnForKey else { return key.stringValue } @@ -208,9 +206,9 @@ private struct _RowDecoder: Decoder { return try R.databaseDateDecodingStrategy.decodeIfPresent( fromRow: row, atUncheckedIndex: index) as! T? - } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { + } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { return try type.fastDecodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T? - } else if let type = T.self as? DatabaseValueConvertible.Type { + } else if let type = T.self as? any DatabaseValueConvertible.Type { return try type.decodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T? } else if row.impl.hasNull(atUncheckedIndex: index) { return nil @@ -251,9 +249,9 @@ private struct _RowDecoder: Decoder { // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T - } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { + } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { return try type.fastDecode(fromRow: row, atUncheckedIndex: index) as! T - } else if let type = T.self as? DatabaseValueConvertible.Type { + } else if let type = T.self as? any DatabaseValueConvertible.Type { return try type.decode(fromRow: row, atUncheckedIndex: index) as! T } else { return try decode(type, fromRow: row, columnAtIndex: index, key: key) @@ -340,9 +338,9 @@ private struct _RowDecoder: Decoder { throws -> T where T: Decodable { - if let type = T.self as? FetchableRecord.Type { + if let type = T.self as? any FetchableRecord.Type { // Prefer FetchableRecord decoding over Decodable. - return type.init(row: row) as! T + return try type.init(row: row) as! T } else { let decoder = _RowDecoder(row: row, codingPath: codingPath, columnDecodingStrategy: .useDefaultKeys) return try T(from: decoder) @@ -414,7 +412,7 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { defer { currentIndex += 1 } let columnDecodingStrategy: DatabaseColumnDecodingStrategy - if let type = T.self as? FetchableRecord.Type { + if let type = T.self as? any FetchableRecord.Type { columnDecodingStrategy = type.databaseColumnDecodingStrategy } else { columnDecodingStrategy = .useDefaultKeys @@ -490,9 +488,9 @@ extension ColumnDecoder: SingleValueDecodingContainer { // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T - } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { + } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { return try type.fastDecode(fromRow: row, atUncheckedIndex: columnIndex) as! T - } else if let type = T.self as? DatabaseValueConvertible.Type { + } else if let type = T.self as? any DatabaseValueConvertible.Type { return try type.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T } else { return try T(from: self) @@ -500,7 +498,6 @@ extension ColumnDecoder: SingleValueDecodingContainer { } } -@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private let iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime @@ -512,7 +509,7 @@ extension DatabaseDateDecodingStrategy { if let sqliteStatement = row.sqliteStatement { return try decodeIfPresent( fromStatement: sqliteStatement, - atUncheckedIndex: Int32(index), + atUncheckedIndex: CInt(index), context: RowDecodingContext(row: row, key: .columnIndex(index))) } else { return try decodeIfPresent( @@ -525,7 +522,7 @@ extension DatabaseDateDecodingStrategy { if let sqliteStatement = row.sqliteStatement { return try decode( fromStatement: sqliteStatement, - atUncheckedIndex: Int32(index), + atUncheckedIndex: CInt(index), context: RowDecodingContext(row: row, key: .columnIndex(index))) } else { return try decode( @@ -534,12 +531,14 @@ extension DatabaseDateDecodingStrategy { } } + /// - precondition: value is not NULL fileprivate func decode( fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, + atUncheckedIndex index: CInt, context: @autoclosure () -> RowDecodingContext) throws -> Date { + assert(sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL, "unexpected NULL value") switch self { case .deferredToDate: guard let date = Date(sqliteStatement: sqliteStatement, index: index) else { @@ -559,18 +558,14 @@ extension DatabaseDateDecodingStrategy { let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) return Date(timeIntervalSince1970: timeInterval / 1000.0) case .iso8601: - if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { - let string = String(sqliteStatement: sqliteStatement, index: index) - guard let date = iso8601Formatter.date(from: string) else { - throw RowDecodingError.valueMismatch( - Date.self, - context: context(), - databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) - } - return date - } else { - fatalError("ISO8601DateFormatter is unavailable on this platform.") + let string = String(sqliteStatement: sqliteStatement, index: index) + guard let date = iso8601Formatter.date(from: string) else { + throw RowDecodingError.valueMismatch( + Date.self, + context: context(), + databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) } + return date case .formatted(let formatter): let string = String(sqliteStatement: sqliteStatement, index: index) guard let date = formatter.date(from: string) else { @@ -594,7 +589,7 @@ extension DatabaseDateDecodingStrategy { fileprivate func decodeIfPresent( fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, + atUncheckedIndex index: CInt, context: @autoclosure () -> RowDecodingContext) throws -> Date? { @@ -648,13 +643,9 @@ extension DatabaseDateDecodingStrategy { .fromDatabaseValue(dbValue) .map { Date(timeIntervalSince1970: $0 / 1000.0) } case .iso8601: - if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { - return String - .fromDatabaseValue(dbValue) - .flatMap { iso8601Formatter.date(from: $0) } - } else { - fatalError("ISO8601DateFormatter is unavailable on this platform.") - } + return String + .fromDatabaseValue(dbValue) + .flatMap { iso8601Formatter.date(from: $0) } case .formatted(let formatter): return String .fromDatabaseValue(dbValue) diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index 1dae5ad2d..2799a2592 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -94,9 +94,8 @@ extension FetchableRecord where Self: TableRecord { /// - keys: A sequence of primary keys. /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, keys: Sequence) + public static func fetchCursor(_ db: Database, keys: some Sequence) throws -> RecordCursor - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { try filter(keys: keys).fetchCursor(db) } @@ -112,9 +111,8 @@ extension FetchableRecord where Self: TableRecord { /// - keys: A sequence of primary keys. /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, keys: Sequence) + public static func fetchAll(_ db: Database, keys: some Sequence) throws -> [Self] - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { @@ -133,12 +131,9 @@ extension FetchableRecord where Self: TableRecord { /// - key: A primary key value. /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, key: PrimaryKeyType?) - throws -> Self? - where PrimaryKeyType: DatabaseValueConvertible - { - guard let key = key else { - // Avoid hitting the database + public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? { + if key.databaseValue.isNull { + // Don't hit the database return nil } return try filter(key: key).fetchOne(db) @@ -164,9 +159,8 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa /// - ids: A collection of primary keys. /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, ids: Collection) + public static func fetchCursor(_ db: Database, ids: some Collection) throws -> RecordCursor - where Collection: Swift.Collection, Collection.Element == ID { try filter(ids: ids).fetchCursor(db) } @@ -182,10 +176,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa /// - ids: A collection of primary keys. /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, ids: Collection) - throws -> [Self] - where Collection: Swift.Collection, Collection.Element == ID - { + public static func fetchAll(_ db: Database, ids: some Collection) throws -> [Self] { if ids.isEmpty { // Avoid hitting the database return [] @@ -207,72 +198,6 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) -extension FetchableRecord -where Self: TableRecord & Identifiable, - ID: _OptionalProtocol, - ID.Wrapped: DatabaseValueConvertible -{ - - // MARK: Fetching by Single-Column Primary Key - - /// Returns a cursor over records, given their primary keys. - /// - /// let players = try Player.fetchCursor(db, ids: [1, 2, 3]) // Cursor of Player - /// while let player = try players.next() { // Player - /// ... - /// } - /// - /// Records are iterated in unspecified order. - /// - /// - parameters: - /// - db: A database connection. - /// - ids: A collection of primary keys. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, ids: Collection) - throws -> RecordCursor - where Collection: Swift.Collection, Collection.Element == ID.Wrapped - { - try filter(ids: ids).fetchCursor(db) - } - - /// Returns an array of records, given their primary keys. - /// - /// let players = try Player.fetchAll(db, ids: [1, 2, 3]) // [Player] - /// - /// The order of records in the returned array is undefined. - /// - /// - parameters: - /// - db: A database connection. - /// - ids: A collection of primary keys. - /// - returns: An array of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, ids: Collection) - throws -> [Self] - where Collection: Swift.Collection, Collection.Element == ID.Wrapped - { - if ids.isEmpty { - // Avoid hitting the database - return [] - } - return try filter(ids: ids).fetchAll(db) - } - - /// Returns a single record given its primary key. - /// - /// let player = try Player.fetchOne(db, id: 123) // Player? - /// - /// - parameters: - /// - db: A database connection. - /// - id: A primary key value. - /// - returns: An optional record. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, id: ID.Wrapped) throws -> Self? { - try filter(id: id).fetchOne(db) - } -} - extension FetchableRecord where Self: TableRecord & Hashable { /// Returns a set of records, given their primary keys. /// @@ -283,9 +208,8 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// - keys: A sequence of primary keys. /// - returns: A set of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, keys: Sequence) + public static func fetchSet(_ db: Database, keys: some Sequence) throws -> Set - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { @@ -307,37 +231,7 @@ extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID: /// - ids: A collection of primary keys. /// - returns: A set of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, ids: Collection) - throws -> Set - where Collection: Swift.Collection, Collection.Element == ID - { - if ids.isEmpty { - // Avoid hitting the database - return [] - } - return try filter(ids: ids).fetchSet(db) - } -} - -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) -extension FetchableRecord -where Self: TableRecord & Hashable & Identifiable, - ID: _OptionalProtocol, - ID.Wrapped: DatabaseValueConvertible -{ - /// Returns a set of records, given their primary keys. - /// - /// let players = try Player.fetchSet(db, ids: [1, 2, 3]) // Set - /// - /// - parameters: - /// - db: A database connection. - /// - ids: A collection of primary keys. - /// - returns: A set of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, ids: Collection) - throws -> Set - where Collection: Swift.Collection, Collection.Element == ID.Wrapped - { + public static func fetchSet(_ db: Database, ids: some Collection) throws -> Set { if ids.isEmpty { // Avoid hitting the database return [] @@ -368,7 +262,7 @@ extension FetchableRecord where Self: TableRecord { /// - keys: An array of key dictionaries. /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) + public static func fetchCursor(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> RecordCursor { try filter(keys: keys).fetchCursor(db) @@ -389,7 +283,7 @@ extension FetchableRecord where Self: TableRecord { /// - keys: An array of key dictionaries. /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> [Self] { + public static func fetchAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> [Self] { if keys.isEmpty { // Avoid hitting the database return [] @@ -407,8 +301,8 @@ extension FetchableRecord where Self: TableRecord { /// - key: A dictionary of values. /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self? { - guard let key = key else { + public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? { + guard let key else { // Avoid hitting the database return nil } @@ -430,7 +324,7 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// - keys: An array of key dictionaries. /// - returns: A set of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Set { + public static func fetchSet(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Set { if keys.isEmpty { // Avoid hitting the database return [] diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index ee520c196..422da1bf3 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -25,7 +25,7 @@ public protocol FetchableRecord { /// For performance reasons, the row argument may be 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()`. - init(row: Row) + init(row: Row) throws // MARK: - Customizing the Format of Database Columns @@ -173,7 +173,7 @@ extension FetchableRecord { public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> RecordCursor { try RecordCursor(statement: statement, arguments: arguments, adapter: adapter) @@ -193,7 +193,7 @@ extension FetchableRecord { public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Self] { try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) @@ -213,7 +213,7 @@ extension FetchableRecord { public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Self? { try fetchCursor(statement, arguments: arguments, adapter: adapter).next() @@ -235,7 +235,7 @@ extension FetchableRecord where Self: Hashable { public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) @@ -269,7 +269,7 @@ extension FetchableRecord { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> RecordCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -290,7 +290,7 @@ extension FetchableRecord { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Self] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -311,7 +311,7 @@ extension FetchableRecord { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Self? { try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -334,7 +334,7 @@ extension FetchableRecord where Self: Hashable { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -384,7 +384,7 @@ extension FetchableRecord { if let supplementaryFetch = request.supplementaryFetch { let rows = try Row.fetchAll(request.statement, adapter: request.adapter) try supplementaryFetch(db, rows) - return rows.map(Self.init(row:)) + return try rows.map(Self.init(row:)) } else { return try fetchAll(request.statement, adapter: request.adapter) } @@ -407,7 +407,7 @@ extension FetchableRecord { return nil } try supplementaryFetch(db, [row]) - return .init(row: row) + return try .init(row: row) } else { return try fetchOne(request.statement, adapter: request.adapter) } @@ -430,7 +430,7 @@ extension FetchableRecord where Self: Hashable { if let supplementaryFetch = request.supplementaryFetch { let rows = try Row.fetchAll(request.statement, adapter: request.adapter) try supplementaryFetch(db, rows) - return Set(rows.lazy.map(Self.init(row:))) + return try Set(rows.lazy.map(Self.init(row:))) } else { return try fetchSet(request.statement, adapter: request.adapter) } @@ -446,7 +446,8 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// A cursor over fetched records. /// - /// let request: ... // Some FetchRequest that fetches Player + /// struct Player: FetchableRecord { ... } + /// let request: some FetchRequest = ... /// let players = try request.fetchCursor(db) // Cursor of Player /// while let player = try players.next() { // Player /// ... @@ -466,7 +467,8 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// An array of fetched records. /// - /// let request: ... // Some FetchRequest that fetches Player + /// struct Player: FetchableRecord { ... } + /// let request: some FetchRequest = ... /// let players = try request.fetchAll(db) // [Player] /// /// - parameter db: A database connection. @@ -478,7 +480,8 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// The first fetched record. /// - /// let request: ... // Some FetchRequest that fetches Player + /// struct Player: FetchableRecord { ... } + /// let request: some FetchRequest = ... /// let player = try request.fetchOne(db) // Player? /// /// - parameter db: A database connection. @@ -492,7 +495,8 @@ extension FetchRequest where RowDecoder: FetchableRecord { extension FetchRequest where RowDecoder: FetchableRecord & Hashable { /// A set of fetched records. /// - /// let request: ... // Some FetchRequest that fetches Player + /// struct Player: FetchableRecord, Hashable { ... } + /// let request: some FetchRequest = ... /// let players = try request.fetchSet(db) // Set /// /// - parameter db: A database connection. @@ -513,13 +517,14 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable { /// } public final class RecordCursor: DatabaseCursor { public typealias Element = Record - public let statement: Statement + /// :nodoc: + public let _statement: Statement /// :nodoc: public var _isDone = false - private let row: Row // Instanciated once, reused for performance + private let row: Row // Instantiated once, reused for performance - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - self.statement = statement + init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { + self._statement = statement row = try Row(statement: statement).adapted(with: adapter, layout: statement) try statement.reset(withArguments: arguments) } @@ -527,12 +532,12 @@ public final class RecordCursor: DatabaseCursor { deinit { // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. - try? statement.reset() + try? _statement.reset() } /// :nodoc: - public func _element(sqliteStatement: SQLiteStatement) -> Record { - Record(row: row) + public func _element(sqliteStatement: SQLiteStatement) throws -> Record { + try Record(row: row) } } @@ -581,7 +586,6 @@ public enum DatabaseDateDecodingStrategy { case millisecondsSince1970 /// Decodes dates according to the ISO 8601 standards - @available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Decodes a String, according to the provided formatter diff --git a/GRDB/Record/MutablePersistableRecord+DAO.swift b/GRDB/Record/MutablePersistableRecord+DAO.swift new file mode 100644 index 000000000..e86a0fdd1 --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord+DAO.swift @@ -0,0 +1,347 @@ +/// DAO takes care of MutablePersistableRecord CRUD +final class DAO { + /// The database + let db: Database + + /// DAO keeps a copy the record's persistenceContainer, so that this + /// dictionary is built once whatever the database operation. It is + /// guaranteed to have at least one (key, value) pair. + let persistenceContainer: PersistenceContainer + + /// The table name + let databaseTableName: String + + /// The table primary key info + let primaryKey: PrimaryKeyInfo + + init(_ db: Database, _ record: Record) throws { + self.db = db + databaseTableName = type(of: record).databaseTableName + primaryKey = try db.primaryKey(databaseTableName) + persistenceContainer = try PersistenceContainer(db, record) + GRDBPrecondition(!persistenceContainer.isEmpty, "\(type(of: record)): invalid empty persistence container") + } + + func insertStatement( + _ db: Database, + onConflict: Database.ConflictResolution, + returning selection: [any SQLSelectable]) + throws -> Statement + { + let query = InsertQuery( + onConflict: onConflict, + tableName: databaseTableName, + insertedColumns: persistenceContainer.columns) + + return try makeStatement( + sql: query.sql, + checkedArguments: StatementArguments(persistenceContainer.values), + returning: selection) + } + + func upsertStatement( + _ db: Database, + conflictTarget conflictTargetColumns: [String], + returning selection: [any SQLSelectable]) + throws -> Statement + { + // Don't update columns not present in the persistenceContainer + // Don't update columns not present in conflictTargetColumns + // Don't update primary key columns + let lowercaseUpdatedColumns = Set(persistenceContainer.columns.map { $0.lowercased() }) + .subtracting(primaryKey.columns.map { $0.lowercased() }) + .subtracting(conflictTargetColumns.map { $0.lowercased() }) + + var updatedColumns: [String] = [] + var arguments = StatementArguments(persistenceContainer.values) + for column in persistenceContainer.columns { + if lowercaseUpdatedColumns.contains(column.lowercased()) { + updatedColumns.append(column) + arguments += [persistenceContainer.databaseValue(at: column)] + } + } + + let query = UpsertQuery( + tableName: databaseTableName, + insertedColumns: persistenceContainer.columns, + conflictTargetColumns: conflictTargetColumns, + updatedColumns: updatedColumns) + + return try makeStatement( + sql: query.sql, + checkedArguments: arguments, + returning: selection) + } + + /// Returns nil if and only if primary key is nil + func updateStatement( + columns: Set, + onConflict: Database.ConflictResolution, + returning selection: [any SQLSelectable]) + throws -> Statement? + { + // Fail early if primary key does not resolve to a database row. + let primaryKeyColumns = primaryKey.columns + let primaryKeyValues = primaryKeyColumns.map { + persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null + } + if primaryKeyValues.allSatisfy({ $0.isNull }) { + return nil + } + + // Don't update columns not present in columns + // Don't update columns not present in the persistenceContainer + // Don't update primary key columns + let lowercaseUpdatedColumns = Set(columns.map { $0.lowercased() }) + .intersection(persistenceContainer.columns.map { $0.lowercased() }) + .subtracting(primaryKeyColumns.map { $0.lowercased() }) + + var updatedColumns: [String] = try db + .columns(in: databaseTableName) + .map(\.name) + .filter { lowercaseUpdatedColumns.contains($0.lowercased()) } + + if updatedColumns.isEmpty { + // IMPLEMENTATION NOTE + // + // It is important to update something, so that + // TransactionObserver can observe a change even though this + // change is useless. + // + // The goal is to be able to write tests with minimal tables, + // including tables made of a single primary key column. + updatedColumns = primaryKeyColumns + } + + let updatedValues = updatedColumns.map { + persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null + } + + let query = UpdateQuery( + onConflict: onConflict, + tableName: databaseTableName, + updatedColumns: updatedColumns, + conditionColumns: primaryKeyColumns) + + return try makeStatement( + sql: query.sql, + checkedArguments: StatementArguments(updatedValues + primaryKeyValues), + returning: selection) + } + + /// Returns nil if and only if primary key is nil + func deleteStatement() throws -> Statement? { + // Fail early if primary key does not resolve to a database row. + let primaryKeyColumns = primaryKey.columns + let primaryKeyValues = primaryKeyColumns.map { + persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null + } + if primaryKeyValues.allSatisfy({ $0.isNull }) { + return nil + } + + let query = DeleteQuery( + tableName: databaseTableName, + conditionColumns: primaryKeyColumns) + let statement = try db.internalCachedStatement(sql: query.sql) + statement.setUncheckedArguments(StatementArguments(primaryKeyValues)) + return statement + } + + /// Returns nil if and only if primary key is nil + func existsStatement() throws -> Statement? { + // Fail early if primary key does not resolve to a database row. + let primaryKeyColumns = primaryKey.columns + let primaryKeyValues = primaryKeyColumns.map { + persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null + } + if primaryKeyValues.allSatisfy({ $0.isNull }) { + return nil + } + + let query = ExistsQuery( + tableName: databaseTableName, + conditionColumns: primaryKeyColumns) + let statement = try db.internalCachedStatement(sql: query.sql) + statement.setUncheckedArguments(StatementArguments(primaryKeyValues)) + return statement + } + + /// Throws a PersistenceError.recordNotFound error + func makeRecordNotFoundError() -> Error { + let key = Dictionary(uniqueKeysWithValues: primaryKey.columns.map { + ($0, persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null) + }) + return PersistenceError.recordNotFound( + databaseTableName: databaseTableName, + key: key) + } + + // Support for the RETURNING clause + private func makeStatement( + sql: String, + checkedArguments arguments: StatementArguments, + returning selection: [any SQLSelectable]) + throws -> Statement + { + if selection.isEmpty { + let statement = try db.internalCachedStatement(sql: sql) + // We have built valid arguments: don't check + statement.setUncheckedArguments(arguments) + return statement + } else { + let context = SQLGenerationContext(db) + var sql = sql + var arguments = arguments + sql += " RETURNING " + sql += try selection + .map { try $0.sqlSelection.sql(context) } + .joined(separator: ", ") + arguments += context.arguments + let statement = try db.internalCachedStatement(sql: sql) + statement.arguments = arguments + return statement + } + } +} + +// MARK: - InsertQuery + +private struct InsertQuery: Hashable { + let onConflict: Database.ConflictResolution + let tableName: String + let insertedColumns: [String] +} + +extension InsertQuery { + @ReadWriteBox private static var sqlCache: [InsertQuery: String] = [:] + var sql: String { + if let sql = Self.sqlCache[self] { + return sql + } + let columnsSQL = insertedColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", ") + let valuesSQL = databaseQuestionMarks(count: insertedColumns.count) + let sql: String + switch onConflict { + case .abort: + sql = """ + INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ + VALUES (\(valuesSQL)) + """ + default: + sql = """ + INSERT OR \(onConflict.rawValue) \ + INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ + VALUES (\(valuesSQL)) + """ + } + Self.sqlCache[self] = sql + return sql + } +} + +// MARK: - UpsertQuery + +private struct UpsertQuery: Hashable { + let tableName: String + let insertedColumns: [String] + let conflictTargetColumns: [String] + let updatedColumns: [String] +} + +extension UpsertQuery { + @ReadWriteBox private static var sqlCache: [UpsertQuery: String] = [:] + var sql: String { + if let sql = Self.sqlCache[self] { + return sql + } + + let columnsSQL = insertedColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", ") + let valuesSQL = databaseQuestionMarks(count: insertedColumns.count) + + let onConflictSQL: String + if conflictTargetColumns.isEmpty { + onConflictSQL = "ON CONFLICT" + } else { + let targetSQL = conflictTargetColumns + .map { $0.quotedDatabaseIdentifier } + .joined(separator: ", ") + onConflictSQL = "ON CONFLICT(\(targetSQL))" + } + + let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ", ") + + let sql = """ + INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ + VALUES (\(valuesSQL)) \ + \(onConflictSQL) DO UPDATE SET \(updateSQL) + """ + Self.sqlCache[self] = sql + return sql + } +} + +// MARK: - UpdateQuery + +private struct UpdateQuery: Hashable { + let onConflict: Database.ConflictResolution + let tableName: String + let updatedColumns: [String] + let conditionColumns: [String] +} + +extension UpdateQuery { + @ReadWriteBox private static var sqlCache: [UpdateQuery: String] = [:] + var sql: String { + if let sql = Self.sqlCache[self] { + return sql + } + let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ", ") + let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ") + let sql: String + switch onConflict { + case .abort: + sql = """ + UPDATE \(tableName.quotedDatabaseIdentifier) \ + SET \(updateSQL) \ + WHERE \(whereSQL) + """ + default: + sql = """ + UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) \ + SET \(updateSQL) \ + WHERE \(whereSQL) + """ + } + Self.sqlCache[self] = sql + return sql + } +} + +// MARK: - DeleteQuery + +private struct DeleteQuery { + let tableName: String + let conditionColumns: [String] +} + +extension DeleteQuery { + var sql: String { + let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ") + return "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL)" + } +} + +// MARK: - ExistsQuery + +private struct ExistsQuery { + let tableName: String + let conditionColumns: [String] +} + +extension ExistsQuery { + var sql: String { + let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ") + return "SELECT EXISTS (SELECT 1 FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL))" + } +} diff --git a/GRDB/Record/MutablePersistableRecord+Delete.swift b/GRDB/Record/MutablePersistableRecord+Delete.swift new file mode 100644 index 000000000..70fd722e6 --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord+Delete.swift @@ -0,0 +1,56 @@ +// MARK: - Delete Callbacks + +extension MutablePersistableRecord { + @inline(__always) + @inlinable + public func willDelete(_ db: Database) throws { } + + @inline(__always) + @inlinable + public func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + _ = try delete() + } + + @inline(__always) + @inlinable + public func didDelete(deleted: Bool) { } +} + +// MARK: - Delete + +extension MutablePersistableRecord { + /// Executes a DELETE statement. + /// + /// - parameter db: A database connection. + /// - returns: Whether a database row was deleted. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @discardableResult + @inlinable // allow specialization so that empty callbacks are removed + public func delete(_ db: Database) throws -> Bool { + try willDelete(db) + + var deleted = false + try aroundDelete(db) { + deleted = try deleteWithoutCallbacks(db) + return deleted + } + + didDelete(deleted: deleted) + return deleted + } +} + +// MARK: - Internals + +extension MutablePersistableRecord { + /// Executes an `DELETE` statement, and DOES NOT run deletion callbacks. + @usableFromInline + func deleteWithoutCallbacks(_ db: Database) throws -> Bool { + guard let statement = try DAO(db, self).deleteStatement() else { + // Nil primary key + return false + } + try statement.execute() + return db.changesCount > 0 + } +} diff --git a/GRDB/Record/MutablePersistableRecord+Insert.swift b/GRDB/Record/MutablePersistableRecord+Insert.swift new file mode 100644 index 000000000..16f15d334 --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord+Insert.swift @@ -0,0 +1,473 @@ +// MARK: - Insert Callbacks + +extension MutablePersistableRecord { + @inline(__always) + @inlinable + public mutating func willInsert(_ db: Database) throws { } + + @inline(__always) + @inlinable + public func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + _ = try insert() + } + + @inline(__always) + @inlinable + public mutating func didInsert(_ inserted: InsertionSuccess) { } +} + +// MARK: - Insert + +extension MutablePersistableRecord { + /// Executes an `INSERT` statement. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public mutating func insert( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil) + throws + { + try willSave(db) + + var saved: PersistenceSuccess! + try aroundSave(db) { + let inserted = try insertWithCallbacks(db, onConflict: conflictResolution) + saved = PersistenceSuccess(inserted) + return saved + } + + didSave(saved) + } + + /// Executes an `INSERT` statement, and returns the inserted record. + /// + /// Usage: + /// + /// let player = Player(id: nil, name: "Arthur") + /// let insertedPlayer = try dbQueue.write { db in + /// try player.inserted(db) + /// } + /// print(player.id) // nil + /// print(insertedPlayer.id) // some id + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - returns: The inserted record. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public func inserted( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil) + throws -> Self + { + var result = self + try result.insert(db, onConflict: conflictResolution) + return result + } +} + +// MARK: - Insert and Fetch + +extension MutablePersistableRecord { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Executes an `INSERT ... RETURNING ...` statement, and returns the + /// inserted record. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let insertedPlayer = player.insertAndFetch(db) + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - returns: The inserted record, if any. The result can be nil when the + /// conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil) + throws -> Self? + where Self: FetchableRecord + { + var result = self + return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self) + } + + /// Executes an `INSERT ... RETURNING ...` statement, and returns a new + /// record built from the inserted row. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } + /// + /// // A player with partial database information + /// struct PartialPlayer: MutablePersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } + /// + /// // A full player, with all database information + /// struct Player: TableRecord, FetchableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } + /// + /// // Insert a base player, get a full one + /// try dbQueue.write { db in + /// var partialPlayer = PartialPlayer(name: "Alice") + /// + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * + /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { + /// print(player.id) // The inserted id + /// print(player.name) // The inserted name + /// print(player.score) // The default score + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`, if any. The result can be + /// nil when the conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public mutating func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + as returnedType: T.Type) + throws -> T? + { + try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { + try T.fetchOne($0) + } + } + + /// Executes an `INSERT ... RETURNING ...` statement, and returns the + /// selected columns from the inserted row. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } + /// + /// // A player with partial database information + /// struct PartialPlayer: MutablePersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } + /// + /// // Insert a base player, get the inserted score + /// try dbQueue.write { db in + /// var partialPlayer = PartialPlayer(name: "Alice") + /// + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score + /// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in + /// try Int.fetchOne(statement) + /// } + /// print(score) // The inserted score + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes its ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + public mutating func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + + try willSave(db) + + var inserted: InsertionSuccess! + var returned: T! + try aroundSave(db) { + (inserted, returned) = try insertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: selection, + fetch: fetch) + return PersistenceSuccess(inserted) + } + + didSave(PersistenceSuccess(inserted)) + return returned + } +#else + /// Executes an `INSERT ... RETURNING ...` statement, and returns the + /// inserted record. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let insertedPlayer = player.insertAndFetch(db) + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - returns: The inserted record, if any. The result can be nil when the + /// conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil) + throws -> Self? + where Self: FetchableRecord + { + var result = self + return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self) + } + + /// Executes an `INSERT ... RETURNING ...` statement, and returns a new + /// record built from the inserted row. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } + /// + /// // A player with partial database information + /// struct PartialPlayer: MutablePersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } + /// + /// // A full player, with all database information + /// struct Player: TableRecord, FetchableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } + /// + /// // Insert a base player, get a full one + /// try dbQueue.write { db in + /// var partialPlayer = PartialPlayer(name: "Alice") + /// + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * + /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { + /// print(player.id) // The inserted id + /// print(player.name) // The inserted name + /// print(player.score) // The default score + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`, if any. The result can be + /// nil when the conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public mutating func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + as returnedType: T.Type) + throws -> T? + { + try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { + try T.fetchOne($0) + } + } + + /// Executes an `INSERT ... RETURNING ...` statement, and returns the + /// selected columns from the inserted row. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } + /// + /// // A player with partial database information + /// struct PartialPlayer: MutablePersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } + /// + /// // Insert a base player, get the inserted score + /// try dbQueue.write { db in + /// var partialPlayer = PartialPlayer(name: "Alice") + /// + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score + /// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in + /// try Int.fetchOne(statement) + /// } + /// print(score) // The inserted score + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes its ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public mutating func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + + try willSave(db) + + var inserted: InsertionSuccess! + var returned: T! + try aroundSave(db) { + (inserted, returned) = try insertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: selection, + fetch: fetch) + return PersistenceSuccess(inserted) + } + + didSave(PersistenceSuccess(inserted)) + return returned + } +#endif +} + +// MARK: - Internals + +extension MutablePersistableRecord { + /// Executes an `INSERT` statement, and runs insertion callbacks. + @inlinable // allow specialization so that empty callbacks are removed + mutating func insertWithCallbacks( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?) + throws -> InsertionSuccess + { + let (inserted, _) = try insertAndFetchWithCallbacks(db, onConflict: conflictResolution, selection: []) { + // Nothing to fetch + try $0.execute() + } + return inserted + } + + /// Executes an `INSERT` statement, with `RETURNING` clause if `selection` + /// is not empty, and runs insertion callbacks. + @inlinable // allow specialization so that empty callbacks are removed + mutating func insertAndFetchWithCallbacks( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> (InsertionSuccess, T) + { + try willInsert(db) + + var inserted: InsertionSuccess! + var returned: T! + try aroundInsert(db) { + (inserted, returned) = try insertAndFetchWithoutCallbacks( + db, onConflict: conflictResolution, + selection: selection, + fetch: fetch) + return inserted + } + + didInsert(inserted) + return (inserted, returned) + } + + /// Executes an `INSERT` statement, with `RETURNING` clause if `selection` + /// is not empty, and DOES NOT run insertion callbacks. + @usableFromInline + func insertAndFetchWithoutCallbacks( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> (InsertionSuccess, T) + { + let conflictResolution = conflictResolution ?? type(of: self) + .persistenceConflictPolicy + .conflictResolutionForInsert + let dao = try DAO(db, self) + let statement = try dao.insertStatement( + db, + onConflict: conflictResolution, + returning: selection) + let returned = try fetch(statement) + + let rowIDColumn = dao.primaryKey.rowIDColumn + let rowid = db.lastInsertedRowID + + // Update the persistenceContainer with the inserted rowid. + // This allows the Record class to set its `hasDatabaseChanges` property + // to false in its `aroundInsert` callback. + var persistenceContainer = dao.persistenceContainer + if let rowIDColumn = rowIDColumn { + persistenceContainer[caseInsensitive: rowIDColumn] = rowid + } + + let inserted = InsertionSuccess( + rowID: rowid, + rowIDColumn: rowIDColumn, + persistenceContainer: persistenceContainer) + return (inserted, returned) + } +} diff --git a/GRDB/Record/MutablePersistableRecord+Save.swift b/GRDB/Record/MutablePersistableRecord+Save.swift new file mode 100644 index 000000000..23e0a4b34 --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord+Save.swift @@ -0,0 +1,372 @@ +// MARK: - Save Callbacks + +extension MutablePersistableRecord { + @inline(__always) + @inlinable + public func willSave(_ db: Database) throws { } + + @inline(__always) + @inlinable + public func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + _ = try save() + } + + @inline(__always) + @inlinable + public func didSave(_ saved: PersistenceSuccess) { } +} + +// MARK: - Save + +extension MutablePersistableRecord { + /// Executes an `INSERT` or `UPDATE` statement. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. + /// + /// Otherwise, performs an insert. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public mutating func save( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil) + throws + { + try willSave(db) + + var saved: PersistenceSuccess! + try aroundSave(db) { + saved = try updateOrInsertWithCallbacks(db, onConflict: conflictResolution) + return saved + } + + didSave(saved) + } + + /// Executes an `INSERT` or `UPDATE` statement, and returns the + /// saved record. + /// + /// Usage: + /// + /// let player = Player(id: nil, name: "Arthur") + /// let savedPlayer = try dbQueue.write { db in + /// try player.saved(db) + /// } + /// print(player.id) // nil + /// print(savedPlayer.id) // some id + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - returns: The saved record. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public func saved( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil) + throws -> Self + { + var result = self + try result.save(db, onConflict: conflictResolution) + return result + } +} + +// MARK: - Save and Fetch + +extension MutablePersistableRecord { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` + /// statement, and returns the saved row. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. Otherwise, it performs + /// an insert. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let savedPlayer = player.saveAndFetch(db) + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - returns: The saved record. The result can be nil when the + /// conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public func saveAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil) + throws -> Self? + where Self: FetchableRecord + { + var result = self + return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self) + } + + /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` + /// statement, and returns a new record built from the saved row. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. Otherwise, it performs + /// an insert. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`. The result can be nil when + /// the conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public mutating func saveAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + as returnedType: T.Type) + throws -> T? + { + try willSave(db) + + var saved: PersistenceSuccess! + var returned: T? + try aroundSave(db) { + (saved, returned) = try updateOrInsertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: T.databaseSelection, + fetch: { + try T.fetchOne($0) + }) + return saved + } + + didSave(saved) + return returned + } + + /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` + /// statement, and returns the selected columns from the saved row. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. Otherwise, it performs + /// an insert. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes it ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + public mutating func saveAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + + try willSave(db) + + var saved: PersistenceSuccess! + var returned: T! + try aroundSave(db) { + (saved, returned) = try updateOrInsertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: selection, + fetch: fetch) + return saved + } + + didSave(saved) + return returned + } +#else + /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` + /// statement, and returns the saved row. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. Otherwise, it performs + /// an insert. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let savedPlayer = player.saveAndFetch(db) + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - returns: The saved record. The result can be nil when the + /// conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func saveAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil) + throws -> Self? + where Self: FetchableRecord + { + var result = self + return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self) + } + + /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` + /// statement, and returns a new record built from the saved row. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. Otherwise, it performs + /// an insert. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`. The result can be nil when + /// the conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public mutating func saveAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + as returnedType: T.Type) + throws -> T? + { + try willSave(db) + + var saved: PersistenceSuccess! + var returned: T? + try aroundSave(db) { + (saved, returned) = try updateOrInsertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: T.databaseSelection, + fetch: { + try T.fetchOne($0) + }) + return saved + } + + didSave(saved) + return returned + } + + /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` + /// statement, and returns the selected columns from the saved row. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. Otherwise, it performs + /// an insert. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes it ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public mutating func saveAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + + try willSave(db) + + var saved: PersistenceSuccess! + var returned: T! + try aroundSave(db) { + (saved, returned) = try updateOrInsertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: selection, + fetch: fetch) + return saved + } + + didSave(saved) + return returned + } +#endif +} + +// MARK: - Internal + +extension MutablePersistableRecord { + /// Executes an `UPDATE` or `INSERT` statement, and runs insertion or + /// update callbacks. + @inlinable // allow specialization so that empty callbacks are removed + mutating func updateOrInsertWithCallbacks( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?) + throws -> PersistenceSuccess + { + let (saved, _) = try updateOrInsertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: [], + fetch: { + // Nothing to fetch + try $0.execute() + }) + return saved + } + + /// Executes an `UPDATE` or `INSERT` statement, with `RETURNING` clause + /// if `selection` is not empty, and runs insertion or update callbacks. + @inlinable // allow specialization so that empty callbacks are removed + mutating func updateOrInsertAndFetchWithCallbacks( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> (PersistenceSuccess, T) + { + // Attempt at updating if the record has a primary key + if let key = try primaryKey(db) { + do { + let databaseTableName = type(of: self).databaseTableName + let columns = try Set(db.columns(in: databaseTableName).map(\.name)) + return try updateAndFetchWithCallbacks( + db, onConflict: conflictResolution, + columns: columns, + selection: selection, + fetch: fetch) + } catch PersistenceError.recordNotFound(databaseTableName: type(of: self).databaseTableName, key: key) { + // No row was updated: fallback on insert. + } + } + + // Insert + let (inserted, returned) = try insertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: selection, + fetch: fetch) + return (PersistenceSuccess(inserted), returned) + } + + /// Return a non-nil dictionary if record has a non-null primary key + @usableFromInline + func primaryKey(_ db: Database) throws -> [String: DatabaseValue]? { + let databaseTableName = type(of: self).databaseTableName + let primaryKeyInfo = try db.primaryKey(databaseTableName) + let container = try PersistenceContainer(db, self) + let primaryKey = Dictionary(uniqueKeysWithValues: primaryKeyInfo.columns.map { + ($0, container[caseInsensitive: $0]?.databaseValue ?? .null) + }) + if primaryKey.allSatisfy({ $0.value.isNull }) { + return nil + } + return primaryKey + } +} diff --git a/GRDB/Record/MutablePersistableRecord+Update.swift b/GRDB/Record/MutablePersistableRecord+Update.swift new file mode 100644 index 000000000..a8c14d009 --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord+Update.swift @@ -0,0 +1,842 @@ +// MARK: - Update Callbacks + +extension MutablePersistableRecord { + @inline(__always) + @inlinable + public func willUpdate(_ db: Database, columns: Set) throws { } + + @inline(__always) + @inlinable + public func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + _ = try update() + } + + @inline(__always) + @inlinable + public func didUpdate(_ updated: PersistenceSuccess) { } +} + +// MARK: - Update + +extension MutablePersistableRecord { + /// Executes an `UPDATE` statement on the provided columns. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter columns: The columns to update. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database. + @inlinable // allow specialization so that empty callbacks are removed + public func update( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + columns: some Sequence) + throws + { + try willSave(db) + + var updated: PersistenceSuccess! + try aroundSave(db) { + updated = try updateWithCallbacks(db, onConflict: conflictResolution, columns: Set(columns)) + return updated + } + + didSave(updated) + } + + /// Executes an `UPDATE` statement on the provided columns. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter columns: The columns to update. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database. + @inlinable // allow specialization so that empty callbacks are removed + public func update( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + columns: some Sequence) + throws + { + try update(db, onConflict: conflictResolution, columns: columns.map(\.name)) + } + + /// Executes an `UPDATE` statement on all columns. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database. + @inlinable // allow specialization so that empty callbacks are removed + public func update( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil) + throws + { + let databaseTableName = type(of: self).databaseTableName + let columns = try db.columns(in: databaseTableName).map(\.name) + try update(db, onConflict: conflictResolution, columns: columns) + } + + /// If the record has any difference from the other record, executes an + /// `UPDATE` statement so that those differences and only those differences + /// are saved in the database. + /// + /// For example: + /// + /// if let oldPlayer = try Player.fetchOne(db, key: 42) { + /// var newPlayer = oldPlayer + /// newPlayer.score += 10 + /// newPlayer.hasAward = true + /// try newPlayer.updateChanges(db, from: oldRecord) + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter record: The comparison record. + /// - returns: Whether the record had changes. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database and record could not be updated. + /// - SeeAlso: updateChanges(_:with:) + @discardableResult + @inlinable // allow specialization so that empty callbacks are removed + public func updateChanges( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + from record: Record) + throws -> Bool + { + try updateChanges(db, onConflict: conflictResolution, from: PersistenceContainer(db, record)) + } + + /// Modifies the record according to the provided `modify` closure, and + /// executes an `UPDATE` statement that updates the modified columns, if and + /// only the record was modified. + /// + /// For example: + /// + /// if var player = try Player.fetchOne(db, key: 42) { + /// try player.updateChanges(db) { + /// $0.score += 10 + /// $0.hasAward = true + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter modify: A closure that modifies the record. + /// - returns: Whether the record had changes. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database and record could not be updated. + @discardableResult + @inlinable // allow specialization so that empty callbacks are removed + public mutating func updateChanges( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + modify: (inout Self) throws -> Void) + throws -> Bool + { + let container = try PersistenceContainer(db, self) + try modify(&self) + return try updateChanges(db, onConflict: conflictResolution, from: container) + } +} + +// MARK: - Update and Fetch + +extension MutablePersistableRecord { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Executes an `UPDATE ... RETURNING ...` statement, and returns the + /// updated record. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let updatedPlayer = player.updateAndFetch(db) + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - returns: The updated record. The result can be nil when the + /// conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public func updateAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil) + throws -> Self? + where Self: FetchableRecord + { + try updateAndFetch(db, onConflict: conflictResolution, as: Self.self) + } + + /// Executes an `UPDATE ... RETURNING ...` statement on all columns, and + /// returns a new record built from the updated row. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`. The result can be nil when + /// the conflict policy is `IGNORE`. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database. + @inlinable // allow specialization so that empty callbacks are removed + public func updateAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + as returnedType: T.Type) + throws -> T? + { + try updateAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { + try T.fetchOne($0) + } + } + + /// Modifies the record according to the provided `modify` closure, and + /// executes an `UPDATE ... RETURNING ...` statement that updates the + /// modified columns, if and only the record was modified. The method + /// returns a new record built from the updated row. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter modify: A closure that modifies the record. + /// - returns: An updated record, or nil if the record has no change, or + /// in case of a failed update due to the `IGNORE` conflict policy. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database and record could not be updated. + @inlinable // allow specialization so that empty callbacks are removed + public mutating func updateChangesAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + modify: (inout Self) throws -> Void) + throws -> Self? + where Self: FetchableRecord + { + try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify) + } + + /// Modifies the record according to the provided `modify` closure, and + /// executes an `UPDATE ... RETURNING ...` statement that updates the + /// modified columns, if and only the record was modified. The method + /// returns a new record built from the updated row. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter returnedType: The type of the returned record. + /// - parameter modify: A closure that modifies the record. + /// - returns: A record of type `returnedType`, or nil if the record has + /// no change, or in case of a failed update due to the `IGNORE` + /// conflict policy. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database and record could not be updated. + @inlinable // allow specialization so that empty callbacks are removed + public mutating func updateChangesAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + as returnedType: T.Type, + modify: (inout Self) throws -> Void) + throws -> T? + { + try updateChangesAndFetch( + db, onConflict: conflictResolution, + selection: T.databaseSelection, + fetch: { try T.fetchOne($0) }, + modify: modify) + } + + /// Executes an `UPDATE ... RETURNING ...` statement on the provided + /// columns, and returns the selected columns from the updated row. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = ... RETURNING totalScore + /// let totalScore = try player.updateAndFetch( + /// db, columns: ["Score"], + /// selection: [Column("totalScore")], + /// fetch: { statement in + /// try Int.fetchOne(statement) + /// }) + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter columns: The columns to update. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes it ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + public func updateAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + columns: some Sequence, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + + try willSave(db) + + var updated: PersistenceSuccess! + var returned: T! + try aroundSave(db) { + (updated, returned) = try updateAndFetchWithCallbacks( + db, onConflict: conflictResolution, + columns: Set(columns), + selection: selection, + fetch: fetch) + return updated + } + + didSave(updated) + return returned + } + + /// Executes an `UPDATE ... RETURNING ...` statement on the provided + /// columns, and returns the selected columns from the updated row. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = ... RETURNING totalScore + /// let totalScore = try player.updateAndFetch( + /// db, columns: [Column("Score")], + /// selection: [Column("totalScore")], + /// fetch: { statement in + /// try Int.fetchOne(statement) + /// }) + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter columns: The columns to update. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes it ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + public func updateAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + columns: some Sequence, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + try updateAndFetch( + db, onConflict: conflictResolution, + columns: columns.map(\.name), + selection: selection, + fetch: fetch) + } + + /// Executes an `UPDATE ... RETURNING ...` statement on all columns, and + /// returns the selected columns from the updated row. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET ... RETURNING totalScore + /// let totalScore = try player.updateAndFetch(db, selection: [Column("totalScore")]) { statement in + /// try Int.fetchOne(statement) + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes it ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + public func updateAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + let databaseTableName = type(of: self).databaseTableName + let columns = try db.columns(in: databaseTableName).map(\.name) + return try updateAndFetch( + db, onConflict: conflictResolution, + columns: columns, + selection: selection, + fetch: fetch) + } + + /// Modifies the record according to the provided `modify` closure, and + /// executes an `UPDATE ... RETURNING ...` statement that updates the + /// modified columns, if and only the record was modified. The method + /// returns a new record built from the updated row. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes it ``Statement`` argument. + /// - parameter modify: A closure that modifies the record. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database and record could not be updated. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + public mutating func updateChangesAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T?, + modify: (inout Self) throws -> Void) + throws -> T? + { + let container = try PersistenceContainer(db, self) + try modify(&self) + return try updateChangesAndFetch( + db, onConflict: conflictResolution, + from: container, + selection: selection, + fetch: fetch) + } +#else + /// Executes an `UPDATE ... RETURNING ...` statement, and returns the + /// updated record. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let updatedPlayer = player.updateAndFetch(db) + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - returns: The updated record. The result can be nil when the + /// conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func updateAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil) + throws -> Self? + where Self: FetchableRecord + { + try updateAndFetch(db, onConflict: conflictResolution, as: Self.self) + } + + /// Executes an `UPDATE ... RETURNING ...` statement on all columns, and + /// returns a new record built from the updated row. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`. The result can be nil when + /// the conflict policy is `IGNORE`. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func updateAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + as returnedType: T.Type) + throws -> T? + { + try updateAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { + try T.fetchOne($0) + } + } + + /// Modifies the record according to the provided `modify` closure, and + /// executes an `UPDATE ... RETURNING ...` statement that updates the + /// modified columns, if and only the record was modified. The method + /// returns a new record built from the updated row. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter modify: A closure that modifies the record. + /// - returns: An updated record, or nil if the record has no change, or + /// in case of a failed update due to the `IGNORE` conflict policy. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database and record could not be updated. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public mutating func updateChangesAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + modify: (inout Self) throws -> Void) + throws -> Self? + where Self: FetchableRecord + { + try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify) + } + + /// Modifies the record according to the provided `modify` closure, and + /// executes an `UPDATE ... RETURNING ...` statement that updates the + /// modified columns, if and only the record was modified. The method + /// returns a new record built from the updated row. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter returnedType: The type of the returned record. + /// - parameter modify: A closure that modifies the record. + /// - returns: A record of type `returnedType`, or nil if the record has + /// no change, or in case of a failed update due to the `IGNORE` + /// conflict policy. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database and record could not be updated. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public mutating func updateChangesAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + as returnedType: T.Type, + modify: (inout Self) throws -> Void) + throws -> T? + { + try updateChangesAndFetch( + db, onConflict: conflictResolution, + selection: T.databaseSelection, + fetch: { try T.fetchOne($0) }, + modify: modify) + } + + /// Executes an `UPDATE ... RETURNING ...` statement on the provided + /// columns, and returns the selected columns from the updated row. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = ... RETURNING totalScore + /// let totalScore = try player.updateAndFetch( + /// db, columns: ["Score"], + /// selection: [Column("totalScore")], + /// fetch: { statement in + /// try Int.fetchOne(statement) + /// }) + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter columns: The columns to update. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes it ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func updateAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + columns: some Sequence, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + + try willSave(db) + + var updated: PersistenceSuccess! + var returned: T! + try aroundSave(db) { + (updated, returned) = try updateAndFetchWithCallbacks( + db, onConflict: conflictResolution, + columns: Set(columns), + selection: selection, + fetch: fetch) + return updated + } + + didSave(updated) + return returned + } + + /// Executes an `UPDATE ... RETURNING ...` statement on the provided + /// columns, and returns the selected columns from the updated row. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = ... RETURNING totalScore + /// let totalScore = try player.updateAndFetch( + /// db, columns: [Column("Score")], + /// selection: [Column("totalScore")], + /// fetch: { statement in + /// try Int.fetchOne(statement) + /// }) + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter columns: The columns to update. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes it ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func updateAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + columns: some Sequence, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + try updateAndFetch( + db, onConflict: conflictResolution, + columns: columns.map(\.name), + selection: selection, + fetch: fetch) + } + + /// Executes an `UPDATE ... RETURNING ...` statement on all columns, and + /// returns the selected columns from the updated row. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET ... RETURNING totalScore + /// let totalScore = try player.updateAndFetch(db, selection: [Column("totalScore")]) { statement in + /// try Int.fetchOne(statement) + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes it ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func updateAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + let databaseTableName = type(of: self).databaseTableName + let columns = try db.columns(in: databaseTableName).map(\.name) + return try updateAndFetch( + db, onConflict: conflictResolution, + columns: columns, + selection: selection, + fetch: fetch) + } + + /// Modifies the record according to the provided `modify` closure, and + /// executes an `UPDATE ... RETURNING ...` statement that updates the + /// modified columns, if and only the record was modified. The method + /// returns a new record built from the updated row. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes it ``Statement`` argument. + /// - parameter modify: A closure that modifies the record. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database and record could not be updated. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public mutating func updateChangesAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T?, + modify: (inout Self) throws -> Void) + throws -> T? + { + let container = try PersistenceContainer(db, self) + try modify(&self) + return try updateChangesAndFetch( + db, onConflict: conflictResolution, + from: container, + selection: selection, + fetch: fetch) + } +#endif +} + +// MARK: - Internals + +extension MutablePersistableRecord { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + @inlinable // allow specialization so that empty callbacks are removed + func updateChangesAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?, + from container: PersistenceContainer, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T?) + throws -> T? + { + let changes = try PersistenceContainer(db, self).changesIterator(from: container) + let changedColumns: Set = changes.reduce(into: []) { $0.insert($1.0) } + if changedColumns.isEmpty { + return nil + } + return try updateAndFetch( + db, onConflict: conflictResolution, + columns: changedColumns, + selection: selection, + fetch: fetch) + } +#else + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + func updateChangesAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?, + from container: PersistenceContainer, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T?) + throws -> T? + { + let changes = try PersistenceContainer(db, self).changesIterator(from: container) + let changedColumns: Set = changes.reduce(into: []) { $0.insert($1.0) } + if changedColumns.isEmpty { + return nil + } + return try updateAndFetch( + db, onConflict: conflictResolution, + columns: changedColumns, + selection: selection, + fetch: fetch) + } +#endif + + /// Executes an `UPDATE` statement, and runs update callbacks. + @inlinable // allow specialization so that empty callbacks are removed + func updateWithCallbacks( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?, + columns: Set) + throws -> PersistenceSuccess + { + let (updated, _) = try updateAndFetchWithCallbacks( + db, onConflict: conflictResolution, + columns: columns, + selection: [], + fetch: { + // Nothing to fetch + try $0.execute() + }) + return updated + } + + /// Executes an `UPDATE` statement, with `RETURNING` clause if `selection` + /// is not empty, and runs update callbacks. + @inlinable // allow specialization so that empty callbacks are removed + func updateAndFetchWithCallbacks( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?, + columns: Set, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> (PersistenceSuccess, T) + { + try willUpdate(db, columns: columns) + + var updated: PersistenceSuccess! + var returned: T! + try aroundUpdate(db, columns: columns) { + (updated, returned) = try updateAndFetchWithoutCallbacks( + db, onConflict: conflictResolution, + columns: columns, + selection: selection, + fetch: fetch) + return updated + } + + didUpdate(updated) + return (updated, returned) + } + + /// Executes an `UPDATE` statement, with `RETURNING` clause if `selection` + /// is not empty, and DOES NOT run update callbacks. + @usableFromInline + func updateAndFetchWithoutCallbacks( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?, + columns: Set, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> (PersistenceSuccess, T) + { + let conflictResolution = conflictResolution ?? type(of: self) + .persistenceConflictPolicy + .conflictResolutionForUpdate + let dao = try DAO(db, self) + guard let statement = try dao.updateStatement( + columns: columns, + onConflict: conflictResolution, + returning: selection) + else { + // Nil primary key + throw dao.makeRecordNotFoundError() + } + let returned = try fetch(statement) + if db.changesCount == 0 { + // No row was updated + throw dao.makeRecordNotFoundError() + } + let updated = PersistenceSuccess(persistenceContainer: dao.persistenceContainer) + return (updated, returned) + } + + @inlinable // allow specialization so that empty callbacks are removed + func updateChanges( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?, + from container: PersistenceContainer) + throws -> Bool + { + let changes = try PersistenceContainer(db, self).changesIterator(from: container) + let changedColumns: Set = changes.reduce(into: []) { $0.insert($1.0) } + if changedColumns.isEmpty { + return false + } + try update(db, onConflict: conflictResolution, columns: changedColumns) + return true + } +} diff --git a/GRDB/Record/MutablePersistableRecord+Upsert.swift b/GRDB/Record/MutablePersistableRecord+Upsert.swift new file mode 100644 index 000000000..ea3022ecd --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord+Upsert.swift @@ -0,0 +1,241 @@ +// MARK: - Upsert + +extension MutablePersistableRecord { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Executes an `INSERT ... ON CONFLICT DO UPDATE` statement. + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public mutating func upsert(_ db: Database) throws { + try willSave(db) + + var saved: PersistenceSuccess! + try aroundSave(db) { + let inserted = try upsertWithCallbacks(db) + saved = PersistenceSuccess(inserted) + return saved + } + + didSave(saved) + } + + /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` + /// statement, and returns the inserted record. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let insertedPlayer = player.upsertAndFetch(db) + /// + /// - parameter db: A database connection. + /// - returns: The inserted record. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public mutating func upsertAndFetch(_ db: Database) throws -> Self + where Self: FetchableRecord + { + try upsertAndFetch(db, as: Self.self) + } + + /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` + /// statement, and returns the inserted record. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let insertedPlayer = player.upsertAndFetch(db) + /// + /// - parameter db: A database connection. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public mutating func upsertAndFetch( + _ db: Database, + as returnedType: T.Type) + throws -> T + { + try willSave(db) + + var inserted: InsertionSuccess! + var returned: T! + try aroundSave(db) { + (inserted, returned) = try upsertAndFetchWithCallbacks( + db, selection: T.databaseSelection, + decode: { try T(row: $0) }) + return PersistenceSuccess(inserted) + } + + didSave(PersistenceSuccess(inserted)) + return returned + } +#else + /// Executes an `INSERT ... ON CONFLICT DO UPDATE` statement. + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public mutating func upsert(_ db: Database) throws { + try willSave(db) + + var saved: PersistenceSuccess! + try aroundSave(db) { + let inserted = try upsertWithCallbacks(db) + saved = PersistenceSuccess(inserted) + return saved + } + + didSave(saved) + } + + /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` + /// statement, and returns the inserted record. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let insertedPlayer = player.upsertAndFetch(db) + /// + /// - parameter db: A database connection. + /// - returns: The inserted record. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public mutating func upsertAndFetch(_ db: Database) throws -> Self + where Self: FetchableRecord + { + try upsertAndFetch(db, as: Self.self) + } + + /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` + /// statement, and returns the inserted record. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let insertedPlayer = player.upsertAndFetch(db) + /// + /// - parameter db: A database connection. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public mutating func upsertAndFetch( + _ db: Database, + as returnedType: T.Type) + throws -> T + { + try willSave(db) + + var inserted: InsertionSuccess! + var returned: T! + try aroundSave(db) { + (inserted, returned) = try upsertAndFetchWithCallbacks( + db, selection: T.databaseSelection, + decode: { try T(row: $0) }) + return PersistenceSuccess(inserted) + } + + didSave(PersistenceSuccess(inserted)) + return returned + } +#endif +} + +// MARK: - Internal + +extension MutablePersistableRecord { + @inlinable // allow specialization so that empty callbacks are removed + mutating func upsertWithCallbacks(_ db: Database) + throws -> InsertionSuccess + { + let (inserted, _) = try upsertAndFetchWithCallbacks( + db, selection: [], + decode: { _ in /* Nothing to decode */ }) + return inserted + } + + @inlinable // allow specialization so that empty callbacks are removed + mutating func upsertAndFetchWithCallbacks( + _ db: Database, + selection: [any SQLSelectable], + decode: (Row) throws -> T) + throws -> (InsertionSuccess, T) + { + try willInsert(db) + + var inserted: InsertionSuccess! + var returned: T! + try aroundInsert(db) { + (inserted, returned) = try upsertAndFetchWithoutCallbacks( + db, selection: selection, + decode: decode) + return inserted + } + + didInsert(inserted) + return (inserted, returned) + } + + /// Executes an `INSERT ... RETURNING` statement, and DOES NOT run + /// insertion callbacks. + @usableFromInline + func upsertAndFetchWithoutCallbacks( + _ db: Database, + selection: [any SQLSelectable], + decode: (Row) throws -> T) + throws -> (InsertionSuccess, T) + { + // Append the rowID to the returned columns + let selection = selection + [Column.rowID] + + let dao = try DAO(db, self) + let statement = try dao.upsertStatement( + db, + conflictTarget: [], + returning: selection) + let cursor = try Row.fetchCursor(statement) + + // Keep cursor alive until we can process the fetched row + let (rowid, returned): (Int64, T) = try withExtendedLifetime(cursor) { cursor in + guard let row = try cursor.next() else { + throw DatabaseError(message: "Insertion failed") + } + + // Rowid is the last column + let rowid: Int64 = row[row.count - 1] + let returned = try decode(row) + return (rowid, returned) + } + + // Update the persistenceContainer with the inserted rowid. + // This allows the Record class to set its `hasDatabaseChanges` property + // to false in its `aroundInsert` callback. + var persistenceContainer = dao.persistenceContainer + let rowIDColumn = dao.primaryKey.rowIDColumn + if let rowIDColumn = rowIDColumn { + persistenceContainer[caseInsensitive: rowIDColumn] = rowid + } + + let inserted = InsertionSuccess( + rowID: rowid, + rowIDColumn: rowIDColumn, + persistenceContainer: persistenceContainer) + return (inserted, returned) + } +} diff --git a/GRDB/Record/MutablePersistableRecord.swift b/GRDB/Record/MutablePersistableRecord.swift new file mode 100644 index 000000000..60a7822fa --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord.swift @@ -0,0 +1,303 @@ +/// Types that adopt `MutablePersistableRecord` can be inserted, updated, +/// and deleted. +public protocol MutablePersistableRecord: EncodableRecord, TableRecord { + /// The policy that handles SQLite conflicts when records are inserted + /// or updated. + /// + /// The default implementation uses the ABORT policy for both insertions and + /// updates, and has GRDB generate regular INSERT and UPDATE queries. + /// + /// See + static var persistenceConflictPolicy: PersistenceConflictPolicy { get } + + // MARK: Insertion Callbacks + + /// Persistence callback called before the record is inserted. + /// + /// Default implementation does nothing. + /// + /// - parameter db: A database connection. + mutating func willInsert(_ db: Database) throws + + /// Persistence callback called around the record insertion. + /// + /// If you provide a custom implementation of this method, you must call + /// the `insert` parameter at some point in your implementation. + /// + /// For example: + /// + /// struct Player: MutablePersistableRecord { + /// func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + /// print("Player will insert") + /// _ = try insert() + /// print("Player did insert") + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter insert: A function that inserts the record, and returns + /// information about the inserted row. + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws + + /// Persistence callback called upon successful insertion. + /// + /// The default implementation does nothing. + /// + /// You can provide a custom implementation in order to grab the + /// auto-incremented id: + /// + /// struct Player: MutablePersistableRecord { + /// var id: Int64? + /// var name: String + /// + /// mutating func didInsert(_ inserted: InsertionSuccess) { + /// id = inserted.rowID + /// } + /// } + /// + /// - parameter inserted: Information about the inserted row. + mutating func didInsert(_ inserted: InsertionSuccess) + + // MARK: Update Callbacks + + /// Persistence callback called before the record is updated. + /// + /// Default implementation does nothing. + /// + /// - parameter db: A database connection. + func willUpdate(_ db: Database, columns: Set) throws + + // swiftlint:disable line_length + /// Persistence callback called around the record update. + /// + /// If you provide a custom implementation of this method, you must call + /// the `update` parameter at some point in your implementation. + /// + /// For example: + /// + /// struct Player: MutablePersistableRecord { + /// func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + /// print("Player will update") + /// _ = try update() + /// print("Player did update") + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter columns: The updated columns. + /// - parameter update: A function that updates the record. Its result is + /// reserved for GRDB usage. + func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws + // swiftlint:enable line_length + + /// Persistence callback called upon successful update. + /// + /// Default implementation does nothing. + /// + /// - parameter updated: Reserved for GRDB usage. + func didUpdate(_ updated: PersistenceSuccess) + + // MARK: Save Callbacks + + /// Persistence callback called before the record is updated or inserted. + /// + /// Default implementation does nothing. + /// + /// - parameter db: A database connection. + func willSave(_ db: Database) throws + + /// Persistence callback called around the record update or insertion. + /// + /// If you provide a custom implementation of this method, you must call + /// the `save` parameter at some point in your implementation. + /// + /// For example: + /// + /// struct Player: MutablePersistableRecord { + /// func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + /// print("Player will save") + /// _ = try save() + /// print("Player did save") + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter update: A function that updates the record. Its result is + /// reserved for GRDB usage. + func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws + + /// Persistence callback called upon successful update or insertion. + /// + /// Default implementation does nothing. + /// + /// - parameter saved: Reserved for GRDB usage. + func didSave(_ saved: PersistenceSuccess) + + // MARK: Deletion Callbacks + + /// Persistence callback called before the record is deleted. + /// + /// Default implementation does nothing. + /// + /// - parameter db: A database connection. + func willDelete(_ db: Database) throws + + /// Persistence callback called around the destruction of the record. + /// + /// If you provide a custom implementation of this method, you must call + /// the `delete` parameter at some point in your implementation. + /// + /// For example: + /// + /// struct Player: MutablePersistableRecord { + /// func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + /// print("Player will delete") + /// _ = try delete() + /// print("Player did delete") + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter delete: A function that deletes the record and returns + /// whether a row was deleted in the database. + func aroundDelete(_ db: Database, delete: () throws -> Bool) throws + + /// Persistence callback called upon successful deletion. + /// + /// Default implementation does nothing. + /// + /// - parameter deleted: Whether a row was deleted in the database. + func didDelete(deleted: Bool) +} + +extension MutablePersistableRecord { + public static var persistenceConflictPolicy: PersistenceConflictPolicy { + PersistenceConflictPolicy(insert: .abort, update: .abort) + } +} + +// MARK: - Existence Check + +extension MutablePersistableRecord { + /// Returns true if and only if the primary key matches a row in + /// the database. + /// + /// - parameter db: A database connection. + /// - returns: Whether the primary key matches a row in the database. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func exists(_ db: Database) throws -> Bool { + guard let statement = try DAO(db, self).existsStatement() else { + // Nil primary key + return false + } + return try Bool.fetchOne(statement)! + } +} + +/// An error thrown by a type that adopts `MutablePersistableRecord`. +public enum PersistenceError: Error { + + /// Thrown by `MutablePersistableRecord.update(_:)` methods when no matching + /// row could be found in the database. + /// + /// - `databaseTableName`: the table of the unfound record + /// - `key`: the key of the unfound record (column and values) + case recordNotFound(databaseTableName: String, key: [String: DatabaseValue]) +} + +extension PersistenceError: CustomStringConvertible { + /// :nodoc: + public var description: String { + switch self { + case let .recordNotFound(databaseTableName: databaseTableName, key: key): + let row = Row(key) // For nice output + return "Key not found in table \(databaseTableName): \(row.description)" + } + } +} + +/// The `MutablePersistableRecord` protocol uses this type in order to handle +/// SQLite conflicts when records are inserted or updated. +/// +/// See `MutablePersistableRecord.persistenceConflictPolicy`. +/// +/// See +public struct PersistenceConflictPolicy { + /// The conflict resolution algorithm for insertions + public let conflictResolutionForInsert: Database.ConflictResolution + + /// The conflict resolution algorithm for updates + public let conflictResolutionForUpdate: Database.ConflictResolution + + /// Creates a policy + public init(insert: Database.ConflictResolution = .abort, update: Database.ConflictResolution = .abort) { + self.conflictResolutionForInsert = insert + self.conflictResolutionForUpdate = update + } +} + +/// The result of a successful record insertion. +/// +/// `InsertionSuccess` gives the auto-incremented id after a successful +/// record insertion: +/// +/// struct Player: Encodable, MutablePersistableRecord { +/// var id: Int64? +/// var name: String +/// +/// mutating func didInsert(_ inserted: InsertionSuccess) { +/// id = inserted.rowID +/// } +/// } +/// +/// try dbQueue.write { db in +/// var player = Player(id: nil, name: "Alice") +/// try player.insert(db) +/// print(player.id) // The inserted id +/// } +public struct InsertionSuccess { + /// The rowid of the inserted record. + /// + /// For example: + /// + /// struct Player: Encodable, MutablePersistableRecord { + /// var id: Int64? + /// var name: String + /// + /// mutating func didInsert(_ inserted: InsertionSuccess) { + /// id = inserted.rowID + /// } + /// } + /// + /// To learn about rowids, see . + public var rowID: Int64 + + /// The name of the eventual INTEGER PRIMARY KEY column. + public var rowIDColumn: String? + + // Used by the Record class in order to manage its `hasDatabaseChanges` flag. + /// The persistence container that was inserted. + /// + /// If the database table has a rowid column, the persistence container + /// contains the rowid of the inserted record. + public var persistenceContainer: PersistenceContainer +} + +/// The result of a successful record persistence (insert or update). +public struct PersistenceSuccess { + // Used by the Record class in order to manage its `hasDatabaseChanges` flag. + /// The persistence container that was saved. + /// + /// After an insert, and if the database table has a rowid column, the + /// persistence container contains the rowid of the inserted record. + public var persistenceContainer: PersistenceContainer + + init(persistenceContainer: PersistenceContainer) { + self.persistenceContainer = persistenceContainer + } + + @usableFromInline + init(_ inserted: InsertionSuccess) { + self.init(persistenceContainer: inserted.persistenceContainer) + } +} diff --git a/GRDB/Record/PersistableRecord+Insert.swift b/GRDB/Record/PersistableRecord+Insert.swift new file mode 100644 index 000000000..504cb3c0f --- /dev/null +++ b/GRDB/Record/PersistableRecord+Insert.swift @@ -0,0 +1,344 @@ +// MARK: - Insert Callbacks + +extension PersistableRecord { + public func willInsert(_ db: Database) throws { } + + public func didInsert(_ inserted: InsertionSuccess) { } +} + +// MARK: - Insert + +extension PersistableRecord { + /// Executes an `INSERT` statement. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public func insert( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil) + throws + { + try willSave(db) + + var saved: PersistenceSuccess! + try aroundSave(db) { + let inserted = try insertWithCallbacks(db, onConflict: conflictResolution) + saved = PersistenceSuccess(inserted) + return saved + } + + didSave(saved) + } +} + +// MARK: - Insert and Fetch + +extension PersistableRecord { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Executes an `INSERT ... RETURNING ...` statement, and returns a new + /// record built from the inserted row. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } + /// + /// // A player with partial database information + /// struct PartialPlayer: PersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } + /// + /// // A full player, with all database information + /// struct Player: TableRecord, FetchableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } + /// + /// // Insert a base player, get a full one + /// try dbQueue.write { db in + /// let partialPlayer = PartialPlayer(name: "Alice") + /// + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * + /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { + /// print(player.id) // The inserted id + /// print(player.name) // The inserted name + /// print(player.score) // The default score + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`. The result can be + /// nil when the conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + as returnedType: T.Type) + throws -> T? + { + try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { + try T.fetchOne($0) + } + } + + /// Executes an `INSERT ... RETURNING ...` statement, and returns the + /// selected columns from the inserted row. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } + /// + /// // A player with partial database information + /// struct PartialPlayer: PersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } + /// + /// // Insert a base player, get the inserted score + /// try dbQueue.write { db in + /// let partialPlayer = PartialPlayer(name: "Alice") + /// + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score + /// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in + /// try Int.fetchOne(statement) + /// } + /// print(score) // The inserted score + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes its ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + public func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + + try willSave(db) + + var inserted: InsertionSuccess! + var returned: T! + try aroundSave(db) { + (inserted, returned) = try insertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: selection, + fetch: fetch) + return PersistenceSuccess(inserted) + } + + didSave(PersistenceSuccess(inserted)) + return returned + } +#else + /// Executes an `INSERT ... RETURNING ...` statement, and returns a new + /// record built from the inserted row. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } + /// + /// // A player with partial database information + /// struct PartialPlayer: PersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } + /// + /// // A full player, with all database information + /// struct Player: TableRecord, FetchableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } + /// + /// // Insert a base player, get a full one + /// try dbQueue.write { db in + /// let partialPlayer = PartialPlayer(name: "Alice") + /// + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * + /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { + /// print(player.id) // The inserted id + /// print(player.name) // The inserted name + /// print(player.score) // The default score + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`. The result can be + /// nil when the conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + as returnedType: T.Type) + throws -> T? + { + try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { + try T.fetchOne($0) + } + } + + /// Executes an `INSERT ... RETURNING ...` statement, and returns the + /// selected columns from the inserted row. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } + /// + /// // A player with partial database information + /// struct PartialPlayer: PersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } + /// + /// // Insert a base player, get the inserted score + /// try dbQueue.write { db in + /// let partialPlayer = PartialPlayer(name: "Alice") + /// + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score + /// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in + /// try Int.fetchOne(statement) + /// } + /// print(score) // The inserted score + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes its ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + + try willSave(db) + + var inserted: InsertionSuccess! + var returned: T! + try aroundSave(db) { + (inserted, returned) = try insertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: selection, + fetch: fetch) + return PersistenceSuccess(inserted) + } + + didSave(PersistenceSuccess(inserted)) + return returned + } +#endif +} + +// MARK: - Internals + +extension PersistableRecord { + /// Executes an `INSERT` statement, and runs insertion callbacks. + @inlinable // allow specialization so that empty callbacks are removed + func insertWithCallbacks( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?) + throws -> InsertionSuccess + { + let (inserted, _) = try insertAndFetchWithCallbacks(db, onConflict: conflictResolution, selection: []) { + // Nothing to fetch + try $0.execute() + } + return inserted + } + + /// Executes an `INSERT` statement, with `RETURNING` clause if `selection` + /// is not empty, and runs insertion callbacks. + @inlinable // allow specialization so that empty callbacks are removed + func insertAndFetchWithCallbacks( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> (InsertionSuccess, T) + { + try willInsert(db) + + var inserted: InsertionSuccess! + var returned: T! + try aroundInsert(db) { + (inserted, returned) = try insertAndFetchWithoutCallbacks( + db, onConflict: conflictResolution, + selection: selection, + fetch: fetch) + return inserted + } + + didInsert(inserted) + return (inserted, returned) + } +} diff --git a/GRDB/Record/PersistableRecord+Save.swift b/GRDB/Record/PersistableRecord+Save.swift new file mode 100644 index 000000000..125985627 --- /dev/null +++ b/GRDB/Record/PersistableRecord+Save.swift @@ -0,0 +1,249 @@ +// MARK: - Save + +extension PersistableRecord { + /// Executes an `INSERT` or `UPDATE` statement. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. + /// + /// Otherwise, performs an insert. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public func save( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil) + throws + { + try willSave(db) + + var saved: PersistenceSuccess! + try aroundSave(db) { + saved = try updateOrInsertWithCallbacks(db, onConflict: conflictResolution) + return saved + } + + didSave(saved) + } +} + +// MARK: - Save and Fetch + +extension PersistableRecord { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` + /// statement, and returns a new record built from the saved row. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. Otherwise, it performs + /// an insert. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`. The result can be nil when + /// the conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public func saveAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + as returnedType: T.Type) + throws -> T? + { + try willSave(db) + + var saved: PersistenceSuccess! + var returned: T? + try aroundSave(db) { + (saved, returned) = try updateOrInsertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: T.databaseSelection, + fetch: { + try T.fetchOne($0) + }) + return saved + } + + didSave(saved) + return returned + } + + /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` + /// statement, and returns the selected columns from the saved row. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. Otherwise, it performs + /// an insert. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes it ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + public func saveAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + + try willSave(db) + + var saved: PersistenceSuccess! + var returned: T! + try aroundSave(db) { + (saved, returned) = try updateOrInsertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: selection, + fetch: fetch) + return saved + } + + didSave(saved) + return returned + } +#else + /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` + /// statement, and returns a new record built from the saved row. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. Otherwise, it performs + /// an insert. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`. The result can be nil when + /// the conflict policy is `IGNORE`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func saveAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + as returnedType: T.Type) + throws -> T? + { + try willSave(db) + + var saved: PersistenceSuccess! + var returned: T? + try aroundSave(db) { + (saved, returned) = try updateOrInsertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: T.databaseSelection, + fetch: { + try T.fetchOne($0) + }) + return saved + } + + didSave(saved) + return returned + } + + /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` + /// statement, and returns the selected columns from the saved row. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. Otherwise, it performs + /// an insert. + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter selection: The returned columns (must not be empty). + /// - parameter fetch: A function that executes it ``Statement`` argument. + /// - returns: The result of the `fetch` function. + /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - precondition: `selection` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func saveAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> T + { + GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") + + try willSave(db) + + var saved: PersistenceSuccess! + var returned: T! + try aroundSave(db) { + (saved, returned) = try updateOrInsertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: selection, + fetch: fetch) + return saved + } + + didSave(saved) + return returned + } +#endif +} + +// MARK: - Internals + +extension PersistableRecord { + /// Executes an `UPDATE` or `INSERT` statement, and runs insertion or + /// update callbacks. + @inlinable // allow specialization so that empty callbacks are removed + func updateOrInsertWithCallbacks( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?) + throws -> PersistenceSuccess + { + let (saved, _) = try updateOrInsertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: [], + fetch: { + // Nothing to fetch + try $0.execute() + }) + return saved + } + + /// Executes an `UPDATE` or `INSERT` statement, with `RETURNING` clause + /// if `selection` is not empty, and runs insertion or update callbacks. + @inlinable // allow specialization so that empty callbacks are removed + func updateOrInsertAndFetchWithCallbacks( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?, + selection: [any SQLSelectable], + fetch: (Statement) throws -> T) + throws -> (PersistenceSuccess, T) + { + // Attempt at updating if the record has a primary key + if let key = try primaryKey(db) { + do { + let databaseTableName = type(of: self).databaseTableName + let columns = try Set(db.columns(in: databaseTableName).map(\.name)) + return try updateAndFetchWithCallbacks( + db, onConflict: conflictResolution, + columns: columns, + selection: selection, + fetch: fetch) + } catch PersistenceError.recordNotFound(databaseTableName: type(of: self).databaseTableName, key: key) { + // No row was updated: fallback on insert. + } + } + + // Insert + let (inserted, returned) = try insertAndFetchWithCallbacks( + db, onConflict: conflictResolution, + selection: selection, + fetch: fetch) + return (PersistenceSuccess(inserted), returned) + } +} diff --git a/GRDB/Record/PersistableRecord+Upsert.swift b/GRDB/Record/PersistableRecord+Upsert.swift new file mode 100644 index 000000000..cfb02b060 --- /dev/null +++ b/GRDB/Record/PersistableRecord+Upsert.swift @@ -0,0 +1,194 @@ +// MARK: - Upsert + +extension PersistableRecord { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Executes an `INSERT ... ON CONFLICT DO UPDATE` statement. + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public func upsert(_ db: Database) throws { + try willSave(db) + + var saved: PersistenceSuccess! + try aroundSave(db) { + let inserted = try upsertWithCallbacks(db) + saved = PersistenceSuccess(inserted) + return saved + } + + didSave(saved) + } + + /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` + /// statement, and returns the inserted record. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let insertedPlayer = player.upsertAndFetch(db) + /// + /// - parameter db: A database connection. + /// - returns: The inserted record. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public func upsertAndFetch(_ db: Database) throws -> Self + where Self: FetchableRecord + { + try upsertAndFetch(db, as: Self.self) + } + + /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` + /// statement, and returns the inserted record. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let insertedPlayer = player.upsertAndFetch(db) + /// + /// - parameter db: A database connection. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + public func upsertAndFetch( + _ db: Database, + as returnedType: T.Type) + throws -> T + { + try willSave(db) + + var inserted: InsertionSuccess! + var returned: T! + try aroundSave(db) { + (inserted, returned) = try upsertAndFetchWithCallbacks( + db, selection: T.databaseSelection, + decode: { try T(row: $0) }) + return PersistenceSuccess(inserted) + } + + didSave(PersistenceSuccess(inserted)) + return returned + } +#else + /// Executes an `INSERT ... ON CONFLICT DO UPDATE` statement. + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func upsert(_ db: Database) throws { + try willSave(db) + + var saved: PersistenceSuccess! + try aroundSave(db) { + let inserted = try upsertWithCallbacks(db) + saved = PersistenceSuccess(inserted) + return saved + } + + didSave(saved) + } + + /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` + /// statement, and returns the inserted record. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let insertedPlayer = player.upsertAndFetch(db) + /// + /// - parameter db: A database connection. + /// - returns: The inserted record. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func upsertAndFetch(_ db: Database) throws -> Self + where Self: FetchableRecord + { + try upsertAndFetch(db, as: Self.self) + } + + /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` + /// statement, and returns the inserted record. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// let player: Player = ... + /// let insertedPlayer = player.upsertAndFetch(db) + /// + /// - parameter db: A database connection. + /// - parameter returnedType: The type of the returned record. + /// - returns: A record of type `returnedType`. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + public func upsertAndFetch( + _ db: Database, + as returnedType: T.Type) + throws -> T + { + try willSave(db) + + var inserted: InsertionSuccess! + var returned: T! + try aroundSave(db) { + (inserted, returned) = try upsertAndFetchWithCallbacks( + db, selection: T.databaseSelection, + decode: { try T(row: $0) }) + return PersistenceSuccess(inserted) + } + + didSave(PersistenceSuccess(inserted)) + return returned + } +#endif +} + +// MARK: - Internal + +extension PersistableRecord { + @inlinable // allow specialization so that empty callbacks are removed + func upsertWithCallbacks(_ db: Database) + throws -> InsertionSuccess + { + let (inserted, _) = try upsertAndFetchWithCallbacks( + db, selection: [], + decode: { _ in /* Nothing to decode */ }) + return inserted + } + + @inlinable // allow specialization so that empty callbacks are removed + func upsertAndFetchWithCallbacks( + _ db: Database, + selection: [any SQLSelectable], + decode: (Row) throws -> T) + throws -> (InsertionSuccess, T) + { + try willInsert(db) + + var inserted: InsertionSuccess! + var returned: T! + try aroundInsert(db) { + (inserted, returned) = try upsertAndFetchWithoutCallbacks( + db, selection: selection, + decode: decode) + return inserted + } + + didInsert(inserted) + return (inserted, returned) + } +} diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index a09a63995..a5c6b3119 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -1,913 +1,38 @@ -extension Database.ConflictResolution { - var invalidatesLastInsertedRowID: Bool { - switch self { - case .abort, .fail, .rollback, .replace: - return false - case .ignore: - // Statement may have succeeded without inserting any row - return true - } - } -} - -/// An error thrown by a type that adopts `MutablePersistableRecord`. -public enum PersistenceError: Error, CustomStringConvertible { - - /// Thrown by `MutablePersistableRecord.update(_:)` methods when no matching - /// row could be found in the database. - /// - /// - `databaseTableName`: the table of the unfound record - /// - `key`: the key of the unfound record (column and values) - case recordNotFound(databaseTableName: String, key: [String: DatabaseValue]) -} - -// CustomStringConvertible -extension PersistenceError { - /// :nodoc: - public var description: String { - switch self { - case let .recordNotFound(databaseTableName: databaseTableName, key: key): - let row = Row(key) // For nice output - return "Key not found in table \(databaseTableName): \(row.description)" - } - } -} - -/// The `MutablePersistableRecord` protocol uses this type in order to handle -/// SQLite conflicts when records are inserted or updated. +/// Types that adopt `PersistableRecord` can be inserted, updated, and deleted. /// -/// See `MutablePersistableRecord.persistenceConflictPolicy`. -/// -/// See -public struct PersistenceConflictPolicy { - /// The conflict resolution algorithm for insertions - public let conflictResolutionForInsert: Database.ConflictResolution +/// `PersistableRecord` has non-mutating variants of +/// `MutablePersistableRecord` methods. +public protocol PersistableRecord: MutablePersistableRecord { - /// The conflict resolution algorithm for updates - public let conflictResolutionForUpdate: Database.ConflictResolution + // MARK: Insertion Callbacks - /// Creates a policy - public init(insert: Database.ConflictResolution = .abort, update: Database.ConflictResolution = .abort) { - self.conflictResolutionForInsert = insert - self.conflictResolutionForUpdate = update - } -} - -/// Types that adopt `MutablePersistableRecord` can be inserted, updated, -/// and deleted. -public protocol MutablePersistableRecord: EncodableRecord, TableRecord { - /// The policy that handles SQLite conflicts when records are inserted - /// or updated. + /// Persistence callback called before the record is inserted. /// - /// This property is optional: its default value uses the ABORT policy - /// for both insertions and updates, and has GRDB generate regular - /// INSERT and UPDATE queries. + /// Default implementation does nothing. /// - /// If insertions are resolved with .ignore policy, the - /// `didInsert(with:for:)` method is not called upon successful insertion, - /// even if a row was actually inserted without any conflict. - /// - /// See - static var persistenceConflictPolicy: PersistenceConflictPolicy { get } + /// - note: If you need a mutating variant of this method, adopt the + /// ``MutablePersistableRecord`` protocol instead. + func willInsert(_ db: Database) throws - /// Notifies the record that it was successfully inserted. + /// Persistence callback called upon successful insertion. /// - /// Do not call this method directly: it is called for you, in a protected - /// dispatch queue, with the inserted RowID and the eventual - /// INTEGER PRIMARY KEY column name. + /// The default implementation does nothing. /// - /// This method is optional: the default implementation does nothing. + /// You can provide a custom implementation in order to grab the + /// auto-incremented id: /// - /// struct Player : MutablePersistableRecord { + /// class Player: PersistableRecord { /// var id: Int64? /// var name: String? /// - /// mutating func didInsert(with rowID: Int64, for column: String?) { - /// self.id = rowID + /// func didInsert(_ inserted: InsertionSuccess) { + /// id = inserted.rowID /// } /// } /// - /// - parameters: - /// - rowID: The inserted rowID. - /// - column: The name of the eventual INTEGER PRIMARY KEY column. - mutating func didInsert(with rowID: Int64, for column: String?) - - // MARK: - CRUD - - /// Executes an INSERT statement. + /// - note: If you need a mutating variant of this method, adopt the + /// ``MutablePersistableRecord`` protocol instead. /// - /// This method is guaranteed to have inserted a row in the database if it - /// returns without error. - /// - /// Upon successful insertion, the didInsert(with:for:) method - /// is called with the inserted RowID and the eventual INTEGER PRIMARY KEY - /// column name. - /// - /// This method has a default implementation, so your adopting types don't - /// have to implement it. Yet your types can provide their own - /// implementation of insert(). In their implementation, it is recommended - /// that they invoke the performInsert() method. - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError whenever an SQLite error occurs. - mutating func insert(_ db: Database) throws - - /// Executes an UPDATE statement. - /// - /// This method is guaranteed to have updated a row in the database if it - /// returns without error. - /// - /// This method has a default implementation, so your adopting types don't - /// have to implement it. Yet your types can provide their own - /// implementation of update(). In their implementation, it is recommended - /// that they invoke the performUpdate() method. - /// - /// - parameter db: A database connection. - /// - parameter columns: The columns to update. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. - func update(_ db: Database, columns: Set) throws - - /// Executes an INSERT or an UPDATE statement so that `self` is saved in - /// the database. - /// - /// If the receiver has a non-nil primary key and a matching row in the - /// database, this method performs an update. - /// - /// Otherwise, performs an insert. - /// - /// This method is guaranteed to have inserted or updated a row in the - /// database if it returns without error. - /// - /// This method has a default implementation, so your adopting types don't - /// have to implement it. Yet your types can provide their own - /// implementation of save(). In their implementation, it is recommended - /// that they invoke the performSave() method. - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError whenever an SQLite error occurs, or errors - /// thrown by update(). - mutating func save(_ db: Database) throws - - /// Executes a DELETE statement. - /// - /// This method has a default implementation, so your adopting types don't - /// have to implement it. Yet your types can provide their own - /// implementation of delete(). In their implementation, it is recommended - /// that they invoke the performDelete() method. - /// - /// - parameter db: A database connection. - /// - returns: Whether a database row was deleted. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @discardableResult - func delete(_ db: Database) throws -> Bool - - /// Returns true if and only if the primary key matches a row in - /// the database. - /// - /// This method has a default implementation, so your adopting types don't - /// have to implement it. Yet your types can provide their own - /// implementation of exists(). In their implementation, it is recommended - /// that they invoke the performExists() method. - /// - /// - parameter db: A database connection. - /// - returns: Whether the primary key matches a row in the database. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - func exists(_ db: Database) throws -> Bool -} - -extension MutablePersistableRecord { - /// Describes the conflict policy for insertions and updates. - /// - /// The default value specifies ABORT policy for both insertions and - /// updates, which has GRDB generate regular INSERT and UPDATE queries. - public static var persistenceConflictPolicy: PersistenceConflictPolicy { - PersistenceConflictPolicy(insert: .abort, update: .abort) - } - - /// Notifies the record that it was successfully inserted. - /// - /// The default implementation does nothing. - public mutating func didInsert(with rowID: Int64, for column: String?) { - } - - // MARK: - CRUD - - /// Executes an INSERT statement. - /// - /// The default implementation for insert() invokes performInsert(). - public mutating func insert(_ db: Database) throws { - try performInsert(db) - } - - /// Executes an INSERT statement so that `self` is saved in the database, - /// and return the inserted record. - /// - /// Usage: - /// - /// let player = Player(id: nil, name: "Arthur") - /// let insertedPlayer = try dbQueue.write { db in - /// try player.inserted(db) - /// } - /// print(player.id) // nil - /// print(insertedPlayer.id) // some id - public func inserted(_ db: Database) throws -> Self { - var result = self - try result.insert(db) - return result - } - - /// Executes an UPDATE statement. - /// - /// - parameter db: A database connection. - /// - parameter columns: The columns to update. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. - public func update(_ db: Database, columns: Set) throws { - try performUpdate(db, columns: columns) - } - - /// Executes an UPDATE statement. - /// - /// - parameter db: A database connection. - /// - parameter columns: The columns to update. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. - public func update(_ db: Database, columns: Sequence) - throws - where Sequence: Swift.Sequence, Sequence.Element: ColumnExpression - { - try update(db, columns: Set(columns.map(\.name))) - } - - /// Executes an UPDATE statement. - /// - /// - parameter db: A database connection. - /// - parameter columns: The columns to update. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. - public func update(_ db: Database, columns: Sequence) - throws - where Sequence: Swift.Sequence, Sequence.Element == String - { - try update(db, columns: Set(columns)) - } - - /// Executes an UPDATE statement that updates all table columns. - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. - public func update(_ db: Database) throws { - let databaseTableName = type(of: self).databaseTableName - let columns = try db.columns(in: databaseTableName) - try update(db, columns: Set(columns.map(\.name))) - } - - /// If the record has any difference from the other record, executes an - /// UPDATE statement so that those differences and only those difference are - /// saved in the database. - /// - /// This method is guaranteed to have saved the eventual differences in the - /// database if it returns without error. - /// - /// For example: - /// - /// if let oldPlayer = try Player.fetchOne(db, key: 42) { - /// var newPlayer = oldPlayer - /// newPlayer.score += 10 - /// newPlayer.hasAward = true - /// try newPlayer.updateChanges(db, from: oldRecord) - /// } - /// - /// - parameter db: A database connection. - /// - parameter record: The comparison record. - /// - returns: Whether the record had changes. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database and record could not be updated. - /// - SeeAlso: updateChanges(_:with:) - @discardableResult - public func updateChanges(_ db: Database, from record: Record) throws -> Bool { - try updateChanges(db, from: PersistenceContainer(db, record)) - } - - /// Mutates the record according to the provided closure, and then, if the - /// record has any difference from its previous version, executes an - /// UPDATE statement so that those differences and only those difference are - /// saved in the database. - /// - /// This method is guaranteed to have saved the eventual differences in the - /// database if it returns without error. - /// - /// For example: - /// - /// if var player = try Player.fetchOne(db, key: 42) { - /// try player.updateChanges(db) { - /// $0.score += 10 - /// $0.hasAward = true - /// } - /// } - /// - /// - parameter db: A database connection. - /// - parameter change: A closure that modifies the record. - /// - returns: Whether the record had changes. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database and record could not be updated. - @discardableResult - public mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool { - let container = try PersistenceContainer(db, self) - try change(&self) - return try updateChanges(db, from: container) - } - - /// Executes an INSERT or an UPDATE statement so that `self` is saved in - /// the database. - /// - /// The default implementation for save() invokes performSave(). - public mutating func save(_ db: Database) throws { - try performSave(db) - } - - /// Executes an INSERT or an UPDATE statement so that `self` is saved in - /// the database, and return the saved record. - /// - /// Usage: - /// - /// let player = Player(id: nil, name: "Arthur") - /// let savedPlayer = try dbQueue.write { db in - /// try player.saved(db) - /// } - /// print(player.id) // nil - /// print(savedPlayer.id) // some id - public func saved(_ db: Database) throws -> Self { - var result = self - try result.save(db) - return result - } - - /// Executes a DELETE statement. - /// - /// The default implementation for delete() invokes performDelete(). - @discardableResult - public func delete(_ db: Database) throws -> Bool { - try performDelete(db) - } - - /// Returns true if and only if the primary key matches a row in - /// the database. - /// - /// The default implementation for exists() invokes performExists(). - public func exists(_ db: Database) throws -> Bool { - try performExists(db) - } - - // MARK: - Record Comparison - - @discardableResult - fileprivate func updateChanges(_ db: Database, from container: PersistenceContainer) throws -> Bool { - let changes = try PersistenceContainer(db, self).changesIterator(from: container) - let changedColumns: Set = changes.reduce(into: []) { $0.insert($1.0) } - if changedColumns.isEmpty { - return false - } - try update(db, columns: changedColumns) - return true - } - - // MARK: - CRUD Internals - - /// Return a non-nil dictionary if record has a non-null primary key - func primaryKey(_ db: Database) throws -> [String: DatabaseValue]? { - let databaseTableName = type(of: self).databaseTableName - let primaryKeyInfo = try db.primaryKey(databaseTableName) - let container = try PersistenceContainer(db, self) - let primaryKey = Dictionary(uniqueKeysWithValues: primaryKeyInfo.columns.map { - ($0, container[caseInsensitive: $0]?.databaseValue ?? .null) - }) - if primaryKey.allSatisfy({ $0.value.isNull }) { - return nil - } - return primaryKey - } - - /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistableRecord. - /// - /// performInsert() provides the default implementation for insert(). Types - /// that adopt MutablePersistableRecord can invoke performInsert() in their - /// implementation of insert(). They should not provide their own - /// implementation of performInsert(). - public mutating func performInsert(_ db: Database) throws { - let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert - let dao = try DAO(db, self) - try dao.insertStatement(onConflict: conflictResolutionForInsert).execute() - - if !conflictResolutionForInsert.invalidatesLastInsertedRowID { - didInsert(with: db.lastInsertedRowID, for: dao.primaryKey.rowIDColumn) - } - } - - /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistableRecord. - /// - /// performUpdate() provides the default implementation for update(). Types - /// that adopt MutablePersistableRecord can invoke performUpdate() in their - /// implementation of update(). They should not provide their own - /// implementation of performUpdate(). - /// - /// - parameter db: A database connection. - /// - parameter columns: The columns to update. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. - public func performUpdate(_ db: Database, columns: Set) throws { - let dao = try DAO(db, self) - guard let statement = try dao.updateStatement( - columns: columns, - onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) - else { - // Nil primary key - throw dao.makeRecordNotFoundError() - } - try statement.execute() - if db.changesCount == 0 { - throw dao.makeRecordNotFoundError() - } - } - - /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistableRecord. - /// - /// performSave() provides the default implementation for save(). Types - /// that adopt MutablePersistableRecord can invoke performSave() in their - /// implementation of save(). They should not provide their own - /// implementation of performSave(). - /// - /// This default implementation forwards the job to `update` or `insert`. - public mutating func performSave(_ db: Database) throws { - // Call self.insert and self.update so that we support classes that - // override those methods. - if let key = try primaryKey(db) { - do { - try update(db) - } catch PersistenceError.recordNotFound(databaseTableName: type(of: self).databaseTableName, key: key) { - try insert(db) - } - } else { - try insert(db) - } - } - - /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistableRecord. - /// - /// performDelete() provides the default implementation for delete(). Types - /// that adopt MutablePersistableRecord can invoke performDelete() in - /// their implementation of delete(). They should not provide their own - /// implementation of performDelete(). - public func performDelete(_ db: Database) throws -> Bool { - guard let statement = try DAO(db, self).deleteStatement() else { - // Nil primary key - return false - } - try statement.execute() - return db.changesCount > 0 - } - - /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistableRecord. - /// - /// performExists() provides the default implementation for exists(). Types - /// that adopt MutablePersistableRecord can invoke performExists() in - /// their implementation of exists(). They should not provide their own - /// implementation of performExists(). - public func performExists(_ db: Database) throws -> Bool { - guard let statement = try DAO(db, self).existsStatement() else { - // Nil primary key - return false - } - return try Row.fetchOne(statement) != nil - } -} - -extension MutablePersistableRecord where Self: AnyObject { - - // MARK: - Record Comparison - - /// Mutates the record according to the provided closure, and then, if the - /// record has any difference from its previous version, executes an - /// UPDATE statement so that those differences and only those difference are - /// saved in the database. - /// - /// This method is guaranteed to have saved the eventual differences in the - /// database if it returns without error. - /// - /// For example: - /// - /// if let player = try Player.fetchOne(db, key: 42) { - /// try player.updateChanges(db) { - /// $0.score += 10 - /// $0.hasAward = true - /// } - /// } - /// - /// - parameter db: A database connection. - /// - parameter change: A closure that modifies the record. - /// - returns: Whether the record had changes. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database and record could not be updated. - @discardableResult - public func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool { - let container = try PersistenceContainer(db, self) - try change(self) - return try updateChanges(db, from: container) - } -} - -// MARK: - PersistableRecord - -/// Types that adopt `PersistableRecord` can be inserted, updated, and deleted. -/// -/// Unlike `MutablePersistableRecord`, the `insert(_:)` and `save(_:)` methods -/// are not mutating methods. -public protocol PersistableRecord: MutablePersistableRecord { - - /// Notifies the record that it was successfully inserted. - /// - /// Do not call this method directly: it is called for you, in a protected - /// dispatch queue, with the inserted RowID and the eventual - /// INTEGER PRIMARY KEY column name. - /// - /// This method is optional: the default implementation does nothing. - /// - /// If you need a mutating variant of this method, adopt the - /// MutablePersistableRecord protocol instead. - /// - /// - parameters: - /// - rowID: The inserted rowID. - /// - column: The name of the eventual INTEGER PRIMARY KEY column. - func didInsert(with rowID: Int64, for column: String?) - - /// Executes an INSERT statement. - /// - /// This method is guaranteed to have inserted a row in the database if it - /// returns without error. - /// - /// Upon successful insertion, the didInsert(with:for:) method - /// is called with the inserted RowID and the eventual INTEGER PRIMARY KEY - /// column name. - /// - /// This method has a default implementation, so your adopting types don't - /// have to implement it. Yet your types can provide their own - /// implementation of insert(). In their implementation, it is recommended - /// that they invoke the performInsert() method. - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError whenever an SQLite error occurs. - func insert(_ db: Database) throws - - /// Executes an INSERT or an UPDATE statement so that `self` is saved in - /// the database. - /// - /// If the receiver has a non-nil primary key and a matching row in the - /// database, this method performs an update. - /// - /// Otherwise, performs an insert. - /// - /// This method is guaranteed to have inserted or updated a row in the - /// database if it returns without error. - /// - /// This method has a default implementation, so your adopting types don't - /// have to implement it. Yet your types can provide their own - /// implementation of save(). In their implementation, it is recommended - /// that they invoke the performSave() method. - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError whenever an SQLite error occurs, or errors - /// thrown by update(). - func save(_ db: Database) throws -} - -extension PersistableRecord { - - /// Notifies the record that it was successfully inserted. - /// - /// The default implementation does nothing. - public func didInsert(with rowID: Int64, for column: String?) { - } - - // MARK: - Immutable CRUD - - /// Executes an INSERT statement. - /// - /// The default implementation for insert() invokes performInsert(). - public func insert(_ db: Database) throws { - try performInsert(db) - } - - /// Executes an INSERT or an UPDATE statement so that `self` is saved in - /// the database. - /// - /// The default implementation for save() invokes performSave(). - public func save(_ db: Database) throws { - try performSave(db) - } - - // MARK: - Immutable CRUD Internals - - /// Don't invoke this method directly: it is an internal method for types - /// that adopt PersistableRecord. - /// - /// performInsert() provides the default implementation for insert(). Types - /// that adopt PersistableRecord can invoke performInsert() in their - /// implementation of insert(). They should not provide their own - /// implementation of performInsert(). - public func performInsert(_ db: Database) throws { - let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert - let dao = try DAO(db, self) - try dao.insertStatement(onConflict: conflictResolutionForInsert).execute() - - if !conflictResolutionForInsert.invalidatesLastInsertedRowID { - didInsert(with: db.lastInsertedRowID, for: dao.primaryKey.rowIDColumn) - } - } - - /// Don't invoke this method directly: it is an internal method for types - /// that adopt PersistableRecord. - /// - /// performSave() provides the default implementation for save(). Types - /// that adopt PersistableRecord can invoke performSave() in their - /// implementation of save(). They should not provide their own - /// implementation of performSave(). - /// - /// This default implementation forwards the job to `update` or `insert`. - public func performSave(_ db: Database) throws { - // Call self.insert and self.update so that we support classes that - // override those methods. - if let key = try primaryKey(db) { - do { - try update(db) - } catch PersistenceError.recordNotFound(databaseTableName: type(of: self).databaseTableName, key: key) { - try insert(db) - } - } else { - try insert(db) - } - } -} - -// MARK: - DAO - -extension PersistenceContainer { - /// Convenience initializer from a database connection and a record - init(_ db: Database, _ record: Record) throws { - let databaseTableName = type(of: record).databaseTableName - let columnCount = try db.columns(in: databaseTableName).count - self.init(minimumCapacity: columnCount) - record.encode(to: &self) - } -} - -/// DAO takes care of PersistableRecord CRUD -final class DAO { - /// The database - let db: Database - - /// DAO keeps a copy the record's persistenceContainer, so that this - /// dictionary is built once whatever the database operation. It is - /// guaranteed to have at least one (key, value) pair. - let persistenceContainer: PersistenceContainer - - /// The table name - let databaseTableName: String - - /// The table primary key info - let primaryKey: PrimaryKeyInfo - - init(_ db: Database, _ record: Record) throws { - self.db = db - databaseTableName = type(of: record).databaseTableName - primaryKey = try db.primaryKey(databaseTableName) - persistenceContainer = try PersistenceContainer(db, record) - GRDBPrecondition(!persistenceContainer.isEmpty, "\(type(of: record)): invalid empty persistence container") - } - - func insertStatement(onConflict: Database.ConflictResolution) throws -> Statement { - let query = InsertQuery( - onConflict: onConflict, - tableName: databaseTableName, - insertedColumns: persistenceContainer.columns) - 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 - 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 { - persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null - } - if primaryKeyValues.allSatisfy({ $0.isNull }) { - return nil - } - - // Don't update columns not present in columns - // Don't update columns not present in the persistenceContainer - // Don't update primary key columns - let lowercaseUpdatedColumns = Set(columns.map { $0.lowercased() }) - .intersection(persistenceContainer.columns.map { $0.lowercased() }) - .subtracting(primaryKeyColumns.map { $0.lowercased() }) - - var updatedColumns: [String] = try db - .columns(in: databaseTableName) - .map(\.name) - .filter { lowercaseUpdatedColumns.contains($0.lowercased()) } - - if updatedColumns.isEmpty { - // IMPLEMENTATION NOTE - // - // It is important to update something, so that - // TransactionObserver can observe a change even though this - // change is useless. - // - // The goal is to be able to write tests with minimal tables, - // including tables made of a single primary key column. - updatedColumns = primaryKeyColumns - } - - let updatedValues = updatedColumns.map { - persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null - } - - let query = UpdateQuery( - onConflict: onConflict, - tableName: databaseTableName, - updatedColumns: updatedColumns, - conditionColumns: primaryKeyColumns) - 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 - func deleteStatement() throws -> Statement? { - // Fail early if primary key does not resolve to a database row. - let primaryKeyColumns = primaryKey.columns - let primaryKeyValues = primaryKeyColumns.map { - persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null - } - if primaryKeyValues.allSatisfy({ $0.isNull }) { - return nil - } - - let query = DeleteQuery( - tableName: databaseTableName, - conditionColumns: primaryKeyColumns) - let statement = try db.internalCachedStatement(sql: query.sql) - statement.setUncheckedArguments(StatementArguments(primaryKeyValues)) - return statement - } - - /// Returns nil if and only if primary key is nil - func existsStatement() throws -> Statement? { - // Fail early if primary key does not resolve to a database row. - let primaryKeyColumns = primaryKey.columns - let primaryKeyValues = primaryKeyColumns.map { - persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null - } - if primaryKeyValues.allSatisfy({ $0.isNull }) { - return nil - } - - let query = ExistsQuery( - tableName: databaseTableName, - conditionColumns: primaryKeyColumns) - let statement = try db.internalCachedStatement(sql: query.sql) - statement.setUncheckedArguments(StatementArguments(primaryKeyValues)) - return statement - } - - /// Throws a PersistenceError.recordNotFound error - func makeRecordNotFoundError() -> Error { - let key = Dictionary(uniqueKeysWithValues: primaryKey.columns.map { - ($0, persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null) - }) - return PersistenceError.recordNotFound( - databaseTableName: databaseTableName, - key: key) - } -} - - -// MARK: - InsertQuery - -private struct InsertQuery: Hashable { - let onConflict: Database.ConflictResolution - let tableName: String - let insertedColumns: [String] -} - -extension InsertQuery { - @ReadWriteBox private static var sqlCache: [InsertQuery: String] = [:] - var sql: String { - if let sql = Self.sqlCache[self] { - return sql - } - let columnsSQL = insertedColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", ") - let valuesSQL = databaseQuestionMarks(count: insertedColumns.count) - let sql: String - switch onConflict { - case .abort: - sql = """ - INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ - VALUES (\(valuesSQL)) - """ - default: - sql = """ - INSERT OR \(onConflict.rawValue) \ - INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ - VALUES (\(valuesSQL)) - """ - } - Self.sqlCache[self] = sql - return sql - } -} - - -// MARK: - UpdateQuery - -private struct UpdateQuery: Hashable { - let onConflict: Database.ConflictResolution - let tableName: String - let updatedColumns: [String] - let conditionColumns: [String] -} - -extension UpdateQuery { - @ReadWriteBox private static var sqlCache: [UpdateQuery: String] = [:] - var sql: String { - if let sql = Self.sqlCache[self] { - return sql - } - let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ", ") - let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ") - let sql: String - switch onConflict { - case .abort: - sql = """ - UPDATE \(tableName.quotedDatabaseIdentifier) \ - SET \(updateSQL) \ - WHERE \(whereSQL) - """ - default: - sql = """ - UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) \ - SET \(updateSQL) \ - WHERE \(whereSQL) - """ - } - Self.sqlCache[self] = sql - return sql - } -} - - -// MARK: - DeleteQuery - -private struct DeleteQuery { - let tableName: String - let conditionColumns: [String] -} - -extension DeleteQuery { - var sql: String { - let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ") - return "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL)" - } -} - - -// MARK: - ExistsQuery - -private struct ExistsQuery { - let tableName: String - let conditionColumns: [String] -} - -extension ExistsQuery { - var sql: String { - let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ") - return "SELECT 1 FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL)" - } + /// - parameter inserted: Information about the inserted row. + func didInsert(_ inserted: InsertionSuccess) } diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index e1a1c882c..be2b873bb 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -11,7 +11,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { } /// Creates a Record from a row. - public required init(row: Row) { + public required init(row: Row) throws { if row.isFetched { // Take care of the hasDatabaseChanges flag. // @@ -47,13 +47,8 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// The policy that handles SQLite conflicts when records are inserted /// or updated. /// - /// This property is optional: its default value uses the ABORT policy - /// for both insertions and updates, and has GRDB generate regular - /// INSERT and UPDATE queries. - /// - /// If insertions are resolved with .ignore policy, the - /// `didInsert(with:for:)` method is not called upon successful insertion, - /// even if a row was actually inserted without any conflict. + /// The default implementation uses the ABORT policy for both insertions and + /// updates, and has GRDB generate regular INSERT and UPDATE queries. /// /// See open class var persistenceConflictPolicy: PersistenceConflictPolicy { @@ -71,7 +66,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// of columns: /// /// class RestrictedPlayer : Record { - /// override static var databaseSelection: [SQLSelectable] { + /// override static var databaseSelection: [any SQLSelectable] { /// return [Column("id"), Column("name")] /// } /// } @@ -82,21 +77,21 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// You can also add extra columns such as the `rowid` column: /// /// class ExtendedPlayer : Player { - /// override static var databaseSelection: [SQLSelectable] { + /// override static var databaseSelection: [any SQLSelectable] { /// return [AllColumns(), Column.rowID] /// } /// } /// /// // SELECT *, rowid FROM player /// try ExtendedPlayer.fetchAll(db) - open class var databaseSelection: [SQLSelectable] { + open class var databaseSelection: [any SQLSelectable] { [AllColumns()] } /// Defines the values persisted in the database. /// - /// Store in the *container* argument all values that should be stored in + /// Store in the *container* parameter all values that should be stored in /// the columns of the database table (see Record.databaseTableName()). /// /// Primary key columns, if any, must be included. @@ -105,7 +100,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// var id: Int64? /// var name: String? /// - /// override func encode(to container: inout PersistenceContainer) { + /// override func encode(to container: inout PersistenceContainer) throws { /// container["id"] = id /// container["name"] = name /// } @@ -113,48 +108,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// /// The implementation of the base class Record does not store any value in /// the container. - open func encode(to container: inout PersistenceContainer) { - } - - /// Notifies the record that it was successfully inserted. - /// - /// Do not call this method directly: it is called for you, in a protected - /// dispatch queue, with the inserted RowID and the eventual - /// INTEGER PRIMARY KEY column name. - /// - /// The implementation of the base Record class does nothing. - /// - /// class Player : Record { - /// var id: Int64? - /// var name: String? - /// - /// func didInsert(with rowID: Int64, for column: String?) { - /// id = rowID - /// } - /// } - /// - /// - parameters: - /// - rowID: The inserted rowID. - /// - column: The name of the eventual INTEGER PRIMARY KEY column. - open func didInsert(with rowID: Int64, for column: String?) { - } - - - // MARK: - Copy - - /// Returns a copy of `self`, initialized from all values encoded in the - /// `encode(to:)` method. - /// - /// The eventual primary key is copied, as well as the - /// `hasDatabaseChanges` flag. - /// - /// - returns: A copy of self. - open func copy() -> Self { - let copy = type(of: self).init(row: Row(self)) - copy.referenceRow = referenceRow - return copy - } - + open func encode(to container: inout PersistenceContainer) throws { } // MARK: - Compare with Previous Versions @@ -175,8 +129,12 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// false does not prevent it from turning true on subsequent modifications /// of the record. public var hasDatabaseChanges: Bool { - get { databaseChangesIterator().next() != nil } - set { referenceRow = newValue ? nil : Row(self) } + do { + return try databaseChangesIterator().next() != nil + } catch { + // Can't encode the record: surely it can't be saved. + return true + } } /// A dictionary of changes that have not been saved. @@ -188,15 +146,35 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// are nil. /// /// See `hasDatabaseChanges` for more information. + /// + /// - throws: An error is thrown if the record can't be encoded to its + /// database representation. public var databaseChanges: [String: DatabaseValue?] { - Dictionary(uniqueKeysWithValues: databaseChangesIterator()) + get throws { + try Dictionary(uniqueKeysWithValues: databaseChangesIterator()) + } + } + + /// Sets hasDatabaseChanges to true + private func setHasDatabaseChanges() { + referenceRow = nil + } + + /// Sets hasDatabaseChanges to false + private func resetDatabaseChanges() throws { + referenceRow = try Row(self) + } + + /// Sets hasDatabaseChanges to false + private func resetDatabaseChanges(with persistenceContainer: PersistenceContainer) { + referenceRow = Row(persistenceContainer) } // A change iterator that is used by both hasDatabaseChanges and // persistentChangedValues properties. - private func databaseChangesIterator() -> AnyIterator<(String, DatabaseValue?)> { + private func databaseChangesIterator() throws -> AnyIterator<(String, DatabaseValue?)> { let oldRow = referenceRow - var newValueIterator = PersistenceContainer(self).makeIterator() + var newValueIterator = try PersistenceContainer(self).makeIterator() return AnyIterator { // Loop until we find a change, or exhaust columns: while let (column, newValue) = newValueIterator.next() { @@ -216,80 +194,180 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// Reference row for the *hasDatabaseChanges* property. var referenceRow: Row? + // MARK: Persistence Callbacks + + /// Called before the record is inserted. + /// + /// If you override this method, you must call `super` at some point in + /// your implementation. + /// + /// - parameter db: A database connection. + open func willInsert(_ db: Database) throws { } + + /// Called around the record insertion. + /// + /// If you override this method, you must call `super` at some point in + /// your implementation (this calls the `insert` parameter). + /// + /// For example: + /// + /// class Player: Record { + /// func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + /// print("Player will insert") + /// try super.aroundInsert(db, insert: insert) + /// print("Player did insert") + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter insert: A function that inserts the record, and returns + /// information about the inserted row. + open func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + let inserted = try insert() + resetDatabaseChanges(with: inserted.persistenceContainer) + } + + /// Called upon successful insertion. + /// + /// You can override this method in order to grab the auto-incremented id: + /// + /// class Player: Record { + /// var id: Int64? + /// var name: String + /// + /// override func didInsert(_ inserted: InsertionSuccess) { + /// super.didInsert(inserted) + /// id = inserted.rowID + /// } + /// } + /// + /// If you override this method, you must call `super` at some point in + /// your implementation. + /// + /// - parameter inserted: Information about the inserted row. + open func didInsert(_ inserted: InsertionSuccess) { } + + /// Called before the record is updated. + /// + /// If you override this method, you must call `super` at some point in + /// your implementation. + /// + /// - parameter db: A database connection. + open func willUpdate(_ db: Database, columns: Set) throws { } + + // swiftlint:disable line_length + /// Called around the record update. + /// + /// If you override this method, you must call `super` at some point in + /// your implementation (this calls the `update` parameter). + /// + /// For example: + /// + /// class Player: Record { + /// override func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + /// print("Player will update") + /// try super.aroundUpdate(db, columns: columns, update: update) + /// print("Player did update") + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter columns: The updated columns. + /// - parameter update: A function that updates the record. Its result is + /// reserved for GRDB usage. + open func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + let updated = try update() + resetDatabaseChanges(with: updated.persistenceContainer) + } + // swiftlint:enable line_length + + /// Called upon successful update. + /// + /// If you override this method, you must call `super` at some point in + /// your implementation. + /// + /// - parameter updated: Reserved for GRDB usage. + open func didUpdate(_ updated: PersistenceSuccess) { } + + /// Called before the record is updated or inserted. + /// + /// If you override this method, you must call `super` at some point in + /// your implementation. + /// + /// - parameter db: A database connection. + open func willSave(_ db: Database) throws { } + + /// Called around the record update or insertion. + /// + /// If you override this method, you must call `super` at some point in + /// your implementation (this calls the `update` parameter). + /// + /// For example: + /// + /// class Player: Record { + /// override func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + /// print("Player will save") + /// try super.aroundSave(db, save: save) + /// print("Player did save") + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter update: A function that updates the record. Its result is + /// reserved for GRDB usage. + open func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + _ = try save() + } + + /// Called upon successful update or insertion. + /// + /// If you override this method, you must call `super` at some point in + /// your implementation. + /// + /// - parameter saved: Reserved for GRDB usage. + open func didSave(_ saved: PersistenceSuccess) { } + + /// Called before the record is deleted. + /// + /// If you override this method, you must call `super` at some point in + /// your implementation. + /// + /// - parameter db: A database connection. + open func willDelete(_ db: Database) throws { } + + /// Called around the destruction of the record. + /// + /// If you override this method, you must call `super` at some point in + /// your implementation (this calls the `delete` parameter). + /// + /// For example: + /// + /// class Player: Record { + /// override func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + /// print("Player will delete") + /// try super.aroundDelete(db, delete: delete) + /// print("Player did delete") + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter delete: A function that deletes the record and returns + /// whether a row was deleted in the database. + open func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + _ = try delete() + setHasDatabaseChanges() + } + + /// Called upon successful deletion. + /// + /// If you override this method, you must call `super` at some point in + /// your implementation. + /// + /// - parameter deleted: Whether a row was deleted in the database. + open func didDelete(deleted: Bool) { } // MARK: - CRUD - /// Executes an INSERT statement. - /// - /// On success, this method sets the *hasDatabaseChanges* flag to false. - /// - /// This method is guaranteed to have inserted a row in the database if it - /// returns without error. - /// - /// Records whose primary key is declared as "INTEGER PRIMARY KEY" have - /// their id automatically set after successful insertion, if it was nil - /// before the insertion. - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError whenever an SQLite error occurs. - open func insert(_ db: Database) throws { - let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert - let dao = try DAO(db, self) - var persistenceContainer = dao.persistenceContainer - try dao.insertStatement(onConflict: conflictResolutionForInsert).execute() - - if !conflictResolutionForInsert.invalidatesLastInsertedRowID { - let rowID = db.lastInsertedRowID - let rowIDColumn = dao.primaryKey.rowIDColumn - didInsert(with: rowID, for: rowIDColumn) - - // Update persistenceContainer with inserted id, so that we can - // set hasDatabaseChanges to false: - if let rowIDColumn = rowIDColumn { - persistenceContainer[caseInsensitive: rowIDColumn] = rowID - } - } - - // Set hasDatabaseChanges to false - referenceRow = Row(persistenceContainer) - } - - /// Executes an UPDATE statement. - /// - /// On success, this method sets the *hasDatabaseChanges* flag to false. - /// - /// This method is guaranteed to have updated a row in the database if it - /// returns without error. - /// - /// - parameter db: A database connection. - /// - parameter columns: The columns to update. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database and record could not be updated. - open func update(_ db: Database, columns: Set) throws { - // The simplest code would be: - // - // try performUpdate(db, columns: columns) - // hasDatabaseChanges = false - // - // But this would trigger two calls to `encode(to:)`. - let dao = try DAO(db, self) - guard let statement = try dao.updateStatement( - columns: columns, - onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) - else { - // Nil primary key - throw dao.makeRecordNotFoundError() - } - try statement.execute() - if db.changesCount == 0 { - throw dao.makeRecordNotFoundError() - } - - // Set hasDatabaseChanges to false - referenceRow = Row(dao.persistenceContainer) - } - /// If the record has been changed, executes an UPDATE statement so that /// those changes and only those changes are saved in the database. /// @@ -306,7 +384,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// match any row in the database and record could not be updated. @discardableResult public final func updateChanges(_ db: Database) throws -> Bool { - let changedColumns = Set(databaseChanges.keys) + let changedColumns = try Set(databaseChanges.keys) if changedColumns.isEmpty { return false } else { @@ -314,45 +392,4 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { return true } } - - /// Executes an INSERT or an UPDATE statement so that `self` is saved in - /// the database. - /// - /// If the record has a non-nil primary key and a matching row in the - /// database, this method performs an update. - /// - /// Otherwise, performs an insert. - /// - /// On success, this method sets the *hasDatabaseChanges* flag to false. - /// - /// This method is guaranteed to have inserted or updated a row in the - /// database if it returns without error. - /// - /// You can't override this method. Instead, override `insert(_:)` - /// or `update(_:columns:)`. - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError whenever an SQLite error occurs, or errors - /// thrown by update(). - public final func save(_ db: Database) throws { - try performSave(db) - } - - /// Executes a DELETE statement. - /// - /// On success, this method sets the *hasDatabaseChanges* flag to true. - /// - /// - parameter db: A database connection. - /// - returns: Whether a database row was deleted. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @discardableResult - open func delete(_ db: Database) throws -> Bool { - defer { - // Future calls to update() will throw NotFound. Make the user - // a favor and make sure this error is thrown even if she checks the - // hasDatabaseChanges flag: - hasDatabaseChanges = true - } - return try performDelete(db) - } } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 1e14454ff..0ab4f951f 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -41,12 +41,12 @@ public protocol TableRecord { /// /// struct ExtendedPlayer : TableRecord { /// static var databaseTableName = "player" - /// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + /// static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] /// } /// /// // SELECT *, rowid FROM player /// try ExtendedPlayer.fetchAll(db) - static var databaseSelection: [SQLSelectable] { get } + static var databaseSelection: [any SQLSelectable] { get } } extension TableRecord { @@ -91,7 +91,7 @@ extension TableRecord { } /// Default value: `[AllColumns()]`. - public static var databaseSelection: [SQLSelectable] { + public static var databaseSelection: [any SQLSelectable] { [AllColumns()] } } @@ -144,10 +144,10 @@ extension TableRecord { extension TableRecord { - /// Deletes all records; returns the number of deleted rows. + /// Deletes all records, and returns the number of deleted records. /// /// - parameter db: A database connection. - /// - returns: The number of deleted rows + /// - returns: The number of deleted records /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @discardableResult public static func deleteAll(_ db: Database) throws -> Int { @@ -158,7 +158,7 @@ extension TableRecord { // MARK: - Check Existence by Single-Column Primary Key extension TableRecord { - /// Returns whether a row exists for this primary key. + /// Returns whether a record exists for this primary key. /// /// try Player.exists(db, key: 123) /// try Country.exists(db, key: "FR") @@ -171,18 +171,15 @@ extension TableRecord { /// - parameters: /// - db: A database connection. /// - key: A primary key value. - /// - returns: Whether a row exists for this primary key. - public static func exists(_ db: Database, key: PrimaryKeyType) - throws -> Bool - where PrimaryKeyType: DatabaseValueConvertible - { + /// - returns: Whether a record exists for this primary key. + public static func exists(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { try !filter(key: key).isEmpty(db) } } @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { - /// Returns whether a row exists for this primary key. + /// Returns whether a record exists for this primary key. /// /// try Player.deleteOne(db, id: 123) /// try Country.deleteOne(db, id: "FR") @@ -195,50 +192,29 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// - parameters: /// - db: A database connection. /// - id: A primary key value. - /// - returns: Whether a row exists for this primary key. + /// - returns: Whether a record exists for this primary key. public static func exists(_ db: Database, id: ID) throws -> Bool { - try !filter(id: id).isEmpty(db) - } -} - -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) -extension TableRecord -where Self: Identifiable, - ID: _OptionalProtocol, - ID.Wrapped: DatabaseValueConvertible -{ - /// Returns whether a row exists for this primary key. - /// - /// try Player.deleteOne(db, id: 123) - /// try Country.deleteOne(db, id: "FR") - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// try Document.deleteOne(db, id: 1) - /// - /// - parameters: - /// - db: A database connection. - /// - id: A primary key value. - /// - returns: Whether a row exists for this primary key. - public static func exists(_ db: Database, id: ID.Wrapped) throws -> Bool { - try !filter(id: id).isEmpty(db) + if id.databaseValue.isNull { + // Don't hit the database + return false + } + return try !filter(id: id).isEmpty(db) } } // MARK: - Check Existence by Key extension TableRecord { - /// Returns whether a row exists for this unique key (primary key or any key - /// with a unique index on it). + /// Returns whether a record exists for this unique key (primary key or any + /// key with a unique index on it). /// /// try Player.exists(db, key: ["name": Arthur"]) /// /// - parameters: /// - db: A database connection. /// - key: A dictionary of values. - /// - returns: Whether a row exists for this key. - public static func exists(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + /// - returns: Whether a record exists for this key. + public static func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try !filter(key: key).isEmpty(db) } } @@ -247,8 +223,8 @@ extension TableRecord { extension TableRecord { - /// Delete records identified by their primary keys; returns the number of - /// deleted rows. + /// Delete records identified by their primary keys, and returns the number + /// of deleted records. /// /// // DELETE FROM player WHERE id IN (1, 2, 3) /// try Player.deleteAll(db, keys: [1, 2, 3]) @@ -265,11 +241,10 @@ extension TableRecord { /// - parameters: /// - db: A database connection. /// - keys: A sequence of primary keys. - /// - returns: The number of deleted rows + /// - returns: The number of deleted records @discardableResult - public static func deleteAll(_ db: Database, keys: Sequence) + public static func deleteAll(_ db: Database, keys: some Sequence) throws -> Int - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { @@ -279,8 +254,8 @@ extension TableRecord { return try filter(keys: keys).deleteAll(db) } - /// Delete a record, identified by its primary key; returns whether a - /// database row was deleted. + /// Delete a record, identified by its primary key, and returns whether a + /// record was deleted. /// /// // DELETE FROM player WHERE id = 123 /// try Player.deleteOne(db, key: 123) @@ -297,14 +272,11 @@ extension TableRecord { /// - parameters: /// - db: A database connection. /// - key: A primary key value. - /// - returns: Whether a database row was deleted. + /// - returns: Whether a record 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 + public static func deleteOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { + if key.databaseValue.isNull { + // Don't hit the database return false } return try deleteAll(db, keys: [key]) > 0 @@ -313,8 +285,8 @@ extension TableRecord { @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 records identified by their primary keys, and returns the number + /// of deleted records. /// /// // DELETE FROM player WHERE id IN (1, 2, 3) /// try Player.deleteAll(db, ids: [1, 2, 3]) @@ -331,12 +303,9 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// - parameters: /// - db: A database connection. /// - ids: A collection of primary keys. - /// - returns: The number of deleted rows + /// - returns: The number of deleted records @discardableResult - public static func deleteAll(_ db: Database, ids: Collection) - throws -> Int - where Collection: Swift.Collection, Collection.Element == ID - { + public static func deleteAll(_ db: Database, ids: some Collection) throws -> Int { if ids.isEmpty { // Avoid hitting the database return 0 @@ -344,8 +313,8 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { return try filter(ids: ids).deleteAll(db) } - /// Delete a record, identified by its primary key; returns whether a - /// database row was deleted. + /// Delete a record, identified by its primary key, and returns whether a + /// record was deleted. /// /// // DELETE FROM player WHERE id = 123 /// try Player.deleteOne(db, id: 123) @@ -362,89 +331,28 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// - parameters: /// - db: A database connection. /// - id: A primary key value. - /// - returns: Whether a database row was deleted. + /// - returns: Whether a record 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. + /// any key with a unique index on it), and returns the number of + /// deleted records. /// /// 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 + /// - returns: The number of deleted records @discardableResult - public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int { + public static func deleteAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Int { if keys.isEmpty { // Avoid hitting the database return 0 @@ -453,16 +361,17 @@ extension TableRecord { } /// 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. + /// with a unique index on it), and returns whether a database record + /// 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. + /// - returns: Whether a record was deleted. @discardableResult - public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + public static func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try deleteAll(db, keys: [key]) > 0 } } @@ -471,7 +380,7 @@ extension TableRecord { extension TableRecord { - /// Updates all records; returns the number of updated records. + /// Updates all records, and returns the number of updated records. /// /// For example: /// @@ -484,7 +393,7 @@ extension TableRecord { /// - 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. + /// - returns: The number of updated records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @discardableResult public static func updateAll( @@ -496,7 +405,7 @@ extension TableRecord { try all().updateAll(db, onConflict: conflictResolution, assignments) } - /// Updates all records; returns the number of updated records. + /// Updates all records, and returns the number of updated records. /// /// For example: /// @@ -508,19 +417,17 @@ extension TableRecord { /// - 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. + /// - parameter assignments: Column assignments. + /// - returns: The number of updated records. /// - 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...) + _ assignments: ColumnAssignment...) throws -> Int { - try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments) + try updateAll(db, onConflict: conflictResolution, assignments) } } diff --git a/GRDB/Utils/Inflections.swift b/GRDB/Utils/Inflections.swift index af1f05fd3..5302926c2 100644 --- a/GRDB/Utils/Inflections.swift +++ b/GRDB/Utils/Inflections.swift @@ -3,7 +3,7 @@ import Foundation extension String { /// "player" -> "Player" var uppercasingFirstCharacter: String { - guard let first = first else { + guard let first else { return self } return String(first).uppercased() + dropFirst() diff --git a/GRDB/Utils/LockedBox.swift b/GRDB/Utils/LockedBox.swift index 37e3f0bbf..f9c72785a 100644 --- a/GRDB/Utils/LockedBox.swift +++ b/GRDB/Utils/LockedBox.swift @@ -17,12 +17,31 @@ final class LockedBox { _wrappedValue = wrappedValue } + /// Runs the provided closure while holding a lock on the value. + /// + /// For example: + /// + /// // Prints "0" + /// @LockedBox var count = 0 + /// $count.read { print($0) } + /// + /// - parameter block: A closure that accepts the value. func read(_ block: (T) throws -> U) rethrows -> U { lock.lock() defer { lock.unlock() } return try block(_wrappedValue) } + /// Runs the provided closure while holding a lock on the value. + /// + /// For example: + /// + /// // Prints "1" + /// @LockedBox var count = 0 + /// $count.update { $0 += 1 } + /// print(count) + /// + /// - parameter block: A closure that can modify the value. func update(_ block: (inout T) throws -> U) rethrows -> U { lock.lock() defer { lock.unlock() } diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index 3bd60eaf2..c4e1f0ccb 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -114,11 +114,10 @@ struct OrderedDictionary { return OrderedDictionary(keys: keys, dictionary: dictionary) } - mutating func merge( - _ other: S, + mutating func merge( + _ other: some Sequence<(Key, Value)>, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows - where S: Sequence, S.Element == (Key, Value) { for (key, value) in other { if let current = self[key] { @@ -129,11 +128,10 @@ struct OrderedDictionary { } } - mutating func merge( - _ other: S, + mutating func merge( + _ other: some Sequence<(key: Key, value: Value)>, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows - where S: Sequence, S.Element == (key: Key, value: Value) { for (key, value) in other { if let current = self[key] { @@ -144,22 +142,20 @@ struct OrderedDictionary { } } - func merging( - _ other: S, + func merging( + _ other: some Sequence<(Key, Value)>, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows -> OrderedDictionary - where S: Sequence, S.Element == (Key, Value) { var result = self try result.merge(other, uniquingKeysWith: combine) return result } - func merging( - _ other: S, + func merging( + _ other: some Sequence<(key: Key, value: Value)>, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows -> OrderedDictionary - where S: Sequence, S.Element == (key: Key, value: Value) { var result = self try result.merge(other, uniquingKeysWith: combine) diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index f42e0f2ce..49ef225c5 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -20,24 +20,6 @@ public func databaseQuestionMarks(count: Int) -> String { repeatElement("?", count: count).joined(separator: ",") } -/// This protocol is an implementation detail of GRDB. Don't use it. -/// -/// :nodoc: -public protocol _OptionalProtocol { - associatedtype Wrapped -} - -/// This conformance is an implementation detail of GRDB. Don't rely on it. -/// -/// :nodoc: -extension Optional: _OptionalProtocol { } - -#if swift(>=5.6) && canImport(_Concurrency) -public typealias GRDBSendable = Swift.Sendable -#else -public typealias GRDBSendable = Any -#endif - // MARK: - Internal /// Reserved for GRDB: do not use. diff --git a/GRDB/ValueObservation/DatabaseCancellable.swift b/GRDB/ValueObservation/DatabaseCancellable.swift index f58ecd2b8..079b08e9f 100644 --- a/GRDB/ValueObservation/DatabaseCancellable.swift +++ b/GRDB/ValueObservation/DatabaseCancellable.swift @@ -19,8 +19,8 @@ public class AnyDatabaseCancellable: DatabaseCancellable { /// Creates a cancellable object that forwards cancellation to the /// provided cancellable. - public convenience init(_ cancellable: DatabaseCancellable) { - var cancellable: DatabaseCancellable? = cancellable + public convenience init(_ cancellable: some DatabaseCancellable) { + var cancellable = Optional.some(cancellable) self.init { cancellable?.cancel() cancellable = nil // Release memory diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index 8ef622ba9..f9305ab94 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -60,7 +60,7 @@ extension ValueObservation { /// /// let cancellable = try sharedObservation.start( /// onError: { error in ... }, - /// onChange: { players: [Player] in + /// onChange: { (players: [Player]) in /// print("fresh players: \(players)") /// }) /// // <- here "fresh players" is already printed. @@ -79,7 +79,7 @@ extension ValueObservation { /// - parameter extent: The extent of the shared database observation. /// - returns: A `SharedValueObservation` public func shared( - in reader: DatabaseReader, + in reader: some DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), extent: SharedValueObservationExtent = .whileObserved) -> SharedValueObservation @@ -103,7 +103,7 @@ extension ValueObservation { /// /// let cancellable = try sharedObservation.start( /// onError: { error in ... }, -/// onChange: { players: [Player] in +/// onChange: { (players: [Player]) in /// print("Players have changed.") /// }) /// @@ -164,7 +164,7 @@ public final class SharedValueObservation { /// /// let cancellable = try sharedObservation.start( /// onError: { error in ... }, - /// onChange: { players: [Player] in + /// onChange: { (players: [Player]) in /// print("fresh players: \(players)") /// }) /// @@ -175,7 +175,7 @@ public final class SharedValueObservation { public func start( onError: @escaping (Error) -> Void, onChange: @escaping (Element) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { synchronized { // Support for reentrancy: a shared immediate observation is @@ -194,7 +194,7 @@ public final class SharedValueObservation { // Side effect if needsStart { // Self retains the cancellable, so don't have the cancellable retain self. - cancellable = AnyDatabaseCancellable(startObservation( + cancellable = startObservation( // onError { [weak self] error in self?.handleError(error) @@ -202,7 +202,7 @@ public final class SharedValueObservation { // onChange { [weak self] element in self?.handleChange(element) - })) + }) } else if let result = lastResult { // Notify last result as an initial value scheduler.scheduleInitial { @@ -234,7 +234,7 @@ public final class SharedValueObservation { /// /// let cancellable = publisher.sink( /// receiveCompletion: { completion in ... }, - /// receiveValue: { players: [Player] in + /// receiveValue: { (players: [Player]) in /// print("fresh players: \(players)") /// }) /// @@ -299,7 +299,6 @@ public final class SharedValueObservation { } } -#if compiler(>=5.6) && canImport(_Concurrency) extension SharedValueObservation { // MARK: - Asynchronous Observation /// The database observation, as an asynchronous sequence of @@ -315,4 +314,3 @@ extension SharedValueObservation { } } } -#endif diff --git a/GRDB/ValueObservation/ValueConcurrentObserver.swift b/GRDB/ValueObservation/ValueConcurrentObserver.swift index 57728ea2f..9a6a5588c 100644 --- a/GRDB/ValueObservation/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/ValueConcurrentObserver.swift @@ -191,12 +191,11 @@ final class ValueConcurrentObserver { // `WALSnapshot` class. extension ValueConcurrentObserver { // Starts the observation - func start() -> DatabaseCancellable { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let (notificationCallbacksOpt, databaseAccessOpt) = lock.synchronized { + func start() -> AnyDatabaseCancellable { + let (notificationCallbacks, databaseAccess) = lock.synchronized { (self.notificationCallbacks, self.databaseAccess) } - guard let notificationCallbacks = notificationCallbacksOpt, let databaseAccess = databaseAccessOpt else { + guard let notificationCallbacks, let databaseAccess else { // Likely a GRDB bug: during a synchronous start, user is not // able to cancel observation. fatalError("can't start a cancelled or failed observation") @@ -280,8 +279,8 @@ extension ValueConcurrentObserver { } // Reduce - let initialValue: Reducer.Value = reduceQueue.sync { - guard let initialValue = reducer._value(fetchedValue) else { + let initialValue = try reduceQueue.sync { + guard let initialValue = try reducer._value(fetchedValue) else { fatalError("Broken contract: reducer has no initial value") } return initialValue @@ -345,16 +344,19 @@ extension ValueConcurrentObserver { let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } guard isNotifying else { return /* Cancelled */ } - guard let initialValue = self.reducer._value(fetchedValue) else { - fatalError("Broken contract: reducer has no initial value") - } - - // Notify - self.scheduler.schedule { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange } - guard let onChange = onChangeOpt else { return /* Cancelled */ } - onChange(initialValue) + do { + guard let initialValue = try self.reducer._value(fetchedValue) else { + fatalError("Broken contract: reducer has no initial value") + } + + // Notify + self.scheduler.schedule { + let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } + guard let onChange else { return /* Cancelled */ } + onChange(initialValue) + } + } catch { + self.notifyError(error) } } @@ -380,9 +382,8 @@ extension ValueConcurrentObserver { initialRegion: DatabaseRegion) { databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let eventsOpt = self.lock.synchronized { self.notificationCallbacks?.events } - guard let events = eventsOpt else { return /* Cancelled */ } + let events = self.lock.synchronized { self.notificationCallbacks?.events } + guard let events else { return /* Cancelled */ } do { var observedRegion = initialRegion @@ -393,8 +394,8 @@ extension ValueConcurrentObserver { // database versions. It prevents database checkpointing, // and keeps WAL snapshots (`sqlite3_snapshot`) valid // and comparable. - let isModified: Bool = withExtendedLifetime(initialSnapshot) { - guard let initialWALSnapshot = initialWALSnapshot, + let isModified = withExtendedLifetime(initialSnapshot) { + guard let initialWALSnapshot, let currentWALSnapshot = WALSnapshot(writerDB) else { return true @@ -438,16 +439,23 @@ extension ValueConcurrentObserver { let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } guard isNotifying else { return /* Cancelled */ } - let value = self.reducer._value(fetchedValue) - - // Notify - if let value = value { - self.scheduler.schedule { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange } - guard let onChange = onChangeOpt else { return /* Cancelled */ } - onChange(value) + do { + let value = try self.reducer._value(fetchedValue) + + // Notify + if let value = value { + self.scheduler.schedule { + let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } + guard let onChange else { return /* Cancelled */ } + onChange(value) + } } + } catch { + let dbPool = self.lock.synchronized { self.databaseAccess?.dbPool } + dbPool?.asyncWriteWithoutTransaction { writerDB in + self.stopDatabaseObservation(writerDB) + } + self.notifyError(error) } } } else { @@ -489,13 +497,12 @@ extension ValueConcurrentObserver: TransactionObserver { // Reset the isModified flag until next transaction observationState.isModified = false - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ // Ignore transaction unless we are still notifying database events, and // we can still access the database. - let (eventsOpt, databaseAccessOpt) = lock.synchronized { + let (events, databaseAccess) = lock.synchronized { (notificationCallbacks?.events, self.databaseAccess) } - guard let events = eventsOpt, let databaseAccess = databaseAccessOpt else { return /* Cancelled */ } + guard let events, let databaseAccess else { return /* Cancelled */ } events.databaseDidChange?() @@ -562,14 +569,13 @@ extension ValueConcurrentObserver: TransactionObserver { let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } guard isNotifying else { return /* Cancelled */ } - let value = self.reducer._value(fetchedValue) + let value = try self.reducer._value(fetchedValue) // Notify value if let value = value { self.scheduler.schedule { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange } - guard let onChange = onChangeOpt else { return /* Cancelled */ } + let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } + guard let onChange else { return /* Cancelled */ } onChange(value) } } @@ -593,21 +599,20 @@ extension ValueConcurrentObserver: TransactionObserver { extension ValueConcurrentObserver: DatabaseCancellable { func cancel() { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ // Notify cancellation - let (eventsOpt, dbPoolOpt): (ValueObservationEvents?, DatabasePool?) = lock.synchronized { + let (events, dbPool): (ValueObservationEvents?, DatabasePool?) = lock.synchronized { let events = notificationCallbacks?.events notificationCallbacks = nil return (events, databaseAccess?.dbPool) } - guard let events = eventsOpt else { return /* Cancelled or failed */ } + guard let events else { return /* Cancelled or failed */ } events.didCancel?() // Stop observing the database // Do it asynchronously, so that we do not block the current thread: // cancellation may be triggered while a long write access is executing. - guard let dbPool = dbPoolOpt else { return /* Failed */ } + guard let dbPool else { return /* Failed */ } dbPool.asyncWriteWithoutTransaction { db in self.stopDatabaseObservation(db) } @@ -615,13 +620,12 @@ extension ValueConcurrentObserver: DatabaseCancellable { func notifyError(_ error: Error) { scheduler.schedule { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let eventsOpt: ValueObservationEvents? = self.lock.synchronized { + let events = self.lock.synchronized { let events = self.notificationCallbacks?.events self.notificationCallbacks = nil return events } - guard let events = eventsOpt else { return /* Cancelled */ } + guard let events else { return /* Cancelled */ } events.didFail?(error) } } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index bdfb58e3b..8c3739dd0 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -16,7 +16,7 @@ import Foundation /// let cancellable = try observation.start( /// in: dbQueue, /// onError: { error in ... }, -/// onChange: { players: [Player] in +/// onChange: { (players: [Player]) in /// print("Players have changed.") /// }) public struct ValueObservation { @@ -55,7 +55,7 @@ enum ValueObservationTrackingMode { /// /// // Tracked Region is always the full player table /// ValueObservation.trackingConstantRegion(Player.all()) { db in ... } - case constantRegion([DatabaseRegionConvertible]) + case constantRegion([any DatabaseRegionConvertible]) /// The tracked region is constant and inferred from the fetched values. /// @@ -88,7 +88,7 @@ struct ValueObservationEvents: Refinable { typealias ValueObservationStart = ( _ onError: @escaping (Error) -> Void, _ onChange: @escaping (T) -> Void) --> DatabaseCancellable +-> AnyDatabaseCancellable extension ValueObservation: Refinable { @@ -109,7 +109,7 @@ extension ValueObservation: Refinable { /// let cancellable = try observation.start( /// in: dbQueue, /// onError: { error in ... }, - /// onChange: { players: [Player] in + /// onChange: { (players: [Player]) in /// print("fresh players: \(players)") /// }) /// @@ -123,7 +123,7 @@ extension ValueObservation: Refinable { /// in: dbQueue, /// scheduling: .immediate, // <- /// onError: { error in ... }, - /// onChange: { players: [Player] in + /// onChange: { (players: [Player]) in /// print("fresh players: \(players)") /// }) /// // <- here "fresh players" is already printed. @@ -137,12 +137,13 @@ extension ValueObservation: Refinable { /// - parameter onError: A closure that is provided eventual errors that /// happen during observation /// - parameter onChange: A closure that is provided fresh values - /// - returns: a DatabaseCancellable + /// - returns: a cancellable. public func start( - in reader: DatabaseReader, + in reader: some DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), onError: @escaping (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable + onChange: @escaping (Reducer.Value) -> Void) + -> AnyDatabaseCancellable { let observation = self.with { $0.events.didFail = concat($0.events.didFail, onError) @@ -252,7 +253,6 @@ extension ValueObservation: Refinable { } } -#if compiler(>=5.6) && canImport(_Concurrency) extension ValueObservation { // MARK: - Asynchronous Observation /// The database observation, as an asynchronous sequence of @@ -265,7 +265,7 @@ extension ValueObservation { /// dispatched asynchronously on the main queue. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func values( - in reader: DatabaseReader, + in reader: some DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), bufferingPolicy: AsyncValueObservation.BufferingPolicy = .unbounded) -> AsyncValueObservation @@ -310,7 +310,7 @@ public struct AsyncValueObservation: AsyncSequence { // the iterator. var cancellable: AnyDatabaseCancellable? let stream = AsyncThrowingStream(Element.self, bufferingPolicy: bufferingPolicy) { continuation in - cancellable = AnyDatabaseCancellable(start( + cancellable = start( // onError { error in continuation.finish(throwing: error) @@ -321,7 +321,7 @@ public struct AsyncValueObservation: AsyncSequence { // TODO: I could never see this code running. Is it needed? cancellable?.cancel() } - })) + }) continuation.onTermination = { @Sendable [weak cancellable] _ in cancellable?.cancel() } @@ -350,7 +350,6 @@ public struct AsyncValueObservation: AsyncSequence { } } } -#endif #if canImport(Combine) extension ValueObservation { @@ -367,7 +366,7 @@ extension ValueObservation { /// .publisher(in: dbQueue) /// .sink( /// receiveCompletion: { completion in ... }, - /// receiveValue: { players: [Player] in + /// receiveValue: { (players: [Player]) in /// print("fresh players: \(players)") /// }) /// @@ -384,7 +383,7 @@ extension ValueObservation { /// scheduling: .immediate) // <- /// .sink( /// receiveCompletion: { completion in ... }, - /// receiveValue: { players: [Player] in + /// receiveValue: { (players: [Player]) in /// print("fresh players: \(players)") /// }) /// // <- here "fresh players" is already printed. @@ -398,7 +397,7 @@ extension ValueObservation { /// - returns: A Combine publisher @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func publisher( - in reader: DatabaseReader, + in reader: some DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main)) -> DatabasePublishers.Value { @@ -460,7 +459,7 @@ extension DatabasePublishers { // Cancellable is not stored in self.state because we must enter the // .observing state *before* the observation starts, so that the user // can change the state even before the cancellable is known. - private var cancellable: DatabaseCancellable? + private var cancellable: AnyDatabaseCancellable? private var state: State private var lock = NSRecursiveLock() // Allow re-entrancy @@ -669,7 +668,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { /// - parameter fetch: A function that fetches the observed value from /// the database. public static func tracking( - region: DatabaseRegionConvertible..., + region: any DatabaseRegionConvertible..., fetch: @escaping (Database) throws -> Value) -> ValueObservation> { @@ -714,7 +713,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { /// - parameter fetch: A function that fetches the observed value from /// the database. public static func tracking( - regions: [DatabaseRegionConvertible], + regions: [any DatabaseRegionConvertible], fetch: @escaping (Database) throws -> Value) -> ValueObservation> { @@ -735,7 +734,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { /// let cancellable = try observation.start( /// in: dbQueue, /// onError: { error in ... }, - /// onChange: { players: [Player] in + /// onChange: { (players: [Player]) in /// print("Players have changed") /// }) /// @@ -749,30 +748,4 @@ extension ValueObservation where Reducer == ValueReducers.Auto { trackingMode: .nonConstantRegionRecordedFromSelection, makeReducer: { ValueReducers.Fetch(fetch: fetch) }) } - - /// Creates a `ValueObservation` that notifies the values returned by the - /// `fetch` function whenever a database transaction changes them. - /// - /// For example: - /// - /// let observation = ValueObservation.tracking { db in - /// try Player.fetchAll(db) - /// } - /// - /// let cancellable = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { players: [Player] in - /// print("Players have changed") - /// }) - /// - /// - parameter fetch: A function that fetches the observed value from - /// the database. - @available(*, deprecated, renamed: "tracking(_:)") - public static func trackingVaryingRegion( - _ fetch: @escaping (Database) throws -> Value) - -> ValueObservation> - { - tracking(fetch) - } } diff --git a/GRDB/ValueObservation/ValueObservationScheduler.swift b/GRDB/ValueObservation/ValueObservationScheduler.swift index 46c380d95..488d7fac0 100644 --- a/GRDB/ValueObservation/ValueObservationScheduler.swift +++ b/GRDB/ValueObservation/ValueObservationScheduler.swift @@ -4,9 +4,9 @@ import Foundation /// ValueObservationScheduler determines how `ValueObservation` notifies its /// fresh values. public class ValueObservationScheduler { - private let impl: ValueObservationSchedulerImpl + private let impl: any ValueObservationSchedulerImpl - private init(impl: ValueObservationSchedulerImpl) { + private init(impl: any ValueObservationSchedulerImpl) { self.impl = impl } @@ -34,7 +34,7 @@ public class ValueObservationScheduler { /// in: dbQueue, /// scheduling: .async(onQueue: .main), /// onError: { error in ... }, - /// onChange: { players: [Player] in + /// onChange: { (players: [Player]) in /// print("fresh players: \(players)") /// }) public static func async(onQueue queue: DispatchQueue) -> ValueObservationScheduler { @@ -54,7 +54,7 @@ public class ValueObservationScheduler { /// in: dbQueue, /// scheduling: .immediate, /// onError: { error in ... }, - /// onChange: { players: [Player] in + /// onChange: { (players: [Player]) in /// print("fresh players: \(players)") /// }) /// // <- here "fresh players" is already printed. diff --git a/GRDB/ValueObservation/ValueReducer/Map.swift b/GRDB/ValueObservation/ValueReducer/Map.swift index f980f0349..28347cef5 100644 --- a/GRDB/ValueObservation/ValueReducer/Map.swift +++ b/GRDB/ValueObservation/ValueReducer/Map.swift @@ -2,7 +2,7 @@ extension ValueObservation { /// Returns a ValueObservation which notifies the results of calling the /// given transformation which each element notified by this /// value observation. - public func map(_ transform: @escaping (Reducer.Value) -> T) + public func map(_ transform: @escaping (Reducer.Value) throws -> T) -> ValueObservation> { mapReducer { ValueReducers.Map($0, transform) } @@ -16,9 +16,9 @@ extension ValueReducers { /// See `ValueObservation.map(_:)` public struct Map: ValueReducer { private var base: Base - private let transform: (Base.Value) -> Value + private let transform: (Base.Value) throws -> Value - init(_ base: Base, _ transform: @escaping (Base.Value) -> Value) { + init(_ base: Base, _ transform: @escaping (Base.Value) throws -> Value) { self.base = base self.transform = transform } @@ -29,9 +29,9 @@ extension ValueReducers { } /// :nodoc: - public mutating func _value(_ fetched: Base.Fetched) -> Value? { - guard let value = base._value(fetched) else { return nil } - return transform(value) + public mutating func _value(_ fetched: Base.Fetched) throws -> Value? { + guard let value = try base._value(fetched) else { return nil } + return try transform(value) } } } diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift index a41880ef7..1c3f116c9 100644 --- a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift @@ -35,8 +35,8 @@ extension ValueReducers { } /// :nodoc: - public mutating func _value(_ fetched: Base.Fetched) -> Base.Value? { - guard let value = base._value(fetched) else { + public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? { + guard let value = try base._value(fetched) else { return nil } if let previousValue = previousValue, predicate(previousValue, value) { diff --git a/GRDB/ValueObservation/ValueReducer/Trace.swift b/GRDB/ValueObservation/ValueReducer/Trace.swift index 239897a3d..f4c7c7735 100644 --- a/GRDB/ValueObservation/ValueReducer/Trace.swift +++ b/GRDB/ValueObservation/ValueReducer/Trace.swift @@ -12,8 +12,8 @@ extension ValueReducers { } /// :nodoc: - public mutating func _value(_ fetched: Base.Fetched) -> Base.Value? { - guard let value = base._value(fetched) else { + public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? { + guard let value = try base._value(fetched) else { return nil } didReceiveValue(value) diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index d4fe77257..be1fec7d7 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -26,7 +26,7 @@ public protocol _ValueReducer { /// reducer._value(...) // MUST NOT be nil /// reducer._value(...) // MAY be nil /// reducer._value(...) // MAY be nil - mutating func _value(_ fetched: Fetched) -> Value? + mutating func _value(_ fetched: Fetched) throws -> Value? } /// The `ValueReducer` protocol supports `ValueObservation`. diff --git a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/ValueWriteOnlyObserver.swift index 440a17ec4..604acbffe 100644 --- a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/ValueWriteOnlyObserver.swift @@ -151,12 +151,11 @@ final class ValueWriteOnlyObserver DatabaseCancellable { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let (notificationCallbacksOpt, databaseAccessOpt) = lock.synchronized { - (self.notificationCallbacks, self.databaseAccess) + func start() -> AnyDatabaseCancellable { + let (notificationCallbacks, writer) = lock.synchronized { + (self.notificationCallbacks, self.databaseAccess?.writer) } - guard let notificationCallbacks = notificationCallbacksOpt, let writer = databaseAccessOpt?.writer else { + guard let notificationCallbacks, let writer else { // Likely a GRDB bug: during a synchronous start, user is not // able to cancel observation. fatalError("can't start a cancelled or failed observation") @@ -208,8 +207,8 @@ extension ValueWriteOnlyObserver { } // Reduce - return reduceQueue.sync { - guard let initialValue = reducer._value(fetchedValue) else { + return try reduceQueue.sync { + guard let initialValue = try reducer._value(fetchedValue) else { fatalError("Broken contract: reducer has no initial value") } @@ -242,16 +241,23 @@ extension ValueWriteOnlyObserver { let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } guard isNotifying else { return /* Cancelled */ } - guard let initialValue = self.reducer._value(fetchedValue) else { - fatalError("Broken contract: reducer has no initial value") - } - - // Notify - self.scheduler.schedule { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange } - guard let onChange = onChangeOpt else { return /* Cancelled */ } - onChange(initialValue) + do { + guard let initialValue = try self.reducer._value(fetchedValue) else { + fatalError("Broken contract: reducer has no initial value") + } + + // Notify + self.scheduler.schedule { + let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } + guard let onChange else { return /* Cancelled */ } + onChange(initialValue) + } + } catch { + let writer = self.lock.synchronized { self.databaseAccess?.writer } + writer?.asyncWriteWithoutTransaction { db in + self.stopDatabaseObservation(db) + } + self.notifyError(error) } } } catch { @@ -270,11 +276,10 @@ extension ValueWriteOnlyObserver { /// single database access, we are sure that no concurrent write can happen /// during the initial fetch, and that we won't miss any future change. private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetched? { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let (eventsOpt, fetchOpt) = lock.synchronized { + let (events, fetch) = lock.synchronized { (notificationCallbacks?.events, databaseAccess?.fetch) } - guard let events = eventsOpt, let fetch = fetchOpt else { + guard let events, let fetch else { return nil /* Cancelled */ } @@ -338,13 +343,12 @@ extension ValueWriteOnlyObserver: TransactionObserver { // Reset the isModified flag until next transaction observationState.isModified = false - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ // Ignore transaction unless we are still notifying database events, and // we can still fetch fresh values. - let (eventsOpt, fetchOpt) = lock.synchronized { + let (events, fetch) = lock.synchronized { (notificationCallbacks?.events, databaseAccess?.fetch) } - guard let events = eventsOpt, let fetch = fetchOpt else { return /* Cancelled */ } + guard let events, let fetch else { return /* Cancelled */ } // Notify events.databaseDidChange?() @@ -389,16 +393,23 @@ extension ValueWriteOnlyObserver: TransactionObserver { let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } guard isNotifying else { return /* Cancelled */ } - let value = self.reducer._value(fetchedValue) - - // Notify value - if let value = value { - self.scheduler.schedule { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange } - guard let onChange = onChangeOpt else { return /* Cancelled */ } - onChange(value) + do { + let value = try self.reducer._value(fetchedValue) + + // Notify value + if let value = value { + self.scheduler.schedule { + let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } + guard let onChange else { return /* Cancelled */ } + onChange(value) + } } + } catch { + let writer = self.lock.synchronized { self.databaseAccess?.writer } + writer?.asyncWriteWithoutTransaction { db in + self.stopDatabaseObservation(db) + } + self.notifyError(error) } } } catch { @@ -417,21 +428,20 @@ extension ValueWriteOnlyObserver: TransactionObserver { extension ValueWriteOnlyObserver: DatabaseCancellable { func cancel() { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ // Notify cancellation - let (eventsOpt, writerOpt): (ValueObservationEvents?, Writer?) = lock.synchronized { + let (events, writer) = lock.synchronized { let events = notificationCallbacks?.events notificationCallbacks = nil return (events, databaseAccess?.writer) } - guard let events = eventsOpt else { return /* Cancelled or failed */ } + guard let events else { return /* Cancelled or failed */ } events.didCancel?() // Stop observing the database // Do it asynchronously, so that we do not block the current thread: // cancellation may be triggered while a long write access is executing. - guard let writer = writerOpt else { return /* Failed */ } + guard let writer else { return /* Failed */ } writer.asyncWriteWithoutTransaction { db in self.stopDatabaseObservation(db) } @@ -439,13 +449,12 @@ extension ValueWriteOnlyObserver: DatabaseCancellable { func notifyError(_ error: Error) { scheduler.schedule { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let eventsOpt: ValueObservationEvents? = self.lock.synchronized { + let events = self.lock.synchronized { let events = self.notificationCallbacks?.events self.notificationCallbacks = nil return events } - guard let events = eventsOpt else { return /* Cancelled */ } + guard let events else { return /* Cancelled */ } events.didFail?(error) } } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3b2e7c5cf..06c22ce01 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -35,8 +35,8 @@ 5611626C2576BF9D007AAF99 /* JoinAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561162692576BF9C007AAF99 /* JoinAssociation.swift */; }; 5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */; }; 5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */; }; - 561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614089E221596A100DAD589 /* GRDB-5.0.swift */; }; - 561408A1221596A100DAD589 /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614089E221596A100DAD589 /* GRDB-5.0.swift */; }; + 56158786288D878500A67323 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56158784288D878500A67323 /* Optional.swift */; }; + 56158787288D878500A67323 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56158784288D878500A67323 /* Optional.swift */; }; 5615B258222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B256222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */; }; 5615B259222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B256222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */; }; 5615B26D222AFEB300061C1C /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B26C222AFEB300061C1C /* AssociationHasOneThroughRowScopeTests.swift */; }; @@ -330,6 +330,8 @@ 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566BE7152342541F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7132342541F00A8254B /* LockedBox.swift */; }; 566BE7162342541F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7132342541F00A8254B /* LockedBox.swift */; }; + 566DDE12288D76400000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE11288D76400000DCFB /* Fixits.swift */; }; + 566DDE13288D76400000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE11288D76400000DCFB /* Fixits.swift */; }; 5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 5670329C212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; }; @@ -507,6 +509,24 @@ 56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB5031EAA2F4D00BFAF62 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; }; 56CEB5061EAA2F4D00BFAF62 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; }; + 56D110E928AFC90800E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E128AFC90800E64463 /* MutablePersistableRecord+Delete.swift */; }; + 56D110EA28AFC90800E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E128AFC90800E64463 /* MutablePersistableRecord+Delete.swift */; }; + 56D110EB28AFC90800E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E228AFC90800E64463 /* MutablePersistableRecord+Insert.swift */; }; + 56D110EC28AFC90800E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E228AFC90800E64463 /* MutablePersistableRecord+Insert.swift */; }; + 56D110ED28AFC90800E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E328AFC90800E64463 /* PersistableRecord+Insert.swift */; }; + 56D110EE28AFC90800E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E328AFC90800E64463 /* PersistableRecord+Insert.swift */; }; + 56D110EF28AFC90800E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E428AFC90800E64463 /* PersistableRecord+Save.swift */; }; + 56D110F028AFC90800E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E428AFC90800E64463 /* PersistableRecord+Save.swift */; }; + 56D110F128AFC90800E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E528AFC90800E64463 /* PersistableRecord.swift */; }; + 56D110F228AFC90800E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E528AFC90800E64463 /* PersistableRecord.swift */; }; + 56D110F328AFC90800E64463 /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E628AFC90800E64463 /* MutablePersistableRecord.swift */; }; + 56D110F428AFC90800E64463 /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E628AFC90800E64463 /* MutablePersistableRecord.swift */; }; + 56D110F528AFC90800E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E728AFC90800E64463 /* MutablePersistableRecord+Save.swift */; }; + 56D110F628AFC90800E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E728AFC90800E64463 /* MutablePersistableRecord+Save.swift */; }; + 56D110F728AFC90800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E828AFC90800E64463 /* MutablePersistableRecord+Update.swift */; }; + 56D110F828AFC90800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E828AFC90800E64463 /* MutablePersistableRecord+Update.swift */; }; + 56D110FF28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110FE28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift */; }; + 56D1110028AFC9C600E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110FE28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift */; }; 56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; @@ -539,6 +559,10 @@ 56F3E7501E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; 56F61DEA283D469F00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DE8283D469F00AF9884 /* getThreadsCount.c */; }; 56F61DEB283D469F00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DE8283D469F00AF9884 /* getThreadsCount.c */; }; + 56FA0C3628B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3428B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; }; + 56FA0C3728B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3428B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; }; + 56FA0C4128B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C4028B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift */; }; + 56FA0C4228B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C4028B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift */; }; 56FBFED62210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; }; 56FBFED72210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; }; 56FEB8FE248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */; }; @@ -578,7 +602,6 @@ F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; - F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; F3BA80381CFB2932003DC1BA /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF11CFB23D3003DC1BA /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -617,7 +640,6 @@ F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; - F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; F3BA80931CFB2F13003DC1BA /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF11CFB23D3003DC1BA /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -724,7 +746,6 @@ F3BA81221CFB3063003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */; }; F3BA81231CFB3063003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382B1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift */; }; F3BA81241CFB3063003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */; }; - F3BA81261CFB3063003DC1BA /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; F3BA81271CFB3063003DC1BA /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; F3BA81291CFB3063003DC1BA /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; F3BA812A1CFB3063003DC1BA /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; }; @@ -736,7 +757,6 @@ F3BA81301CFB3064003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */; }; F3BA81311CFB3064003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382B1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift */; }; F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */; }; - F3BA81341CFB3064003DC1BA /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; F3BA81351CFB3064003DC1BA /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; F3BA81371CFB3064003DC1BA /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; F3BA81381CFB3064003DC1BA /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; }; @@ -810,11 +830,10 @@ 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunctionTests.swift; sourceTree = ""; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; - 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 561162692576BF9C007AAF99 /* JoinAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinAssociation.swift; sourceTree = ""; }; 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; - 5614089E221596A100DAD589 /* GRDB-5.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-5.0.swift"; sourceTree = ""; }; + 56158784288D878500A67323 /* Optional.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Optional.swift; sourceTree = ""; }; 5615B256222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLDerivationTests.swift; sourceTree = ""; }; 5615B26C222AFEB300061C1C /* AssociationHasOneThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughRowScopeTests.swift; sourceTree = ""; }; 5615B277222B109500061C1C /* AssociationHasOneThroughFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughFetchableRecordTests.swift; sourceTree = ""; }; @@ -977,6 +996,7 @@ 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; }; 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; 566BE7132342541F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = ""; }; + 566DDE11288D76400000DCFB /* Fixits.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Fixits.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 = ""; }; @@ -1064,7 +1084,6 @@ 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPrimaryKeyRowIDTests.swift; sourceTree = ""; }; 56A2382B1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPrimaryKeySingleTests.swift; sourceTree = ""; }; 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift; sourceTree = ""; }; - 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordCopyTests.swift; sourceTree = ""; }; 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordEditedTests.swift; sourceTree = ""; }; 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordInitializersTests.swift; sourceTree = ""; }; 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordSubClassTests.swift; sourceTree = ""; }; @@ -1116,6 +1135,15 @@ 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecord.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; + 56D110E128AFC90800E64463 /* MutablePersistableRecord+Delete.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Delete.swift"; sourceTree = ""; }; + 56D110E228AFC90800E64463 /* MutablePersistableRecord+Insert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Insert.swift"; sourceTree = ""; }; + 56D110E328AFC90800E64463 /* PersistableRecord+Insert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Insert.swift"; sourceTree = ""; }; + 56D110E428AFC90800E64463 /* PersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Save.swift"; sourceTree = ""; }; + 56D110E528AFC90800E64463 /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; + 56D110E628AFC90800E64463 /* MutablePersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecord.swift; sourceTree = ""; }; + 56D110E728AFC90800E64463 /* MutablePersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Save.swift"; sourceTree = ""; }; + 56D110E828AFC90800E64463 /* MutablePersistableRecord+Update.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Update.swift"; sourceTree = ""; }; + 56D110FE28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+DAO.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56DA7D02260FAA1A00A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = ""; }; @@ -1140,6 +1168,8 @@ 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = ""; }; 56F61DE8283D469F00AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; 56F61DE9283D469F00AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = ""; }; + 56FA0C3428B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Upsert.swift"; sourceTree = ""; }; + 56FA0C4028B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Upsert.swift"; sourceTree = ""; }; 56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; 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 = ""; }; @@ -1245,6 +1275,7 @@ 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */, 5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */, 56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */, + 56158784288D878500A67323 /* Optional.swift */, 5605F1581C672E4000235C62 /* StandardLibrary.swift */, ); path = StandardLibrary; @@ -1303,14 +1334,6 @@ path = ValueObservation; sourceTree = ""; }; - 5614089D221596A100DAD589 /* Fixit */ = { - isa = PBXGroup; - children = ( - 5614089E221596A100DAD589 /* GRDB-5.0.swift */, - ); - path = Fixit; - sourceTree = ""; - }; 5614DEEE1BA9D6F9003163B3 /* Frameworks */ = { isa = PBXGroup; children = ( @@ -1350,7 +1373,6 @@ 56176C9E1EACEDF9000F3F2B /* Record */ = { isa = PBXGroup; children = ( - 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */, 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */, 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */, 56DA7D02260FAA1A00A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */, @@ -1857,7 +1879,17 @@ 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */, 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */, 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */, - 560D92441C672C4B00F4F92B /* PersistableRecord.swift */, + 56D110E628AFC90800E64463 /* MutablePersistableRecord.swift */, + 56D110FE28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift */, + 56D110E128AFC90800E64463 /* MutablePersistableRecord+Delete.swift */, + 56D110E228AFC90800E64463 /* MutablePersistableRecord+Insert.swift */, + 56D110E728AFC90800E64463 /* MutablePersistableRecord+Save.swift */, + 56D110E828AFC90800E64463 /* MutablePersistableRecord+Update.swift */, + 56FA0C3428B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift */, + 56D110E528AFC90800E64463 /* PersistableRecord.swift */, + 56D110E328AFC90800E64463 /* PersistableRecord+Insert.swift */, + 56D110E428AFC90800E64463 /* PersistableRecord+Save.swift */, + 56FA0C4028B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, ); @@ -1966,8 +1998,8 @@ isa = PBXGroup; children = ( 56A2FA3724424F4200E97D23 /* Export.swift */, + 566DDE11288D76400000DCFB /* Fixits.swift */, 56A2386F1B9C75030082EB20 /* Core */, - 5614089D221596A100DAD589 /* Fixit */, 5698AC291D9E5A480056AF8C /* FTS */, 56A238911B9C750B0082EB20 /* Migration */, 5656A8252295BD56001FF3FF /* QueryInterface */, @@ -2139,7 +2171,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0730; - LastUpgradeCheck = 1200; + LastUpgradeCheck = 1400; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { F3BA7FFD1CFB25E4003DC1BA = { @@ -2314,12 +2346,14 @@ files = ( 5656A8722295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */, 56713FE42691F487006153C3 /* JSONRequiredEncoder.swift in Sources */, + 56158787288D878500A67323 /* Optional.swift in Sources */, 5679533A27E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */, 5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */, F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */, 563B8FBE24A1D388007A48C9 /* OnDemandFuture.swift in Sources */, 5656A85E2295BD56001FF3FF /* VirtualTableModule.swift in Sources */, 5656A8882295BD56001FF3FF /* SQLOperators.swift in Sources */, + 566DDE13288D76400000DCFB /* Fixits.swift in Sources */, 563EF44E2161F196007DAACD /* Inflections.swift in Sources */, 566B910E1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 5656A8682295BD56001FF3FF /* HasOneAssociation.swift in Sources */, @@ -2327,6 +2361,7 @@ 5656A8602295BD56001FF3FF /* FTS3+QueryInterface.swift in Sources */, 56012B81257404A400B4925B /* CommonTableExpression.swift in Sources */, 5656A8982295BD56001FF3FF /* SQLRelation.swift in Sources */, + 56D1110028AFC9C600E64463 /* MutablePersistableRecord+DAO.swift in Sources */, 5659F4951EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, 56CEB4F61EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, @@ -2350,6 +2385,7 @@ 563EF421215F8A76007DAACD /* OrderedDictionary.swift in Sources */, F3BA80161CFB2876003DC1BA /* Row.swift in Sources */, 569EF0E7200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */, + 56FA0C4228B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */, F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */, 563B8FBA24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */, 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */, @@ -2359,8 +2395,11 @@ 563A4B72242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */, 5674A6F61F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, + 56D110EA28AFC90800E64463 /* MutablePersistableRecord+Delete.swift in Sources */, 5698AD171DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */, 569BBA4C229170B300478429 /* Inflections+English.swift in Sources */, + 56D110F628AFC90800E64463 /* MutablePersistableRecord+Save.swift in Sources */, + 56D110F028AFC90800E64463 /* PersistableRecord+Save.swift in Sources */, 56A6EB2526076F6A00C27594 /* SQL.swift in Sources */, 5656A8762295BD56001FF3FF /* RequestProtocols.swift in Sources */, 568ECB3625D91CEF00B71526 /* SQLSubquery.swift in Sources */, @@ -2371,6 +2410,7 @@ 56C0539822ACEECD0029D27D /* ValueReducer.swift in Sources */, 4E13D2F92769BC230037588C /* DatabaseBackupProgress.swift in Sources */, 56A2FA3A24424F4200E97D23 /* Export.swift in Sources */, + 56FA0C3628B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */, 56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */, 56CEB5061EAA2F4D00BFAF62 /* FTS4.swift in Sources */, @@ -2413,18 +2453,20 @@ 566BE7162342541F00A8254B /* LockedBox.swift in Sources */, F3BA80111CFB2876003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */, - F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */, 5656A8802295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */, 56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 561408A1221596A100DAD589 /* GRDB-5.0.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, 56FBFED72210731100945324 /* SQLRequest.swift in Sources */, 564CE43D21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */, 5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */, + 56D110EC28AFC90800E64463 /* MutablePersistableRecord+Insert.swift in Sources */, 5656A8702295BD56001FF3FF /* Association.swift in Sources */, + 56D110F828AFC90800E64463 /* MutablePersistableRecord+Update.swift in Sources */, + 56D110EE28AFC90800E64463 /* PersistableRecord+Insert.swift in Sources */, 563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */, 564D4F94261E1D3400F55856 /* CaseInsensitiveIdentifier.swift in Sources */, + 56D110F228AFC90800E64463 /* PersistableRecord.swift in Sources */, 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 5656A85C2295BD56001FF3FF /* TableDefinition.swift in Sources */, 5656A8562295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */, @@ -2435,6 +2477,7 @@ 5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */, F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */, 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, + 56D110F428AFC90800E64463 /* MutablePersistableRecord.swift in Sources */, F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 5657AABE1D107001006283EF /* NSData.swift in Sources */, 5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, @@ -2586,7 +2629,6 @@ 56419C9824A51D7F004967E1 /* Prefix.swift in Sources */, F3BA80BD1CFB2FD1003DC1BA /* DatabasePoolFunctionTests.swift in Sources */, 5615B279222B109600061C1C /* AssociationHasOneThroughFetchableRecordTests.swift in Sources */, - F3BA81261CFB3063003DC1BA /* RecordCopyTests.swift in Sources */, 56A8C24D1D1918F30096E9D4 /* FoundationNSUUIDTests.swift in Sources */, 4ECF777D273AFBA9001685F5 /* BackupTestCase.swift in Sources */, 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, @@ -2686,12 +2728,14 @@ files = ( 5656A8712295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */, 56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */, + 56158786288D878500A67323 /* Optional.swift in Sources */, 5679533927E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */, 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */, F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */, 563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */, 5656A85D2295BD56001FF3FF /* VirtualTableModule.swift in Sources */, 5656A8872295BD56001FF3FF /* SQLOperators.swift in Sources */, + 566DDE12288D76400000DCFB /* Fixits.swift in Sources */, 563EF44D2161F196007DAACD /* Inflections.swift in Sources */, 566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 5656A8672295BD56001FF3FF /* HasOneAssociation.swift in Sources */, @@ -2699,6 +2743,7 @@ 5656A85F2295BD56001FF3FF /* FTS3+QueryInterface.swift in Sources */, 56012B82257404A400B4925B /* CommonTableExpression.swift in Sources */, 5656A8972295BD56001FF3FF /* SQLRelation.swift in Sources */, + 56D110FF28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift in Sources */, 5659F4921EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, 56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, @@ -2722,6 +2767,7 @@ 563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */, F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */, 569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */, + 56FA0C4128B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */, F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */, 563B8FBB24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */, 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */, @@ -2731,8 +2777,11 @@ 563A4B71242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */, 5674A6F51F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, + 56D110E928AFC90800E64463 /* MutablePersistableRecord+Delete.swift in Sources */, 5698AD161DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */, 569BBA4D229170B300478429 /* Inflections+English.swift in Sources */, + 56D110F528AFC90800E64463 /* MutablePersistableRecord+Save.swift in Sources */, + 56D110EF28AFC90800E64463 /* PersistableRecord+Save.swift in Sources */, 56A6EB2426076F6A00C27594 /* SQL.swift in Sources */, 5656A8752295BD56001FF3FF /* RequestProtocols.swift in Sources */, 568ECB3525D91CEF00B71526 /* SQLSubquery.swift in Sources */, @@ -2743,6 +2792,7 @@ 56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */, 4E13D2F82769BC230037588C /* DatabaseBackupProgress.swift in Sources */, 56A2FA3924424F4200E97D23 /* Export.swift in Sources */, + 56FA0C3728B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */, 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */, 56CEB5031EAA2F4D00BFAF62 /* FTS4.swift in Sources */, @@ -2785,18 +2835,20 @@ 566BE7152342541F00A8254B /* LockedBox.swift in Sources */, F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */, - F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */, 5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */, 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, 56FBFED62210731100945324 /* SQLRequest.swift in Sources */, 564CE43C21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */, 5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, + 56D110EB28AFC90800E64463 /* MutablePersistableRecord+Insert.swift in Sources */, 5656A86F2295BD56001FF3FF /* Association.swift in Sources */, + 56D110F728AFC90800E64463 /* MutablePersistableRecord+Update.swift in Sources */, + 56D110ED28AFC90800E64463 /* PersistableRecord+Insert.swift in Sources */, 563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */, 564D4F93261E1D3300F55856 /* CaseInsensitiveIdentifier.swift in Sources */, + 56D110F128AFC90800E64463 /* PersistableRecord.swift in Sources */, 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 5656A85B2295BD56001FF3FF /* TableDefinition.swift in Sources */, 5656A8552295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */, @@ -2807,6 +2859,7 @@ 5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */, F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */, 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, + 56D110F328AFC90800E64463 /* MutablePersistableRecord.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, 5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, @@ -2823,7 +2876,6 @@ files = ( F3BA80D81CFB300B003DC1BA /* DatabaseValueTests.swift in Sources */, F3BA80CC1CFB2FD8003DC1BA /* DatabaseQueueTests.swift in Sources */, - F3BA81341CFB3064003DC1BA /* RecordCopyTests.swift in Sources */, F3BA81101CFB3057003DC1BA /* Row+FoundationTests.swift in Sources */, F3BA812C1CFB3064003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 5698AC991DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, @@ -3109,6 +3161,7 @@ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; + DEAD_CODE_STRIPPING = YES; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; @@ -3166,6 +3219,7 @@ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = YES; CURRENT_PROJECT_VERSION = 1; + DEAD_CODE_STRIPPING = YES; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; @@ -3311,6 +3365,7 @@ CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; @@ -3339,6 +3394,7 @@ CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; @@ -3366,6 +3422,7 @@ CLANG_ENABLE_OBJC_WEAK = YES; CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; @@ -3393,6 +3450,7 @@ CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; diff --git a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBOSX.xcscheme b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBOSX.xcscheme index 3ffb73a97..ac0c87d43 100644 --- a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBOSX.xcscheme +++ b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBOSX.xcscheme @@ -1,6 +1,6 @@ A toolkit for SQLite databases, with a focus on application development

- Swift 5.3 + Swift 5.7 Platforms License CI Status @@ -11,13 +11,14 @@ --- -**Latest release**: July 9, 2022 • [version 5.26.0](https://github.com/groue/GRDB.swift/tree/v5.26.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +**Latest release**: August 21, 2022 • [version 6.0.0-beta](https://github.com/groue/GRDB.swift/tree/v6.0.0-beta) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) -**Requirements**: iOS 11.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.3+ / Xcode 12+ +**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.3+** | **v5.26.0** | +| **Swift 5.7+** | **v6.0.0-beta** | +| Swift 5.3 | [v5.26.0](https://github.com/groue/GRDB.swift/tree/v5.26.0) | | Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) | | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | @@ -285,7 +286,7 @@ let observation = ValueObservation.tracking { db in // Start observation let cancellable = observation.start( in: dbQueue, - onError: { error in ... } + onError: { error in ... }, onChange: { (places: [Place]) in print("Fresh places: \(places)") }) ``` @@ -321,7 +322,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.26/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -360,7 +361,7 @@ Documentation #### General Guides & Good Practices - :bulb: [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) -- :bulb: [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +- :bulb: [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) - :bulb: [Issues tagged "best practices"](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22) - :question: [Issues tagged "question"](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion) - :blue_book: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) @@ -402,9 +403,9 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di GRDB offers two libraries, `GRDB` and `GRDB-dynamic`. Pick only one. When in doubt, prefer `GRDB`. The `GRDB-dynamic` library can reveal useful if you are going to link it with multiple targets within your app and only wish to link to a shared, dynamic framework once. See [How to link a Swift Package as dynamic](https://forums.swift.org/t/how-to-link-a-swift-package-as-dynamic/32062) for more information. -> :point_up: **Note**: Linux is not currently supported. +> **Note**: Linux is not currently supported. > -> :warning: **Warning**: Due to an Xcode bug, you will get "No such module 'CSQLite'" errors when you want to embed the GRDB package in other targets than the main application (watch extensions, for example). UI and Unit testing targets are OK, though. See [#642](https://github.com/groue/GRDB.swift/issues/642#issuecomment-575994093) for more information. +> **Warning**: Due to an Xcode bug, you will get "No such module 'CSQLite'" errors when you want to embed the GRDB package in other targets than the main application (watch extensions, for example). UI and Unit testing targets are OK, though. See [#642](https://github.com/groue/GRDB.swift/issues/642#issuecomment-575994093) for more information. ## Carthage @@ -457,7 +458,7 @@ The differences are: import GRDB let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") -let inMemoryDBQueue = DatabaseQueue() +let inMemoryDBQueue = try DatabaseQueue() ``` SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deinitialized. @@ -519,7 +520,7 @@ let dbPool = try DatabasePool(path: "/path/to/database.sqlite") SQLite creates the database file if it does not already exist. The connection is closed when the database pool gets deinitialized. -> :point_up: **Note**: unless read-only, a database pool opens your database in the SQLite "WAL mode". The WAL mode does not fit all situations. Please have a look at https://www.sqlite.org/wal.html. +> **Note**: unless read-only, a database pool opens your database in the SQLite "WAL mode". The WAL mode does not fit all situations. Please have a look at https://www.sqlite.org/wal.html. **A database pool can be used from any thread.** The `write` and `read` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue: @@ -613,11 +614,9 @@ do { } ``` -> :warning: **Warning**: It is your responsibility to prevent sensitive information from leaking in unexpected locations, so you should not set the `publicStatementArguments` flag in release builds (think about GDPR and other privacy-related rules). -> -> :warning: **Warning**: The SQLite version that ships with old operating systems (prior to OSX 10.12, tvOS 10.0, and watchOS 3.0) outputs statement arguments in the [trace events](#how-do-i-print-a-request-as-sql), regardless of the `publicStatementArguments` flag. +> **Warning**: It is your responsibility to prevent sensitive information from leaking in unexpected locations, so you should not set the `publicStatementArguments` flag in release builds (think about GDPR and other privacy-related rules). -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.26/Structs/Configuration.html) for more details and configuration options. +See [Configuration](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Structs/Configuration.html) for more details and configuration options. SQLite API @@ -674,7 +673,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.26/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/6.0.0-beta/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. @@ -932,7 +931,7 @@ try dbQueue.read { db in let dictionary = try Dictionary(uniqueKeysWithValues: cursor) ``` -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.26/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/6.0.0-beta/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 @@ -1011,11 +1010,11 @@ 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.26/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/6.0.0-beta/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: -> :point_up: **Don't turn a cursor of `Row` into an array or a set**. You would not get the distinct rows you expect. To get a array of rows, use `Row.fetchAll(...)`. To get a set of rows, use `Row.fetchSet(...)`. Generally speaking, make sure you copy a row whenever you extract it from a cursor for later use: `row.copy()`. +> **Note**: **Don't turn a cursor of `Row` into an array or a set**. You would not get the distinct rows you expect. To get a array of rows, use `Row.fetchAll(...)`. To get a set of rows, use `Row.fetchSet(...)`. Generally speaking, make sure you copy a row whenever you extract it from a cursor for later use: `row.copy()`. #### Column Values @@ -1053,7 +1052,7 @@ row[...] as Int row[...] as Int? ``` -> :warning: **Warning**: avoid the `as!` and `as?` operators: +> **Warning**: avoid the `as!` and `as?` operators: > > ```swift > if let int = row[...] as? Int { ... } // BAD - doesn't work @@ -1250,7 +1249,9 @@ See the documentation of [`Dictionary.init(_:uniquingKeysWith:)`](https://develo ### Value Queries -Instead of rows, you can directly fetch **[values](#values)**. Like rows, fetch them as **cursors**, **arrays**, **sets**, or **single** values (see [fetching methods](#fetching-methods)). Values are extracted from the leftmost column of the SQL queries: +**Instead of rows, you can directly fetch values.** There are many supported [value types](#values) (Bool, Int, String, Date, Swift enums, etc.). + +Like rows, fetch values as **cursors**, **arrays**, **sets**, or **single** values (see [fetching methods](#fetching-methods)). Values are extracted from the leftmost column of the SQL queries: ```swift try dbQueue.read { db in @@ -1259,25 +1260,46 @@ try dbQueue.read { db in try Int.fetchSet(db, sql: "SELECT ...", arguments: ...) // Set try Int.fetchOne(db, sql: "SELECT ...", arguments: ...) // Int? - // When database may contain NULL: + let maxScore = try Int.fetchOne(db, sql: "SELECT MAX(score) FROM player") // Int? + let names = try String.fetchAll(db, sql: "SELECT name FROM player") // [String] +} +``` + +`Int.fetchOne` returns nil in two cases: either the SELECT statement yielded no row, or one row with a NULL value: + +```swift +// No row: +try Int.fetchOne(db, sql: "SELECT 42 WHERE FALSE") // nil + +// One row with a NULL value: +try Int.fetchOne(db, sql: "SELECT NULL") // nil + +// One row with a non-NULL value: +try Int.fetchOne(db, sql: "SELECT 42") // 42 +``` + +For requests which may contain NULL, fetch optionals: + +```swift +try dbQueue.read { db in try Optional.fetchCursor(db, sql: "SELECT ...", arguments: ...) // A Cursor of Int? try Optional.fetchAll(db, sql: "SELECT ...", arguments: ...) // [Int?] try Optional.fetchSet(db, sql: "SELECT ...", arguments: ...) // Set } - -let playerCount = try dbQueue.read { db in - try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player")! -} ``` -`fetchOne` returns an optional value which is nil in two cases: either the SELECT statement yielded no row, or one row with a NULL value. +> :bulb: **Tip**: One advanced use case, when you fetch one value, is to distinguish the cases of a statement that yields no row, or one row with a NULL value. To do so, use `Optional.fetchOne`, which returns a double optional `Int??`: +> +> ```swift +> // No row: +> try Optional.fetchOne(db, sql: "SELECT 42 WHERE FALSE") // .none +> // One row with a NULL value: +> try Optional.fetchOne(db, sql: "SELECT NULL") // .some(.none) +> // One row with a non-NULL value: +> try Optional.fetchOne(db, sql: "SELECT 42") // .some(.some(42)) +> ``` -There are many supported value types (Bool, Int, String, Date, Swift enums, etc.). See [Values](#values) for more information: - -```swift -let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player")! // Int -let urls = try URL.fetchAll(db, sql: "SELECT url FROM link") // [URL] -``` +There are many supported value types (Bool, Int, String, Date, Swift enums, etc.). See [Values](#values) for more information. ## Values @@ -1296,7 +1318,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.26/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1395,7 +1417,7 @@ Here is how GRDB supports the various [date formats](https://www.sqlite.org/lang ³ GRDB 2+ interprets numerical values as timestamps that fuel `Date(timeIntervalSince1970:)`. Previous GRDB versions used to interpret numbers as [julian days](https://en.wikipedia.org/wiki/Julian_day). Julian days are still supported, with the `Date(julianDay:)` initializer. -> :warning: **Warning**: the range of valid years in the SQLite date formats is 0000-9999. You will need to pick another date format when your application needs to process years outside of this range. See the following chapters. +> **Warning**: the range of valid years in the SQLite date formats is 0000-9999. You will need to pick another date format when your application needs to process years outside of this range. See the following chapters. #### Date @@ -1413,14 +1435,14 @@ let creationDate: Date = row["creationDate"] Dates are stored using the format "YYYY-MM-DD HH:MM:SS.SSS" in the UTC time zone. It is precise to the millisecond. -> :point_up: **Note**: this format was chosen because it is the only format that is: +> **Note**: this format was chosen because it is the only format that is: > > - Comparable (`ORDER BY date` works) > - Comparable with the SQLite keyword CURRENT_TIMESTAMP (`WHERE date > CURRENT_TIMESTAMP` works) > - Able to feed [SQLite date & time functions](https://www.sqlite.org/lang_datefunc.html) > - Precise enough > -> :warning: **Warning**: the range of valid years in the SQLite date format is 0000-9999. You will experience problems with years outside of this range, such as decoding errors, or invalid date computations with [SQLite date & time functions](https://www.sqlite.org/lang_datefunc.html). +> **Warning**: the range of valid years in the SQLite date format is 0000-9999. You will experience problems with years outside of this range, such as decoding errors, or invalid date computations with [SQLite date & time functions](https://www.sqlite.org/lang_datefunc.html). Some applications may prefer another date format: @@ -1460,7 +1482,7 @@ DateComponents is indirectly supported, through the **DatabaseDateComponents** h DatabaseDateComponents reads date components from all [date formats supported by SQLite](https://www.sqlite.org/lang_datefunc.html), and stores them in the format of your choice, from HH:MM to YYYY-MM-DD HH:MM:SS.SSS. -> :warning: **Warning**: the range of valid years is 0000-9999. You will experience problems with years outside of this range, such as decoding errors, or invalid date computations with [SQLite date & time functions](https://www.sqlite.org/lang_datefunc.html). See [Date](#date) for more information. +> **Warning**: the range of valid years is 0000-9999. You will experience problems with years outside of this range, such as decoding errors, or invalid date computations with [SQLite date & time functions](https://www.sqlite.org/lang_datefunc.html). See [Date](#date) for more information. DatabaseDateComponents can be stored and fetched from the database just like other [values](#values): @@ -1528,7 +1550,7 @@ Here is how GRDB supports the various data types supported by SQLite: try db.execute(sql: "INSERT INTO transfer VALUES (?)", arguments: [NSDecimalNumber(string: "10.5")]) ``` - > :warning: **Warning**: since SQLite does not support decimal numbers, sending a non-integer `NSDecimalNumber` can result in a loss of precision during the conversion to double. + > **Warning**: since SQLite does not support decimal numbers, sending a non-integer `NSDecimalNumber` can result in a loss of precision during the conversion to double. > > Instead of sending non-integer `NSDecimalNumber` to the database, you may prefer: > @@ -1638,7 +1660,7 @@ For such codable value types, GRDB uses the standard [JSONDecoder](https://devel 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. +> **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 @@ -1767,7 +1789,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.26/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1879,7 +1901,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.26/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/6.0.0-beta/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift insertStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1960,9 +1982,9 @@ let statements = try Array(db.allStatements(sql: """ 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. +> **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so. -For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.26/Classes/Statement.html). +For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Classes/Statement.html). ### Prepared Statements Cache @@ -1971,7 +1993,7 @@ When the same query will be used several times in the lifetime of your applicati **Don't cache statements yourself.** -> :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. +> **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 `cachedStatement` method. GRDB does all the hard caching and [memory management](#memory-management) stuff for you: @@ -1986,7 +2008,7 @@ 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. +> **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 @@ -2404,7 +2426,7 @@ try dbQueue.read { db in } ``` -> :point_up: **Notes** +> **Note** > > - Those pointers are owned by GRDB: don't close connections or finalize statements created by GRDB. > - GRDB opens SQLite connections in the "[multi-thread mode](https://www.sqlite.org/threadsafe.html)", which (oddly) means that **they are not thread-safe**. Make sure you touch raw databases and statements inside their dedicated dispatch queues. @@ -2431,7 +2453,7 @@ To define your custom records, you subclass the ready-made `Record` class, or yo Extending structs with record protocols is more "swifty". Subclassing the Record class is more "classic". You can choose either way. See some [examples of record definitions](#examples-of-record-definitions), and the [list of record methods](#list-of-record-methods) for an overview. -> :point_up: **Note**: if you are familiar with Core Data's NSManagedObject or Realm's Object, you may experience a cultural shock: GRDB records are not uniqued, do not auto-update, and do not lazy-load. This is both a purpose, and a consequence of protocol-oriented programming. You should read [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) for a general introduction. +> **Note**: if you are familiar with Core Data's NSManagedObject or Realm's Object, you may experience a cultural shock: GRDB records are not uniqued, do not auto-update, and do not lazy-load. This is both a purpose, and a consequence of protocol-oriented programming. You should read [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) for a general introduction. > > :bulb: **Tip**: after you have read this chapter, check the [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) Guide. > @@ -2451,8 +2473,9 @@ Extending structs with record protocols is more "swifty". Subclassing the Record - [FetchableRecord Protocol](#fetchablerecord-protocol) - [TableRecord Protocol](#tablerecord-protocol) - [PersistableRecord Protocol](#persistablerecord-protocol) - - [Persistence Methods](#persistence-methods) - - [Customizing the Persistence Methods] + - [Persistence Methods] + - [Persistence Methods and the `RETURNING` clause](#persistence-methods-and-the-returning-clause) + - [Persistence Callbacks] - [Identifiable Records] - [Codable Records] - [Record Class](#record-class) @@ -2641,7 +2664,7 @@ Details follow: ```swift protocol FetchableRecord { /// Row initializer - init(row: Row) + init(row: Row) throws } ``` @@ -2705,11 +2728,11 @@ 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.26/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/6.0.0-beta/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()`. +> **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()`. -> :point_up: **Note**: The `FetchableRecord.init(row:)` initializer fits the needs of most applications. But some application are more demanding than others. When FetchableRecord does not exactly provide the support you need, have a look at the [Beyond FetchableRecord] chapter. +> **Note**: The `FetchableRecord.init(row:)` initializer fits the needs of most applications. But some application are more demanding than others. When FetchableRecord does not exactly provide the support you need, have a look at the [Beyond FetchableRecord] chapter. ## TableRecord Protocol @@ -2719,7 +2742,7 @@ See [fetching methods](#fetching-methods) for information about the `fetchCursor ```swift protocol TableRecord { static var databaseTableName: String { get } - static var databaseSelection: [SQLSelectable] { get } + static var databaseSelection: [any SQLSelectable] { get } } ``` @@ -2778,30 +2801,30 @@ Those abilities are granted by three protocols: // Defines how a record encodes itself into the database protocol EncodableRecord { /// Defines the values persisted in the database - func encode(to container: inout PersistenceContainer) + func encode(to container: inout PersistenceContainer) throws } // Adds persistence methods protocol MutablePersistableRecord: TableRecord, EncodableRecord { /// Optional method that lets your adopting type store its rowID upon /// successful insertion. Don't call it directly: it is called for you. - mutating func didInsert(with rowID: Int64, for column: String?) + mutating func didInsert(_ inserted: InsertionSuccess) } // Adds immutability protocol PersistableRecord: MutablePersistableRecord { - /// Non-mutating version of the optional didInsert(with:for:) - func didInsert(with rowID: Int64, for column: String?) + /// Non-mutating version of the optional didInsert(_:) + func didInsert(_ inserted: InsertionSuccess) } ``` Yes, three protocols instead of one. Here is how you pick one or the other: -- **If your type is a class**, choose `PersistableRecord`. On top of that, implement `didInsert(with:for:)` if the database table has an auto-incremented primary key. +- **If your type is a class**, choose `PersistableRecord`. On top of that, implement `didInsert(_:)` if the database table has an auto-incremented primary key. -- **If your type is a struct, and the database table has an auto-incremented primary key**, choose `MutablePersistableRecord`, and implement `didInsert(with:for:)`. +- **If your type is a struct, and the database table has an auto-incremented primary key**, choose `MutablePersistableRecord`, and implement `didInsert(_:)`. -- **Otherwise**, choose `PersistableRecord`, and ignore `didInsert(with:for:)`. +- **Otherwise**, choose `PersistableRecord`, and ignore `didInsert(_:)`. The `encode(to:)` method defines which [values](#values) (Bool, Int, String, Date, Swift enums, etc.) are assigned to database columns. @@ -2820,8 +2843,8 @@ extension Place : MutablePersistableRecord { } // Update auto-incremented id upon successful insertion - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -2861,8 +2884,8 @@ struct Player: Encodable, MutablePersistableRecord { var score: Int // Update auto-incremented id upon successful insertion - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } ``` @@ -2870,7 +2893,7 @@ struct Player: Encodable, MutablePersistableRecord { ### Persistence Methods -[Record](#record-class) subclasses and types that adopt [PersistableRecord] are given default implementations for methods that insert, update, and delete: +[Record](#record-class) subclasses and types that adopt [PersistableRecord] are given methods that insert, update, and delete: ```swift // INSERT @@ -2890,6 +2913,10 @@ try place.updateChanges(db) // Record class only try place.save(db) let savedPlace = place.saved(db) // non-mutating +// UPSERT +try place.upsert(db) +let insertedPlace = place.upsertAndFetch(db) + // DELETE try place.delete(db) @@ -2897,7 +2924,7 @@ try place.delete(db) let exists = try place.exists(db) ``` -The [TableRecord] protocol comes with batch operations: +**The [TableRecord] protocol comes with batch operations**: ```swift // UPDATE @@ -2911,65 +2938,229 @@ try Place.deleteOne(db, id:...) try Place.deleteOne(db, key:...) ``` -- All those methods can throw a [DatabaseError](#error-handling). +For more information about batch updates, see [Update Requests](#update-requests). + +- All persistence methods can throw a [DatabaseError](#error-handling). - `update` and `updateChanges` throw [PersistenceError](#persistenceerror) if the database does not contain any row for the primary key of the record. - `save` makes sure your values are stored in the database. It performs an UPDATE if the record has a non-null primary key, and then, if no row was modified, an INSERT. It directly performs an INSERT if the record has no primary key, or a null primary key. +- `upsert` requires SQLite 3.35.0+ (iOS 15.0+, macOS 12.0+, tvOS 15.0+, watchOS 8.0+, or [custom SQLite build]). + - `delete` and `deleteOne` returns whether a database row was deleted or not. `deleteAll` returns the number of deleted rows. `updateAll` returns the number of updated rows. `updateChanges` returns whether a database row was updated or not. **All primary keys are supported**, including composite primary keys that span several columns, and the [implicit rowid primary key](#the-implicit-rowid-primary-key). +**To customize persistence methods**, you provide [Persistence Callbacks], described below. Do not attempt at overriding the ready-made persistence methods. -### Customizing the Persistence Methods +### Persistence Methods and the `RETURNING` clause -Your custom type may want to perform extra work when the persistence methods are invoked. +SQLite 3.35.0+ is able to return values from a inserted or updated row, with the [`RETURNING` clause](https://www.sqlite.org/lang_returning.html) (available from iOS 15.0+, macOS 12.0+, tvOS 15.0+, watchOS 8.0+, or with a [custom SQLite build]). -For example, it may want to have its UUID automatically set before inserting. Or it may want to validate its values before saving. +The `RETURNING` clause helps dealing with database features such as auto-incremented ids, default values, and [generated columns](https://sqlite.org/gencol.html). You can, for example, insert a few columns and fetch the default or generated ones in one step. -When you subclass [Record](#record-class), you simply have to override the customized method, and call `super`: +GRDB uses the `RETURNING` clause in all persistence methods that contain `AndFetch` in their name. + +For example, given a database table with an auto-incremented primary key and a default score: ```swift -class Player : Record { - var uuid: UUID? +try dbQueue.write { db in + try db.execute(sql: """ + CREATE TABLE player( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + score INTEGER NOT NULL DEFAULT 1000) + """) +} +``` + +You can define a record type with full database information, and another partial record type that deals with a subset of columns: + +```swift +// A player with full database information +struct Player: Codable, PersistableRecord, FetchableRecord { + var id: Int64 + var name: String + var score: Int +} + +// A partial player +struct PartialPlayer: Encodable, PersistableRecord { + static let databaseTableName = "player" + var name: String +} +``` + +And now you can get a full player by inserting a partial one: + +```swift +try dbQueue.write { db in + let partialPlayer = PartialPlayer(name: "Alice") - override func insert(_ db: Database) throws { - if uuid == nil { - uuid = UUID() - } - try super.insert(db) + // INSERT INTO player (name) VALUES ('Alice') RETURNING * + if let player = try partialPlayer.insertAndFetch(db, as: Player.self) { + print(player.id) // The inserted id + print(player.name) // The inserted name + print(player.score) // The default score } } ``` -If you use the raw [PersistableRecord] protocol, use one of the *special methods* `performInsert`, `performUpdate`, `performSave`, `performDelete`, or `performExists`: +For extra precision, you can select only the columns you need, and fetch the desired value from the provided [prepared statement](#prepared-statements): ```swift -struct Link : PersistableRecord { +try dbQueue.write { db in + let partialPlayer = PartialPlayer(name: "Alice") + + // INSERT INTO player (name) VALUES ('Alice') RETURNING score + let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in + try Int.fetchOne(statement) + } + print(score) // Prints 1000, the default score +} +``` + +There are other similar persistence methods, such as `saveAndFetch`, `updateAndFetch`, `updateChangesAndFetch`, etc. They all behave like `save`, `update`, `updateChanges` (see [Persistence Methods] and the [`updateChanges` methods](#the-updatechanges-methods)), except that they return saved values. For example: + +```swift +// Save and return the saved player +let savedPlayer = try player.saveAndFetch(db) +``` + +**Batch operations** can return updated or deleted values: + +> **Warning**: Make sure you check the [documentation of the `RETURNING` clause](https://www.sqlite.org/lang_returning.html), which describes important limitations and caveats for batch operations. + +```swift +let request = Player.filter(...)... + +// Fetch all deleted players +// DELETE FROM player RETURNING * +let deletedPlayers = try request.deleteAndFetchAll(db) // [Player] + +// Fetch a selection of columns from the deleted rows +// DELETE FROM player RETURNING name +let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")]) +let deletedNames = try String.fetchSet(statement) + +// Fetch all updated players +// UPDATE player SET score = score + 10 RETURNING * +let updatedPlayers = try request.updateAndFetchAll(db, [Column("score") += 10]) // [Player] + +// Fetch a selection of columns from the updated rows +// UPDATE player SET score = score + 10 RETURNING score +let statement = try request.updateAndFetchStatement( + db, [Column("score") += 10], + select: [Column("score")]) +let updatedScores = try Int.fetchAll(statement) +``` + + +### Persistence Callbacks + +Your custom type may want to perform extra work when the persistence methods are invoked. + +To this end, your record type can implement **persistence callbacks**. Callbacks are methods that get called at certain moments of a record's life cycle. With callbacks it is possible to write code that will run whenever an record is inserted, updated, or deleted. + +In order to use a callback method, you need to provide its implementation. For example, a frequently used callback is `didInsert`, in the case of auto-incremented database ids: + +```swift +struct Player: MutablePersistableRecord { + var id: Int64? + + // Update auto-incremented id upon successful insertion + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID + } +} + +try dbQueue.write { db in + var player = Player(id: nil, ...) + try player.insert(db) + print(player.id) // didInsert was called: prints some non-nil id +} +``` + +When you subclass the [Record](#record-class) class, override the callback, and make sure you call `super` at some point of your implementation: + +```swift +class Player: Record { + var id: Int64? + + // Update auto-incremented id upon successful insertion + func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + id = inserted.rowID + } +} +``` + +Callbacks can also help implementing record validation: + +```swift +struct Link: PersistableRecord { var url: URL - func insert(_ db: Database) throws { - try validate() - try performInsert(db) - } - - func update(_ db: Database, columns: Set) throws { - try validate() - try performUpdate(db, columns: columns) - } - - func validate() throws { + func willSave(_ db: Database) throws { if url.host == nil { throw ValidationError("url must be absolute.") } } } + +try link.insert(db) // Calls the willSave callback +try link.update(db) // Calls the willSave callback +try link.save(db) // Calls the willSave callback +try link.upsert(db) // Calls the willSave callback ``` -> :point_up: **Note**: the special methods `performInsert`, `performUpdate`, etc. are reserved for your custom implementations. Do not use them elsewhere. Do not provide another implementation for those methods. +#### Available Callbacks + +Here is a list with all the available callbacks, listed in the same order in which they will get called during the respective operations: + +- Inserting a record (all `record.insert` and `record.upsert` methods) + - `willSave` + - `aroundSave` + - `willInsert` + - `aroundInsert` + - `didInsert` + - `didSave` + +- Updating a record (all `record.update` methods) + - `willSave` + - `aroundSave` + - `willUpdate` + - `aroundUpdate` + - `didUpdate` + - `didSave` + +- Deleting a record (only the `record.delete(_:)` method) + - `willDelete` + - `aroundDelete` + - `didDelete` + +Make sure you provide implementations that match the exact callback signatures. When in doubt, check the [reference](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Protocols/MutablePersistableRecord.html). + +In the `MutablePersistableRecord` protocol, `willInsert` and `didInsert` are mutating methods. In `PersistableRecord`, they are not mutating. + +> **Note**: The `record.save(_:)` method performs an UPDATE if the record has a non-null primary key, and then, if no row was modified, an INSERT. It directly performs an INSERT if the record has no primary key, or a null primary key. It triggers update and/or insert callbacks accordingly. > -> :point_up: **Note**: it is recommended that you do not implement your own version of the `save` method. Its default implementation forwards the job to `update` or `insert`: these are the methods that may need customization, not `save`. +> **Warning**: Callbacks are only invoked from persistence methods called on record instances. Callbacks are not invoked when you call a type method, perform a batch operations, or execute raw SQL. +> +> **Warning**: When a `did***` callback is invoked, do not assume that the change is actually persisted on disk, because the database may still be inside an uncommitted transaction. When you need to handle transaction completions, use the [Transaction Hook](#transaction-hook). For example: +> +> ```swift +> struct PictureFile: PersistableRecord { +> var path: String +> +> func willDelete(_ db: Database) { +> db.afterNextTransaction { _ in +> try? deleteFileOnDisk() +> } +> } +> } +> ``` ## Identifiable Records @@ -2994,14 +3185,11 @@ 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]) ``` -> :point_up: **Note**: `Identifiable` is not available on all application targets, and not all tables have a single-column primary key. GRDB provides other methods that deal with primary and unique keys, but they won't check the type of their arguments: +> **Note**: `Identifiable` is not available on all application targets, and not all tables have a single-column primary key. GRDB provides other methods that deal with primary and unique keys, but they won't check the type of their arguments: > > ```swift > // Those methods are not type-checked @@ -3100,7 +3288,7 @@ struct Player: Codable, FetchableRecord, PersistableRecord { var achievements: [Achievement] // stored in a JSON column } -try! dbQueue.write { db in +try dbQueue.write { db in // INSERT INTO player (name, score, achievements) // VALUES ( // 'Arthur', @@ -3126,7 +3314,7 @@ protocol EncodableRecord { } ``` -> :bulb: **Tip**: Make sure you set the JSONEncoder `sortedKeys` option, available from iOS 11.0+, macOS 10.13+, tvOS 9.0+ and watchOS 4.0+. This option makes sure that the JSON output is stable. This stability is required for [Record Comparison] to work as expected, and database observation tools such as [ValueObservation] to accurately recognize changed records. +> :bulb: **Tip**: Make sure you set the JSONEncoder `sortedKeys` option. This option makes sure that the JSON output is stable. This stability is required for [Record Comparison] to work as expected, and database observation tools such as [ValueObservation] to accurately recognize changed records. ### Column Names Coding Strategies @@ -3145,7 +3333,7 @@ protocol EncodableRecord { } ``` -See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies. +See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/6.0.0-beta/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/6.0.0-beta/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies. ### Date and UUID Coding Strategies @@ -3167,7 +3355,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/6.0.0-beta/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/6.0.0-beta/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/6.0.0-beta/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase). @@ -3259,7 +3447,7 @@ extension Player: FetchableRecord { let player = try Player.fetchOne(db, ...) ``` -> :point_up: **Note**: make sure the `databaseDecodingUserInfo` and `databaseEncodingUserInfo` properties are explicitly declared as `[CodingUserInfoKey: Any]`. If they are not, the Swift compiler may silently miss the protocol requirement, resulting in sticky empty userInfo. +> **Note**: make sure the `databaseDecodingUserInfo` and `databaseEncodingUserInfo` properties are explicitly declared as `[CodingUserInfoKey: Any]`. If they are not, the Swift compiler may silently miss the protocol requirement, resulting in sticky empty userInfo. ### Tip: Derive Columns from Coding Keys @@ -3315,18 +3503,18 @@ class Place: Record { } /// Creates a record from a database row - required init(row: Row) { + required init(row: Row) throws { id = row[Columns.id] title = row[Columns.title] isFavorite = row[Columns.favorite] coordinate = CLLocationCoordinate2D( latitude: row[Columns.latitude], longitude: row[Columns.longitude]) - super.init(row: row) + try super.init(row: row) } /// The values persisted in the database - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container[Columns.id] = id container[Columns.title] = title container[Columns.favorite] = isFavorite @@ -3335,8 +3523,9 @@ class Place: Record { } /// Update record ID after a successful insertion - override func didInsert(with rowID: Int64, for column: String?) { - id = rowID + override func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + id = inserted.rowID } } ``` @@ -3373,7 +3562,7 @@ The `updateChanges` methods perform a database update of the changed columns onl } ``` -- `updateChanges(_:with:)` +- `updateChanges(_:modify:)` This method lets you update a record in place: @@ -3419,7 +3608,7 @@ if newPlayer.databaseEquals(oldPlayer) == false { } ``` -> :point_up: **Note**: The comparison is performed on the database representation of records. As long as your record type adopts the EncodableRecord protocol, you don't need to care about Equatable. +> **Note**: The comparison is performed on the database representation of records. As long as your record type adopts the EncodableRecord protocol, you don't need to care about Equatable. ### The `databaseChanges` and `hasDatabaseChanges` Methods @@ -3429,7 +3618,7 @@ if newPlayer.databaseEquals(oldPlayer) == false { ```swift let oldPlayer = Player(id: 1, name: "Arthur", score: 100) let newPlayer = Player(id: 1, name: "Arthur", score: 1000) -for (column, oldValue) in newPlayer.databaseChanges(from: oldPlayer) { +for (column, oldValue) in try newPlayer.databaseChanges(from: oldPlayer) { print("\(column) was \(oldValue)") } // prints "score was 100" @@ -3442,7 +3631,7 @@ The [Record](#record-class) class is able to compare against itself: let player = Player(id: 1, name: "Arthur", score: 100) try player.insert(db) player.score = 1000 -for (column, oldValue) in player.databaseChanges { +for (column, oldValue) in try player.databaseChanges { print("\(column) was \(oldValue)") } // prints "score was 100" @@ -3462,17 +3651,17 @@ if player.hasDatabaseChanges { ```swift let player = Player(name: "Barbara", score: 750) -player.hasDatabaseChanges // true +player.hasDatabaseChanges // true try player.insert(db) -player.hasDatabaseChanges // false +player.hasDatabaseChanges // false player.name = "Barbara" -player.hasDatabaseChanges // false +player.hasDatabaseChanges // false player.score = 1000 -player.hasDatabaseChanges // true -player.databaseChanges // ["score": 750] +player.hasDatabaseChanges // true +try player.databaseChanges // ["score": 750] ``` For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check [groue/SortedDifference](https://github.com/groue/SortedDifference). @@ -3482,7 +3671,7 @@ For an efficient algorithm which synchronizes the content of a database table wi GRDB records come with many default behaviors, that are designed to fit most situations. Many of those defaults can be customized for your specific needs: -- [Customizing the Persistence Methods]: define what happens when you call a persistence method such as `player.insert(db)` +- [Persistence Callbacks]: define what happens when you call a persistence method such as `player.insert(db)` - [Conflict Resolution]: Run `INSERT OR REPLACE` queries, and generally define what happens when a persistence method violates a unique index. - [The Implicit RowID Primary Key]: all about the special `rowid` column. - [Columns Selected by a Request]: define which columns are selected by requests such as `Player.fetchAll(db)`. @@ -3541,7 +3730,7 @@ The [five different policies](https://www.sqlite.org/lang_conflict.html) are: ab try db.execute(sql: "INSERT OR REPLACE INTO player (email) VALUES (?)", arguments: ["arthur@example.com"]) ``` -When you want to handle conflicts at the query level, specify a custom `persistenceConflictPolicy` in your type that adopts the PersistableRecord protocol. It will alter the INSERT and UPDATE queries run by the `insert`, `update` and `save` [persistence methods](#persistence-methods): +When you want to handle conflicts at the query level, specify a custom `persistenceConflictPolicy` in your type that adopts the PersistableRecord protocol. It will alter the INSERT and UPDATE queries run by the `insert`, `update` and `save` [persistence methods]: ```swift protocol MutablePersistableRecord { @@ -3564,12 +3753,19 @@ struct Player : MutablePersistableRecord { try player.insert(db) ``` -> :point_up: **Note**: the `ignore` policy does not play well at all with the `didInsert` method which notifies the rowID of inserted records. Choose your poison: +> **Note**: If you specify the `ignore` policy for inserts, the [`didInsert` callback](#persistence-callbacks) will be called with some random id in case of failed insert. You can detect failed insertions with `insertAndFetch`: +> +> ```swift +> // How to detect failed `INSERT OR IGNORE`: +> // INSERT OR IGNORE INTO player ... RETURNING * +> if let insertedPlayer = try player.insertAndFetch(db) { +> // Succesful insertion +> } else { +> // Ignored failure +> } +> ``` > -> - if you specify the `ignore` policy in the database table definition, don't implement the `didInsert` method: it will be called with some random id in case of failed insert. -> - if you specify the `ignore` policy at the query level, the `didInsert` method is never called. -> -> :point_up: **Note**: The `replace` policy may have to delete rows so that inserts and updates can succeed. Those deletions are not reported to [transaction observers](#transactionobserver-protocol) (this might change in a future release of SQLite). +> **Note**: The `replace` policy may have to delete rows so that inserts and updates can succeed. Those deletions are not reported to [transaction observers](#transactionobserver-protocol) (this might change in a future release of SQLite). ### The Implicit RowID Primary Key @@ -3616,13 +3812,13 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](Doc ```swift struct Event : TableRecord { - static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] } // When you subclass Record, you need an override: class Book : Record { - override class var databaseSelection: [SQLSelectable] { - [AllColums(), Column.rowID] + override class var databaseSelection: [any SQLSelectable] { + [AllColumns(), Column.rowID] } } ``` @@ -3653,7 +3849,7 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](Doc event.id // some value ``` -3. Encode the rowid in `encode(to:)`, and keep it in the `didInsert(with:for:)` method (both from the [PersistableRecord and MutablePersistableRecord](#persistablerecord-protocol) protocols): +3. Encode the rowid in `encode(to:)`, and keep it in the `didInsert(_:)` callback (both from the [PersistableRecord and MutablePersistableRecord](#persistablerecord-protocol) protocols): ```swift struct Event : MutablePersistableRecord { @@ -3666,8 +3862,8 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](Doc } // Update auto-incremented id upon successful insertion - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } ``` @@ -3698,12 +3894,8 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](Doc - Your application needs to decode rows with a context: each decoded value should be initialized with some extra value that does not come from the database. -- Your application needs a record type that supports untrusted databases, and may fail at decoding database rows (throw an error when a row contains invalid values). - Since those use cases are not well handled by FetchableRecord, don't try to implement them on top of this protocol: you'll just fight the framework. -Instead, please have a look at the [CustomizedDecodingOfDatabaseRows](Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift) playground. You'll run some sample code, and learn how to escape FetchableRecord when you need. And remember that leaving FetchableRecord will not deprive you of [query interface requests](#requests) and generally all SQL generation features of the [TableRecord] and [PersistableRecord] protocols. - ## Examples of Record Definitions @@ -3769,8 +3961,8 @@ extension Place: FetchableRecord { } // Persistence methods extension Place: MutablePersistableRecord { // Update auto-incremented id upon successful insertion - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } ``` @@ -3823,8 +4015,8 @@ extension Place: MutablePersistableRecord { } // Update auto-incremented id upon successful insertion - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } ``` @@ -3871,7 +4063,7 @@ extension Place: TableRecord { } /// Arrange the selected columns and lock their order - static let databaseSelection: [SQLSelectable] = [ + static let databaseSelection: [any SQLSelectable] = [ Columns.id, Columns.title, Columns.favorite, @@ -3897,8 +4089,8 @@ extension Place: FetchableRecord { // Persistence methods extension Place: MutablePersistableRecord { // Update auto-incremented id upon successful insertion - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } ``` @@ -3934,18 +4126,18 @@ class Place: Record { } /// Creates a record from a database row - required init(row: Row) { + required init(row: Row) throws { id = row[Columns.id] title = row[Columns.title] isFavorite = row[Columns.isFavorite] coordinate = CLLocationCoordinate2D( latitude: row[Columns.latitude], longitude: row[Columns.longitude]) - super.init(row: row) + try super.init(row: row) } /// The values persisted in the database - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container[Columns.id] = id container[Columns.title] = title container[Columns.isFavorite] = isFavorite @@ -3954,8 +4146,9 @@ class Place: Record { } // Update auto-incremented id upon successful insertion - override func didInsert(with rowID: Int64, for column: String?) { - id = rowID + override func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + id = inserted.rowID } } ``` @@ -3975,17 +4168,31 @@ This is the list of record methods, along with their required protocols. The [Re | `Type.databaseSelection` | [TableRecord] | [*](#columns-selected-by-a-request) | | `Type.persistenceConflictPolicy` | [PersistableRecord] | [*](#conflict-resolution) | | `record.encode(to:)` | [EncodableRecord] | | -| `record.didInsert(with:for:)` | [PersistableRecord] | | | **Insert and Update Records** | | | | `record.insert(db)` | [PersistableRecord] | | +| `record.insertAndFetch(db)` | [PersistableRecord] & [FetchableRecord] | | +| `record.insertAndFetch(_:as:)` | [PersistableRecord] | | +| `record.insertAndFetch(_:selection:fetch:)` | [PersistableRecord] | | | `record.inserted(db)` | [PersistableRecord] | | | `record.save(db)` | [PersistableRecord] | | +| `record.saveAndFetch(db)` | [PersistableRecord] & [FetchableRecord] | | +| `record.saveAndFetch(_:as:)` | [PersistableRecord] | | +| `record.saveAndFetch(_:selection:fetch:)` | [PersistableRecord] | | | `record.saved(db)` | [PersistableRecord] | | | `record.update(db)` | [PersistableRecord] | | +| `record.updateAndFetch(db)` | [PersistableRecord] & [FetchableRecord] | | +| `record.updateAndFetch(_:as:)` | [PersistableRecord] | | +| `record.updateAndFetch(_:selection:fetch:)` | [PersistableRecord] | | | `record.update(db, columns:...)` | [PersistableRecord] | | +| `record.updateAndFetch(_:columns:selection:fetch:)` | [PersistableRecord] | | | `record.updateChanges(db, from:...)` | [PersistableRecord] | [*](#record-comparison) | | `record.updateChanges(db) { ... }` | [PersistableRecord] | [*](#record-comparison) | +| `record.updateChangesAndFetch(_:columns:as:modify:)` | [PersistableRecord] | | +| `record.updateChangesAndFetch(_:columns:selection:fetch:modify:)` | [PersistableRecord] | | | `record.updateChanges(db)` | [Record](#record-class) | [*](#record-comparison) | +| `record.upsert(db)` | [PersistableRecord] | | +| `record.upsertAndFetch(db)` | [PersistableRecord] & [FetchableRecord] | | +| `record.upsertAndFetch(_:as:)` | [PersistableRecord] | | | `Type.updateAll(db, ...)` | [TableRecord] | | | `Type.filter(...).updateAll(db, ...)` | [TableRecord] | ² | | **Delete Records** | | | @@ -3996,6 +4203,19 @@ This is the list of record methods, along with their required protocols. The [Re | `Type.deleteAll(db, keys:...)` | [TableRecord] | ¹ | | `Type.deleteAll(db, ids:...)` | [TableRecord] & [Identifiable] | ¹ | | `Type.filter(...).deleteAll(db)` | [TableRecord] | ² | +| **Persistence Callbacks** | | | +| `record.willInsert(_:)` | [PersistableRecord] | | +| `record.aroundInsert(_:insert:)` | [PersistableRecord] | | +| `record.didInsert(_:)` | [PersistableRecord] | | +| `record.willUpdate(_:columns:)` | [PersistableRecord] | | +| `record.aroundUpdate(_:columns:update:)` | [PersistableRecord] | | +| `record.didUpdate(_:)` | [PersistableRecord] | | +| `record.willSave(_:)` | [PersistableRecord] | | +| `record.aroundSave(_:save:)` | [PersistableRecord] | | +| `record.didSave(_:)` | [PersistableRecord] | | +| `record.willDelete(_:)` | [PersistableRecord] | | +| `record.aroundDelete(_:delete:)` | [PersistableRecord] | | +| `record.didDelete(deleted:)` | [PersistableRecord] | | | **Check Record Existence** | | | | `record.exists(db)` | [PersistableRecord] | | | `Type.exists(db, key: ...)` | [TableRecord] | ¹ | @@ -4054,7 +4274,7 @@ 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.selectPrimaryKey(as:...)` | [TableRecord] | ² | | `Type.annotated(with:...)` | [TableRecord] | ² | | `Type.filter(...)` | [TableRecord] | ² | | `Type.filter(id:)` | [TableRecord] & Identifiable | [*](#identifiable-records) | @@ -4173,7 +4393,7 @@ try dbQueue.write { db in So don't miss the [SQL API](#sqlite-api). -> :point_up: **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output. +> **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output. - [Database Schema](#database-schema) - [Requests](#requests) @@ -4240,7 +4460,7 @@ try db.create(table: "example", options: [.temporary, .ifNotExists]) { t in ... > > This will help you using [Associations] when you need them. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration. > -> :point_up: **Note**: [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables can not be tracked with [Database Observation] tools. +> **Note**: [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables can not be tracked with [Database Observation] tools. **Add regular columns** with their name and eventual type (`text`, `integer`, `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime` and `any`) - see [SQLite data types](https://www.sqlite.org/datatype3.html): @@ -4367,7 +4587,7 @@ try db.alter(table: "player") { t in } ``` -> :point_up: **Note**: SQLite restricts the possible table alterations, and may require you to recreate dependent triggers or views. See the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html) for details. See [Advanced Database Schema Changes](Documentation/Migrations.md#advanced-database-schema-changes) for a way to lift restrictions. +> **Note**: SQLite restricts the possible table alterations, and may require you to recreate dependent triggers or views. See the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html) for details. See [Advanced Database Schema Changes](Documentation/Migrations.md#advanced-database-schema-changes) for a way to lift restrictions. ### Drop Tables @@ -4431,7 +4651,7 @@ 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. +> **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: @@ -4469,16 +4689,6 @@ 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 @@ -4655,6 +4865,19 @@ You can now build requests with the following methods: `all`, `none`, `select`, - Other requests that involve the primary key: + - `selectPrimaryKey(as:)` selects the primary key. + + ```swift + // SELECT id FROM player + Player.selectPrimaryKey(as: Int64.self) // QueryInterfaceRequest + + // SELECT code FROM country + Country.selectPrimaryKey(as: String.self) // QueryInterfaceRequest + + // SELECT citizenId, countryCode FROM citizenship + Citizenship.selectPrimaryKey(as: Row.self) // QueryInterfaceRequest + ``` + - `orderByPrimaryKey()` sorts by primary key. ```swift @@ -4692,7 +4915,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -4734,12 +4957,12 @@ The default selection for a record type is controlled by the `databaseSelection` ```swift struct RestrictedPlayer : TableRecord { static let databaseTableName = "player" - static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")] + static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")] } struct ExtendedPlayer : TableRecord { static let databaseTableName = "player" - static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] } // SELECT id, name FROM player @@ -4749,7 +4972,7 @@ let request = RestrictedPlayer.all() let request = ExtendedPlayer.all() ``` -> :point_up: **Note**: make sure the `databaseSelection` property is explicitly declared as `[SQLSelectable]`. If it is not, the Swift compiler may silently miss the protocol requirement, resulting in sticky `SELECT *` requests. To verify your setup, see the [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) FAQ. +> **Note**: make sure the `databaseSelection` property is explicitly declared as `[any SQLSelectable]`. If it is not, the Swift compiler may silently miss the protocol requirement, resulting in sticky `SELECT *` requests. To verify your setup, see the [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) FAQ. ## Expressions @@ -4791,7 +5014,7 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli Player.filter(scoreColumn == maximumScore) ``` - > :point_up: **Note**: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See [string comparison](#string-comparison) if you need more control. + > **Note**: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See [string comparison](#string-comparison) if you need more control. - `*`, `/`, `+`, `-` @@ -4802,7 +5025,7 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli Planet.select((temperatureColumn * 1.8 + 32).forKey("fahrenheit")) ``` - > :point_up: **Note**: an expression like `nameColumn + "rrr"` will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation. See the `concat` operator below. + > **Note**: an expression like `nameColumn + "rrr"` will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation. See the `concat` operator below. When you want to join a sequence of expressions with the `+` or `*` operator, use `joined(operator:)`: @@ -4909,7 +5132,7 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli .filter(cte.contains(nameColumn)) ``` - > :point_up: **Note**: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See [string comparison](#string-comparison) if you need more control. + > **Note**: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See [string comparison](#string-comparison) if you need more control. - `EXISTS`, `NOT EXISTS` @@ -4966,7 +5189,7 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli Player.filter(emailColumn.like("%10\\%%", escape: "\\")) ``` - > :point_up: **Note**: the SQLite LIKE operator is case-insensitive but not Unicode-aware. For example, the expression `'a' LIKE 'A'` is true but `'æ' LIKE 'Æ'` is false. + > **Note**: the SQLite LIKE operator is case-insensitive but not Unicode-aware. For example, the expression `'a' LIKE 'A'` is true but `'æ' LIKE 'Æ'` is false. - `MATCH` @@ -5062,7 +5285,7 @@ GRDB comes with a Swift version of many SQLite [built-in functions](https://sqli Player.select(nameColumn.uppercased()) ``` - > :point_up: **Note**: When *comparing* strings, you'd rather use a [collation](#string-comparison): + > **Note**: When *comparing* strings, you'd rather use a [collation](#string-comparison): > > ```swift > let name: String = ... @@ -5147,7 +5370,7 @@ LIMIT ... -- 9 Such expression literals allow you to build a reusable support library of SQL functions or operators that are missing from the query interface. For example, you can define a Swift `date` function: ```swift - func date(_ value: SQLSpecificExpressible) -> SQLExpression { + func date(_ value: some SQLSpecificExpressible) -> SQLExpression { SQL("DATE(\(value))").sqlExpression } @@ -5429,7 +5652,7 @@ try Player .deleteAll(db) ``` -> :point_up: **Note** Deletion methods are available on types that adopt the [TableRecord] protocol, and `Table`: +> **Note** Deletion methods are available on types that adopt the [TableRecord] protocol, and `Table`: > > ```swift > struct Player: TableRecord { ... } @@ -5512,7 +5735,7 @@ 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 available on types that adopt the [TableRecord] protocol, and `Table`: +> **Note** The `updateAll` method is available on types that adopt the [TableRecord] protocol, and `Table`: > > ```swift > struct Player: TableRecord { ... } @@ -5598,7 +5821,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.26/Structs/AnyFetchRequest.html): a type-erased request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -5776,7 +5999,7 @@ Now we write a method that returns a [custom request](#custom-requests), and the ```swift extension PlayerInfo { /// The request for all player infos - static func all() -> AdaptedFetchRequest> { + static func all() -> some FetchRequest { ``` To acknowledge that both Player and Team records may customize their selection of the "player" and "team" columns, we'll write our SQL in a slightly different way: @@ -5815,7 +6038,7 @@ And since counting table columns require a database connection, we use the `adap } ``` -> :point_up: **Note**: `splittingRowAdapters` returns as many adapters as necessary to fully split a row. In the example above, it returns *three* adapters: one for player, one for team, and one for the remaining columns. +> **Note**: `splittingRowAdapters` returns as many adapters as necessary to fully split a row. In the example above, it returns *three* adapters: one for player, one for team, and one for the remaining columns. And finally, we can define the fetching method: @@ -5869,7 +6092,7 @@ struct PlayerInfo: Decodable, FetchableRecord { extension PlayerInfo { /// The request for all player infos - static func all() -> AdaptedFetchRequest> { + static func all() -> some FetchRequest { let request: SQLRequest = """ SELECT \(columnsOf: Player.self), @@ -5912,7 +6135,7 @@ Database Changes Observation GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways: -- [After Commit Hook](#after-commit-hook): Handle successful transactions one by one. +- [Transaction Hook](#transaction-hook): Handle transactions commits or rollbacks, one by one. - [ValueObservation]: Track changes of database values. - [DatabaseRegionObservation]: Tracking transactions that impact a database region. - [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation. @@ -5922,24 +6145,20 @@ GRDB puts this SQLite feature to some good use, and lets you observe the databas Database observation requires that a single [database queue](#database-queues) or [pool](#database-pools) is kept open for all the duration of the database usage. -## After Commit Hook +## Transaction Hook -When your application needs to make sure a specific database transaction has been successfully committed before it executes some work, use the `Database.afterNextTransactionCommit(_:)` method. - -Its closure argument is called right after database changes have been successfully written to disk: +When your application needs to make sure a specific database transaction has been successfully committed before it executes some work, use the `Database.afterNextTransaction(onCommit:onRollback:)` method. ```swift try dbQueue.write { db in - db.afterNextTransactionCommit { db in - print("success") + db.afterNextTransaction { db in + print("successful commit") } ... -} // prints "success" +} // prints "successful commit" ``` -The closure runs in a protected dispatch queue, serialized with all database updates. - -**This "after commit hook" helps synchronizing the database with other resources, such as files, or system sensors.** +**This hook helps synchronizing the database with other resources, such as files, or system sensors.** In the example below, a [location manager](https://developer.apple.com/documentation/corelocation/cllocationmanager) starts monitoring a CLRegion if and only if it has successfully been stored in the database: @@ -5955,7 +6174,7 @@ func startMonitoring(_ db: Database, region: CLRegion) throws { // Start monitoring if and only if the insertion is // eventually committed - db.afterNextTransactionCommit { _ in + db.afterNextTransaction { _ in // locationManager prefers the main queue: DispatchQueue.main.async { locationManager.startMonitoring(for: region) @@ -5987,7 +6206,7 @@ try dbQueue.write { db in Tracked changes are insertions, updates, and deletions that impact the tracked value, performed with the [query interface](#the-query-interface), or [raw SQL](#sqlite-api). This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). -> :point_up: **Note**: Some changes are not notified: changes to internal system tables (such as `sqlite\_master`), and changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables. +> **Note**: Some changes are not notified: changes to internal system tables (such as `sqlite\_master`), and changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables. **ValueObservation is the preferred GRDB tool for keeping your user interface synchronized with the database.** See the [Demo Applications] for sample code. @@ -6180,7 +6399,7 @@ class PlayersViewController: UIViewController { scheduling: .immediate, // <- immediate scheduler onError: { error in ... }, onChange: { [weak self] (players: [Player]) in - guard let self = self else { return } + guard let self else { return } self.updateView(players) }) // <- Here the view has already been updated. @@ -6262,7 +6481,7 @@ let request = Player.filter(id: 42) let observation = ValueObservation .tracking { db in try Row.fetchOne(db, request) } .removeDuplicates() // Row adopts Equatable - .map { row in row.map(Player.init(row:) } + .map { row in try row.map(Player.init(row:) } ``` This technique is also available for requests that involve [Associations]: @@ -6278,7 +6497,7 @@ let request = Team.including(all: Team.players) let observation = ValueObservation .tracking { db in try Row.fetchAll(db, request) } .removeDuplicates() // Row adopts Equatable - .map { rows in rows.map(TeamInfo.init(row:) } + .map { rows in try rows.map(TeamInfo.init(row:) } ``` @@ -6415,7 +6634,7 @@ let sharedObservation = ValueObservation // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` -> :point_up: **Note**: `ValueObservation` and `SharedValueObservation` are nearly identical, but there is a difference you should be aware of. `SharedValueObservation` has no [operator](#valueobservation-operators) such as `map`. As a replacement, you may, for example, use Combine apis: +> **Note**: `ValueObservation` and `SharedValueObservation` are nearly identical, but there is a difference you should be aware of. `SharedValueObservation` has no [operator](#valueobservation-operators) such as `map`. As a replacement, you may, for example, use Combine apis: > > ```swift > let sharedObservation = ValueObservation.tracking { ... }.shared(in: dbQueue) @@ -6562,11 +6781,11 @@ When needed, you can help GRDB optimize observations and reduce database content ## DatabaseRegionObservation -**DatabaseRegionObservation tracks changes in database [requests](#requests), and notifies each impactful [transaction](#transactions-and-savepoints).** +**DatabaseRegionObservation notifies all [transactions](#transactions-and-savepoints) that impact the tracked [requests](#requests).** Tracked changes are insertions, updates, and deletions that impact the tracked requests, performed with the [query interface](#the-query-interface), or [raw SQL](#sqlite-api). This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). -> :point_up: **Note**: Some changes are not notified: changes to internal system tables (such as `sqlite_master`), and changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables. +> **Note**: Some changes are not notified: changes to internal system tables (such as `sqlite_master`), and changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables. DatabaseRegionObservation calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check [ValueObservation] before using DatabaseRegionObservation. @@ -6576,19 +6795,23 @@ DatabaseRegionObservation calls your application right after changes have been c Define an observation by providing one or several requests to track: ```swift -// Track all players +// Track the full player table let observation = DatabaseRegionObservation(tracking: Player.all()) ``` Then start the observation from a [database queue](#database-queues) or [pool](#database-pools): ```swift -let observer = try observation.start(in: dbQueue) { (db: Database) in - print("Players were changed") +let cancellable = try observation.start( + in: dbQueue, + onError: { error in ... }, + onChange: { (db: Database) in + print("Players were changed") + }) } ``` -And enjoy the changes notifications: +Enjoy the changes notifications: ```swift try dbQueue.write { db in @@ -6597,42 +6820,73 @@ try dbQueue.write { db in // Prints "Players were changed" ``` -By default, the observation lasts until the observer returned by the `start` method is deinitialized. See [DatabaseRegionObservation.extent](#databaseregionobservationextent) for more details. +If the `start` method is called from a writing database access method, the observation of impactful transactions starts immediately. Otherwise, it blocks the current thread until a write access can be established. -You can also feed DatabaseRegionObservation with [DatabaseRegion], or any type which conforms to the [DatabaseRegionConvertible] protocol. For example: +**You stop the observation** by calling the `cancel()` method on the object returned by the `start` method. Cancellation is automatic when the cancellable is deinitialized: + +```swift +cancellable.cancel() +``` + +**You can feed DatabaseRegionObservation** with any type that conforms to the [DatabaseRegionConvertible] protocol: requests, [DatabaseRegion], `Table`, etc. For example: ```swift +// Observe the score column of the player table +let observation = DatabaseRegionObservation(tracking: Player.select(Column("score"))) + +// Observe the score column of the player table +let observation = DatabaseRegionObservation(tracking: SQLRequest("SELECT score FROM player")) + +// Observe both the player and team tables +let observation = DatabaseRegionObservation(tracking: Table("player"), Table("team")) + // Observe the full database -let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase) -let observer = try observation.start(in: dbQueue) { (db: Database) in - print("Database was changed") -} +let observation = DatabaseRegionObservation(tracking: .fullDatabase) ``` +**As a convenience**, DatabaseRegionObservation can be turned into a Combine publisher, or an RxSwift observable: -### DatabaseRegionObservation.extent - -The `extent` property lets you specify the duration of the observation. See [Observation Extent](#observation-extent) for more details: - +

+ Combine example + ```swift -// This observation lasts until the database connection is closed -var observation = DatabaseRegionObservation... -observation.extent = .databaseLifetime -_ = try observation.start(in: dbQueue) { db in ... } +import Combine +import GRDB + +let observation = DatabaseRegionObservation.tracking(Player.all()) + +let cancellable = observation.publisher(in: dbQueue).sink( + receiveCompletion: { completion in ... }, + receiveValue: { (db: Database) in + print("Players were changed") + }) ``` -The default extent is `.observerLifetime`: the observation stops when the observer returned by `start` is deinitialized. +See [Combine Support] for more information. -Regardless of the extent of an observation, you can always stop observation with the `remove(transactionObserver:)` method: +
+
+ RxSwift example + ```swift -// Start -let observer = try observation.start(in: dbQueue) { db in ... } +import GRDB +import RxGRDB +import RxSwift -// Stop -dbQueue.remove(transactionObserver: observer) +let observation = DatabaseRegionObservation.tracking(Player.all()) + +let disposable = observation.rx.changes(in: dbQueue).subscribe( + onNext: { (db: Database) in + print("Players were changed") + }, + onError: { error in ... }) ``` +See the companion library [RxGRDB] for more information. + +
+ ## TransactionObserver Protocol @@ -6689,9 +6943,9 @@ By default, database holds weak references to its transaction observers: they ar **A transaction observer is notified of all database changes**: inserts, updates and deletes. This includes indirect changes triggered by ON DELETE and ON UPDATE actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). -> :point_up: **Note**: Some changes are not notified: changes to internal system tables (such as `sqlite_master`), changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite). +> **Note**: Some changes are not notified: changes to internal system tables (such as `sqlite_master`), changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite). > -> :point_up: **Note**: Transactions performed during read-only database accesses are not notified. +> **Note**: Transactions performed during read-only database accesses are not notified. Notified changes are not actually written to disk until the [transaction](#transactions-and-savepoints) commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation: @@ -6755,9 +7009,9 @@ do { } ``` -> :point_up: **Note**: all callbacks are called in a protected dispatch queue, and serialized with all database updates. +> **Note**: all callbacks are called in a protected dispatch queue, and serialized with all database updates. > -> :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. +> **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. [DatabaseRegionObservation] and [ValueObservation] are based on the TransactionObserver protocol. @@ -6900,7 +7154,7 @@ DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track ch For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. -For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.26/Structs/DatabaseRegion.html). +For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/6.0.0-beta/Structs/DatabaseRegion.html). #### The DatabaseRegionConvertible Protocol @@ -6971,9 +7225,9 @@ This extra API can be activated in two ways: end ``` - > :warning: **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version. + > **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version. - > :point_up: **Note**: the `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option in `GCC_PREPROCESSOR_DEFINITIONS` defines some C function prototypes that are lacking from the system `` header. When Xcode eventually ships with an SDK that includes a complete header, you may get a compiler error about duplicate function definitions. When this happens, just remove this `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option. + > **Note**: the `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option in `GCC_PREPROCESSOR_DEFINITIONS` defines some C function prototypes that are lacking from the system `` header. When Xcode eventually ships with an SDK that includes a complete header, you may get a compiler error about duplicate function definitions. When this happens, just remove this `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option. 2. Use a [custom SQLite build] and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option. @@ -7063,7 +7317,7 @@ try dbPool.barrierWriteWithoutTransaction { db in } ``` -> :point_up: **Note**: When an application wants to keep on using a database queue or pool after the passphrase has changed, it is responsible for providing the correct passphrase to the `usePassphrase` method called in the database preparation function. Consider: +> **Note**: When an application wants to keep on using a database queue or pool after the passphrase has changed, it is responsible for providing the correct passphrase to the `usePassphrase` method called in the database preparation function. Consider: > > ```swift > // WRONG: this won't work across a passphrase change @@ -7081,9 +7335,9 @@ try dbPool.barrierWriteWithoutTransaction { db in > } > ``` -> :point_up: **Note**: The `DatabasePool.barrierWriteWithoutTransaction` method does not prevent [database snapshots](Documentation/Concurrency.md#database-snapshots) from accessing the database during the passphrase change, or after the new passphrase has been applied to the database. Those database accesses may throw errors. Applications should provide their own mechanism for invalidating open snapshots before the passphrase is changed. +> **Note**: The `DatabasePool.barrierWriteWithoutTransaction` method does not prevent [database snapshots](Documentation/Concurrency.md#database-snapshots) from accessing the database during the passphrase change, or after the new passphrase has been applied to the database. Those database accesses may throw errors. Applications should provide their own mechanism for invalidating open snapshots before the passphrase is changed. -> :point_up: **Note**: Instead of changing the passphrase "in place" as described here, you can also export the database in a new encrypted database that uses the new passphrase. See [Exporting a Database to an Encrypted Database](#exporting-a-database-to-an-encrypted-database). +> **Note**: Instead of changing the passphrase "in place" as described here, you can also export the database in a new encrypted database that uses the new passphrase. See [Exporting a Database to an Encrypted Database](#exporting-a-database-to-an-encrypted-database). ### Exporting a Database to an Encrypted Database @@ -7273,7 +7527,7 @@ try source.backup( If a call to `progress` throws when `backupProgress.isComplete == false`, the backup will be aborted and the error rethrown. However, if a call to `progress` throws when `backupProgress.isComplete == true`, the backup is unaffected and the error is silently ignored. -> :warning: **Warning**: Passing non-default values of `pagesPerStep` or `progress` to the backup methods is an advanced API intended to provide additional capabilities to expert users. GRDB's backup API provides a faithful, low-level wrapper to the underlying SQLite online backup API. GRDB's documentation is not a comprehensive substitute for the official SQLite [documentation of their backup API](https://www.sqlite.org/c3ref/backup_finish.html). +> **Warning**: Passing non-default values of `pagesPerStep` or `progress` to the backup methods is an advanced API intended to provide additional capabilities to expert users. GRDB's backup API provides a faithful, low-level wrapper to the underlying SQLite online backup API. GRDB's documentation is not a comprehensive substitute for the official SQLite [documentation of their backup API](https://www.sqlite.org/c3ref/backup_finish.html). ## Interrupt a Database @@ -7465,7 +7719,7 @@ do { Each DatabaseError has two codes: an `extendedResultCode` (see [extended result code](https://www.sqlite.org/rescode.html#extended_result_code_list)), and a less precise `resultCode` (see [primary result code](https://www.sqlite.org/rescode.html#primary_result_code_list)). Extended result codes are refinements of primary result codes, as `SQLITE_CONSTRAINT_FOREIGNKEY` is to `SQLITE_CONSTRAINT`, for example. -> :warning: **Warning**: SQLite has progressively introduced extended result codes across its versions. The [SQLite release notes](http://www.sqlite.org/changes.html) are unfortunately not quite clear about that: write your handling of extended result codes with care. +> **Warning**: SQLite has progressively introduced extended result codes across its versions. The [SQLite release notes](http://www.sqlite.org/changes.html) are unfortunately not quite clear about that: write your handling of extended result codes with care. ### PersistenceError @@ -7610,7 +7864,7 @@ Database.logError = { (resultCode, message) in } ``` -> :warning: **Warning**: Database.logError must be set before any database connection is opened. This includes the connections that your application opens with GRDB, but also connections opened by other tools, such as third-party libraries. Setting it after a connection has been opened is an SQLite misuse, and has no effect. +> **Warning**: Database.logError must be set before any database connection is opened. This includes the connections that your application opens with GRDB, but also connections opened by other tools, such as third-party libraries. Setting it after a connection has been opened is an SQLite misuse, and has no effect. See [The Error And Warning Log](https://sqlite.org/errlog.html) for more information. @@ -7675,7 +7929,7 @@ try db.create(table: "player") { t in let players = try Player.order(nameColumn).fetchAll(db) ``` -> :warning: **Warning**: SQLite *requires* host applications to provide the definition of any collation other than binary, nocase and rtrim. When a database file has to be shared or migrated to another SQLite library of platform (such as the Android version of your application), make sure you provide a compatible collation. +> **Warning**: SQLite *requires* host applications to provide the definition of any collation other than binary, nocase and rtrim. When a database file has to be shared or migrated to another SQLite library of platform (such as the Android version of your application), make sure you provide a compatible collation. If you can't or don't want to define the comparison behavior of a column (see warning above), you can still use an explicit collation in SQL requests and in the [query interface](#the-query-interface): @@ -7718,7 +7972,7 @@ dbPool.releaseMemory() This method blocks the current thread until all current database accesses are completed, and the memory collected. -> :warning: **Warning**: If `DatabasePool.releaseMemory()` is called while a long read is performed concurrently, then no other read access will be possible until this long read has completed, and the memory has been released. If this does not suit your application needs, look for the asynchronous options below: +> **Warning**: If `DatabasePool.releaseMemory()` is called while a long read is performed concurrently, then no other read access will be possible until this long read has completed, and the memory has been released. If this does not suit your application needs, look for the asynchronous options below: You can release memory in an asynchronous way as well: @@ -7924,7 +8178,7 @@ try dbQueue.read { db in If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](#database-configuration). -> :point_up: **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output. +> **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output. ## FAQ: General @@ -8264,7 +8518,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.26/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/6.0.0-beta/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). @@ -8379,6 +8633,14 @@ This protocol has been renamed [FetchableRecord] in GRDB 3.0. This protocol has been renamed [TableRecord] in GRDB 3.0. +#### Customizing the Persistence Methods + +This chapter was replaced with [Persistence Callbacks]. + +#### After Commit Hook + +This chapter was replaced with [Transaction Hook]. + #### ValueObservation and DatabaseRegionObservation This chapter has been superseded by [ValueObservation] and [DatabaseRegionObservation]. @@ -8405,7 +8667,7 @@ This chapter has [moved](Documentation/Concurrency.md#database-snapshots). #### DatabaseWriter and DatabaseReader Protocols -This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.26/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.26/Protocols/DatabaseWriter.html). +This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Protocols/DatabaseWriter.html). #### Asynchronous APIs @@ -8427,7 +8689,6 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests]. [common table expression]: Documentation/CommonTableExpressions.md [Common Table Expressions]: Documentation/CommonTableExpressions.md [Conflict Resolution]: #conflict-resolution -[Customizing the Persistence Methods]: #customizing-the-persistence-methods [Column Names Coding Strategies]: #column-names-coding-strategies [Date and UUID Coding Strategies]: #date-and-uuid-coding-strategies [Fetching from Requests]: #fetching-from-requests @@ -8442,6 +8703,7 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests]. [PersistableRecord]: #persistablerecord-protocol [Record Comparison]: #record-comparison [Record Customization Options]: #record-customization-options +[Persistence Callbacks]: #persistence-callbacks [TableRecord]: #tablerecord-protocol [ValueObservation]: #valueobservation [DatabaseRegionObservation]: #databaseregionobservation @@ -8458,8 +8720,10 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests]. [Sharing a Database]: Documentation/SharingADatabase.md [FAQ]: #faq [Database Observation]: #database-changes-observation -[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.26/Structs/SQLRequest.html +[SQLRequest]: http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Structs/SQLRequest.html [SQL literal]: Documentation/SQLInterpolation.md#sql-literal [Identifiable]: https://developer.apple.com/documentation/swift/identifiable [Query Interface Organization]: Documentation/QueryInterfaceOrganization.md [Database Configuration]: #database-configuration +[Persistence Methods]: #persistence-methods +[persistence methods]: #persistence-methods diff --git a/SQLiteCustom/GRDBDeploymentTarget.xcconfig b/SQLiteCustom/GRDBDeploymentTarget.xcconfig index 28b7b90cc..904204125 100644 --- a/SQLiteCustom/GRDBDeploymentTarget.xcconfig +++ b/SQLiteCustom/GRDBDeploymentTarget.xcconfig @@ -1,4 +1,4 @@ IPHONEOS_DEPLOYMENT_TARGET = 11.0 -MACOSX_DEPLOYMENT_TARGET = 10.10 -TVOS_DEPLOYMENT_TARGET = 9.0 -WATCHOS_DEPLOYMENT_TARGET = 2.0 +MACOSX_DEPLOYMENT_TARGET = 10.13 +TVOS_DEPLOYMENT_TARGET = 11.0 +WATCHOS_DEPLOYMENT_TARGET = 4.0 diff --git a/Scripts/swiftlint.yml b/Scripts/swiftlint.yml index 24ef59c58..dc8568d0c 100644 --- a/Scripts/swiftlint.yml +++ b/Scripts/swiftlint.yml @@ -8,6 +8,7 @@ disabled_rules: - file_length - force_cast - force_try + - for_where - function_body_length - function_parameter_count - identifier_name diff --git a/Sources/CSQLite/shim.h b/Sources/CSQLite/shim.h index be4cd9cf9..471b5432c 100644 --- a/Sources/CSQLite/shim.h +++ b/Sources/CSQLite/shim.h @@ -26,3 +26,24 @@ static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { } static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { } #endif + +// Expose APIs that are missing from system +#ifdef GRDB_SQLITE_ENABLE_PREUPDATE_HOOK +SQLITE_API void *sqlite3_preupdate_hook( + sqlite3 *db, + void(*xPreUpdate)( + void *pCtx, /* Copy of third arg to preupdate_hook() */ + sqlite3 *db, /* Database handle */ + int op, /* SQLITE_UPDATE, DELETE or INSERT */ + char const *zDb, /* Database name */ + char const *zName, /* Table name */ + sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ + sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ + ), + void* +); +SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **); +SQLITE_API int sqlite3_preupdate_count(sqlite3 *); +SQLITE_API int sqlite3_preupdate_depth(sqlite3 *); +SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **); +#endif /* GRDB_SQLITE_ENABLE_PREUPDATE_HOOK */ diff --git a/Support/GRDBDeploymentTarget.xcconfig b/Support/GRDBDeploymentTarget.xcconfig index f074b7e79..a3458605c 100644 --- a/Support/GRDBDeploymentTarget.xcconfig +++ b/Support/GRDBDeploymentTarget.xcconfig @@ -1,7 +1,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 11.0 -MACOSX_DEPLOYMENT_TARGET = 10.10 -TVOS_DEPLOYMENT_TARGET = 9.0 -WATCHOS_DEPLOYMENT_TARGET = 2.0 +MACOSX_DEPLOYMENT_TARGET = 10.13 +TVOS_DEPLOYMENT_TARGET = 11.0 +WATCHOS_DEPLOYMENT_TARGET = 4.0 //// Compile with all opt-in APIs //GCC_PREPROCESSOR_DEFINITIONS = $(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 diff --git a/Support/Info.plist b/Support/Info.plist index eb02d5730..9c0482a59 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.26.0 + 6.0.0-beta CFBundleSignature ???? CFBundleVersion diff --git a/TODO.md b/TODO.md index 12b64e2a9..b8fbe3ff3 100644 --- a/TODO.md +++ b/TODO.md @@ -17,31 +17,51 @@ ## 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 - [ ] Property wrapper that decodes dictionaries (but how to tell the key column?) - [X] See if SQLITE_FCNTL_DATA_VERSION could help working around the lack of snapshots in order to avoid double initial fetch of ValueObservation. Result: no, it does not look it returns values that are comparable between two distinct SQLite connections (from the initial reader, and from the writer thhat starts the observation) -- [ ] Grab all FTS tokens in a string -- [ ] GRDB 6: Swift 5.7 -- [ ] GRDB 6: any / some -- [ ] GRDB 6: primary associated types (cursor, requests, ...) -- [ ] GRDB 6: remove existential/generic duplicated methods -- [ ] GRDB 6: remove useless AnyXXX Type erasers -- [ ] GRDB 6: decoding errors -- [ ] GRDB 6: conflict resolution in persistence methods -- [ ] GRDB 6: UPSERT -- [ ] GRDB 6: support for RETURNING -- [ ] GRDB 6: allow mutating `update` (for timestamps) +- [X] Grab all FTS tokens in a string +- [NO] Can we generate EXISTS with association? `Team.annotated(with: Team.players.exists)` + No. We already have `Team.annotated(with: Team.players.isEmpty == false)`. + It does not use an EXISTS expression, but a JOIN, and this is better for + the internal consistency of the query interface, and the rules that deal + with association keys. +- [X] GRDB 6: have DatabaseRegionObservation produce DatabaseCancellable just as ValueObservation. +- [X] RangeReplaceableCollection should have append(contentsOf: cursor) - [ ] GRDB 6: choose persistence table +- [ ] GRDB 6: decoding errors + - [X] throwing FetchableRecord initializer FIRST + - [X] throwing Decodable FetchableRecord initializer SECOND + - [X] deal with as much value decoding error as possible + - [?] expose throwing row accessors +- [ ] GRDB 6: Batch insert & Batch insert RETURNING - https://stackoverflow.com/questions/1609637/is-it-possible-to-insert-multiple-rows-at-a-time-in-an-sqlite-database +- [ ] GRDB 6: INSERT or UPDATE columns to their default value +- [X] GRDB 6: afterNextTransactionCommit -> afterNextTransaction(onCommit:onRollback:) +- [ ] GRDB 6: encoding errors for record (`EncodableRecord.encode(to:)`) + - [X] throwing EncodableRecord.encode FIRST +- [?] GRDB 6: protocol-based record container? This could avoid computing & encoding values we do not need. +- [ ] GRDB 6: encoding & statement binding errors for database values (conversion to DatabaseValue, statement binding, etc) + - [ ] Prevent Date > 9999 from being encoded +- [X] GRDB 6: Swift 5.7 +- [X] GRDB 6: any / some +- [X] GRDB 6: primary associated types (cursor, requests, ...) +- [X] GRDB 6: remove existential/generic duplicated methods +- [ ] GRDB 6: remove useless AnyXXX Type erasers +- [X] GRDB 6: conflict resolution in persistence methods +- [X] GRDB 6: UPSERT +- [X] GRDB 6: support for RETURNING + - [X] Support for default values: `Player.insert(db, as: FullPlayer.self)` +- [?] GRDB 6: allow mutating `update` (for timestamps) +- [?] GRDB 6: let record choose persistence table (insert(into:) ?) +- [?] GRDB 6: Support opaque return types (macOS Catalina, iOS 13, tvOS 13, watchOS 6 and later: https://stackoverflow.com/questions/56518406) - [ ] Long run edition. Use case: user edits the database (CRUD) but the application wants to commit and the end of the editing session. * Create an edition SQLite connection with an open transaction (a new kind of DatabaseWriter with a save() method) * All other writes will fail with SQLITE_BUSY. Unless they are schedules in a target dispatch queue which is paused during the edition. - [ ] Can we use generated columns to makes it convenient to index on inserted JSON objects? https://github.com/apple/swift-package-manager/pull/3090#issuecomment-740091760 - [ ] Look at [@FetchRequest](https://developer.apple.com/documentation/swiftui/fetchrequest): managed object context is stored in the environment, and error processing happens somewhere else (where?). - [ ] Handle SQLITE_LIMIT_VARIABLE_NUMBER in deleteAll(_:keys:) and similar APIs. https://www.sqlite.org/limits.html -- [ ] Concurrent migrator / or not -- [ ] Subqueries: request.isEmpty / request.exists +- [X] Subqueries: ~request.isEmpty~ / [X] request.exists() - [ ] Subqueries: request.count - [ ] Extract one row from a hasMany association (the one with the maximum date, the one with a flag set, etc.) https://stackoverflow.com/questions/43188771/sqlite-join-query-most-recent-posts-by-each-user (failed PR: https://github.com/groue/GRDB.swift/pull/767) - [ ] Turn a hasMany to hasOne without first/last : hasMany(Book.self).filter(Column("isBest") /* assume a single book is flagged best */).asOne() diff --git a/Tests/CocoaPods/GRDBiOS-framework/AppDelegate.swift b/Tests/CocoaPods/GRDBiOS-framework/AppDelegate.swift index 0ecb34814..38d6b51bd 100644 --- a/Tests/CocoaPods/GRDBiOS-framework/AppDelegate.swift +++ b/Tests/CocoaPods/GRDBiOS-framework/AppDelegate.swift @@ -5,7 +5,7 @@ import UIKit class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { // Test GRDB - _ = DatabaseQueue() + _ = try! DatabaseQueue() // test SQLITE_ENABLE_FTS5 _ = FTS5.self diff --git a/Tests/CocoaPods/GRDBiOS-static/AppDelegate.swift b/Tests/CocoaPods/GRDBiOS-static/AppDelegate.swift index 0ecb34814..38d6b51bd 100644 --- a/Tests/CocoaPods/GRDBiOS-static/AppDelegate.swift +++ b/Tests/CocoaPods/GRDBiOS-static/AppDelegate.swift @@ -5,7 +5,7 @@ import UIKit class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { // Test GRDB - _ = DatabaseQueue() + _ = try! DatabaseQueue() // test SQLITE_ENABLE_FTS5 _ = FTS5.self diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 239d10277..c3b31290c 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -25,8 +25,6 @@ 56419D7624A54062004967E1 /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CA324A54054004967E1 /* DropFirstCursorTests.swift */; }; 56419D7724A54062004967E1 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CA424A54054004967E1 /* DatabaseCursorTests.swift */; }; 56419D7824A54062004967E1 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CA424A54054004967E1 /* DatabaseCursorTests.swift */; }; - 56419D7924A54062004967E1 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CA524A54054004967E1 /* RecordCopyTests.swift */; }; - 56419D7A24A54062004967E1 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CA524A54054004967E1 /* RecordCopyTests.swift */; }; 56419D7B24A54062004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CA624A54054004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 56419D7C24A54062004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CA624A54054004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 56419D7D24A54062004967E1 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CA724A54054004967E1 /* ValueObservationMapTests.swift */; }; @@ -466,7 +464,6 @@ 56419CA224A54054004967E1 /* TableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; 56419CA324A54054004967E1 /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; 56419CA424A54054004967E1 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; - 56419CA524A54054004967E1 /* RecordCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordCopyTests.swift; sourceTree = ""; }; 56419CA624A54054004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56419CA724A54054004967E1 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 56419CA824A54054004967E1 /* DatabasePoolFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolFunctionTests.swift; sourceTree = ""; }; @@ -924,7 +921,6 @@ 56419D5224A54060004967E1 /* QueryInterfaceRequestTests.swift */, 56419CDF24A54058004967E1 /* RawRepresentable+DatabaseValueConvertibleTests.swift */, 56419C9F24A54054004967E1 /* Record+QueryInterfaceRequestTests.swift */, - 56419CA524A54054004967E1 /* RecordCopyTests.swift */, 56419D0C24A5405B004967E1 /* RecordEditedTests.swift */, 56419CAE24A54054004967E1 /* RecordInitializersTests.swift */, 56419D4224A5405F004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift */, @@ -1265,7 +1261,6 @@ 56419E0524A54062004967E1 /* AssociationParallelSQLTests.swift in Sources */, 56419D8F24A54062004967E1 /* RecordUniqueIndexTests.swift in Sources */, 56419E4F24A54062004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, - 56419D7924A54062004967E1 /* RecordCopyTests.swift in Sources */, 56419E9F24A54063004967E1 /* FetchableRecordTests.swift in Sources */, 56419E3324A54062004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */, 56419DFF24A54062004967E1 /* DatabaseCollationTests.swift in Sources */, @@ -1491,7 +1486,6 @@ 56419E0624A54062004967E1 /* AssociationParallelSQLTests.swift in Sources */, 56419D9024A54062004967E1 /* RecordUniqueIndexTests.swift in Sources */, 56419E5024A54062004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, - 56419D7A24A54062004967E1 /* RecordCopyTests.swift in Sources */, 56419EA024A54063004967E1 /* FetchableRecordTests.swift in Sources */, 56419E3424A54062004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */, 56419E0024A54062004967E1 /* DatabaseCollationTests.swift in Sources */, @@ -1672,7 +1666,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.13; ONLY_ACTIVE_ARCH = YES; SWIFT_VERSION = 5.0; }; @@ -1706,7 +1700,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.13; SWIFT_VERSION = 5.0; }; name = Release; diff --git a/Tests/CocoaPods/SQLCipher3/Podfile b/Tests/CocoaPods/SQLCipher3/Podfile index 9d45a0d3e..c8066b3ae 100644 --- a/Tests/CocoaPods/SQLCipher3/Podfile +++ b/Tests/CocoaPods/SQLCipher3/Podfile @@ -1,4 +1,4 @@ -platform :macos, '10.10' +platform :macos, '10.13' use_frameworks! def common diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index dc6a20213..a92a67097 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -335,8 +335,6 @@ 5641A10F24A540A1004967E1 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419FA024A5409E004967E1 /* AssociationParallelDecodableRecordTests.swift */; }; 5641A11024A540A1004967E1 /* Row+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419FA124A5409E004967E1 /* Row+FoundationTests.swift */; }; 5641A11124A540A1004967E1 /* Row+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419FA124A5409E004967E1 /* Row+FoundationTests.swift */; }; - 5641A11224A540A1004967E1 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419FA224A5409E004967E1 /* RecordCopyTests.swift */; }; - 5641A11324A540A1004967E1 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419FA224A5409E004967E1 /* RecordCopyTests.swift */; }; 5641A11424A540A1004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419FA324A5409E004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; 5641A11524A540A1004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419FA324A5409E004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; 5641A11624A540A1004967E1 /* ValueObservationRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419FA424A5409E004967E1 /* ValueObservationRowTests.swift */; }; @@ -623,7 +621,6 @@ 56419F9F24A5409E004967E1 /* FoundationNSDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDataTests.swift; sourceTree = ""; }; 56419FA024A5409E004967E1 /* AssociationParallelDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelDecodableRecordTests.swift; sourceTree = ""; }; 56419FA124A5409E004967E1 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; - 56419FA224A5409E004967E1 /* RecordCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordCopyTests.swift; sourceTree = ""; }; 56419FA324A5409E004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; 56419FA424A5409E004967E1 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = ""; }; 56419FA524A5409E004967E1 /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; @@ -928,7 +925,6 @@ 56419F1724A54094004967E1 /* QueryInterfaceRequestTests.swift */, 56419F5324A54098004967E1 /* RawRepresentable+DatabaseValueConvertibleTests.swift */, 56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */, - 56419FA224A5409E004967E1 /* RecordCopyTests.swift */, 56419F2124A54094004967E1 /* RecordEditedTests.swift */, 56419F4824A54097004967E1 /* RecordInitializersTests.swift */, 56419F0C24A54093004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift */, @@ -1374,7 +1370,6 @@ 5641A05224A540A1004967E1 /* FTS3RecordTests.swift in Sources */, 5641A13424A540A1004967E1 /* DerivableRequestTests.swift in Sources */, 56419FF224A540A1004967E1 /* RecordWithColumnNameManglingTests.swift in Sources */, - 5641A11224A540A1004967E1 /* RecordCopyTests.swift in Sources */, 5641A03A24A540A1004967E1 /* SQLLiteralTests.swift in Sources */, 5641A02424A540A1004967E1 /* ValueObservationPrintTests.swift in Sources */, 5641A12024A540A1004967E1 /* AssociationHasManyThroughOrderingTests.swift in Sources */, @@ -1600,7 +1595,6 @@ 5641A05324A540A1004967E1 /* FTS3RecordTests.swift in Sources */, 5641A13524A540A1004967E1 /* DerivableRequestTests.swift in Sources */, 56419FF324A540A1004967E1 /* RecordWithColumnNameManglingTests.swift in Sources */, - 5641A11324A540A1004967E1 /* RecordCopyTests.swift in Sources */, 5641A03B24A540A1004967E1 /* SQLLiteralTests.swift in Sources */, 5641A02524A540A1004967E1 /* ValueObservationPrintTests.swift in Sources */, 5641A12124A540A1004967E1 /* AssociationHasManyThroughOrderingTests.swift in Sources */, @@ -1678,7 +1672,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.13; ONLY_ACTIVE_ARCH = YES; SWIFT_VERSION = 5.0; }; @@ -1712,7 +1706,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.13; SWIFT_VERSION = 5.0; }; name = Release; diff --git a/Tests/CocoaPods/SQLCipher4/Podfile b/Tests/CocoaPods/SQLCipher4/Podfile index d0124a874..d8cd6ce44 100644 --- a/Tests/CocoaPods/SQLCipher4/Podfile +++ b/Tests/CocoaPods/SQLCipher4/Podfile @@ -1,4 +1,4 @@ -platform :macos, '10.10' +platform :macos, '10.13' use_frameworks! def common diff --git a/Tests/CombineExpectations/PublisherExpectations/Finished.swift b/Tests/CombineExpectations/PublisherExpectations/Finished.swift index bea48c442..39fa11bfa 100644 --- a/Tests/CombineExpectations/PublisherExpectations/Finished.swift +++ b/Tests/CombineExpectations/PublisherExpectations/Finished.swift @@ -62,7 +62,7 @@ extension PublisherExpectations { /// } public func get() throws { try recorder.value { (_, completion, remainingElements, consume) in - guard let completion = completion else { + guard let completion else { consume(remainingElements.count) return } diff --git a/Tests/Crash/RecordCrashTests.swift b/Tests/Crash/RecordCrashTests.swift index 1e91bea28..604ded4e0 100644 --- a/Tests/Crash/RecordCrashTests.swift +++ b/Tests/Crash/RecordCrashTests.swift @@ -20,7 +20,7 @@ private class RecordWithNilPrimaryKey : Record { "records" } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["id"] = nil } } @@ -30,7 +30,7 @@ private class RecordForTableWithoutPrimaryKey : Record { "records" } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["name"] = "foo" } } @@ -40,7 +40,7 @@ private class RecordForTableWithMultipleColumnsPrimaryKey : Record { "records" } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["name"] = "foo" } } @@ -50,7 +50,7 @@ private class RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary : Record "records" } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["name"] = "foo" } } diff --git a/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.pbxproj b/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.pbxproj index d74f142e8..4d0fd10cd 100644 --- a/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.pbxproj +++ b/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.pbxproj @@ -342,7 +342,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.13; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; @@ -397,7 +397,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.13; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; SDKROOT = macosx; diff --git a/Tests/CustomSQLite/CustomSQLite/AppDelegate.swift b/Tests/CustomSQLite/CustomSQLite/AppDelegate.swift index 8e99054b9..12798376f 100644 --- a/Tests/CustomSQLite/CustomSQLite/AppDelegate.swift +++ b/Tests/CustomSQLite/CustomSQLite/AppDelegate.swift @@ -4,7 +4,7 @@ import GRDB @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { - _ = DatabaseQueue() + _ = try! DatabaseQueue() _ = FTS5() _ = sqlite3_preupdate_new(nil, 0, nil) } diff --git a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift index 9ffeffc51..aa4957c01 100644 --- a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift @@ -31,7 +31,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { return writer } - func test(reader: DatabaseReader) throws { + func test(reader: some DatabaseReader) throws { let publisher = reader.readPublisher(value: { db in try Player.fetchCount(db) }) @@ -40,11 +40,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { XCTAssertEqual(value, 0) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } } // MARK: - @@ -130,7 +129,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(reader: DatabaseReader) throws { + func test(reader: some DatabaseReader) throws { let publisher = reader.readPublisher(value: { db in try Row.fetchAll(db, sql: "THIS IS NOT SQL") }) @@ -143,11 +142,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { } } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } } // MARK: - @@ -162,7 +160,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { return writer } - func test(reader: DatabaseReader) throws { + func test(reader: some DatabaseReader) throws { let expectation = self.expectation(description: "") let semaphore = DispatchSemaphore(value: 0) let cancellable = reader @@ -181,11 +179,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } } // MARK: - @@ -200,7 +197,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { return writer } - func test(reader: DatabaseReader) { + func test(reader: some DatabaseReader) { let expectation = self.expectation(description: "") let cancellable = reader .readPublisher(value: { db in @@ -219,11 +216,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } } // MARK: - @@ -238,7 +234,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { return writer } - func test(reader: DatabaseReader) { + func test(reader: some DatabaseReader) { let queue = DispatchQueue(label: "test") let expectation = self.expectation(description: "") let cancellable = reader @@ -258,11 +254,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } } // MARK: - @@ -272,7 +267,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(reader: DatabaseReader) throws { + func test(reader: some DatabaseReader) throws { let publisher = reader.readPublisher(value: { db in try Player.createTable(db) }) @@ -284,11 +279,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { } } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } } } #endif diff --git a/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift index c03c2c07a..a870a0066 100644 --- a/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift @@ -29,7 +29,7 @@ class DatabaseRegionObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = DatabaseRegionObservation(tracking: Player.all()) .publisher(in: writer) .tryMap(Player.fetchCount) @@ -49,10 +49,9 @@ class DatabaseRegionObservationPublisherTests : XCTestCase { XCTAssertEqual(elements, [1, 3]) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // This is an usage test. Do the available APIs allow to prepend a @@ -71,7 +70,7 @@ class DatabaseRegionObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let expectation = self.expectation(description: "") let testSubject = PassthroughSubject() let testCancellable = testSubject @@ -108,10 +107,9 @@ class DatabaseRegionObservationPublisherTests : XCTestCase { observationCancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } } #endif diff --git a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift index a8fbb14c1..4f07e7960 100644 --- a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift @@ -31,7 +31,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { try XCTAssertEqual(writer.read(Player.fetchCount), 0) let publisher = writer.writePublisher(updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) @@ -41,10 +41,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { try XCTAssertEqual(writer.read(Player.fetchCount), 1) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -59,7 +58,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher(updates: { db -> Int in try Player(id: 1, name: "Arthur", score: 1000).insert(db) return try Player.fetchCount(db) @@ -69,10 +68,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { XCTAssertEqual(count, 1) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -82,7 +80,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher(updates: { db in try db.execute(sql: "THIS IS NOT SQL") }) @@ -95,10 +93,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testWritePublisherErrorRollbacksTransaction() throws { @@ -111,7 +108,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher(updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) try db.execute(sql: "THIS IS NOT SQL") @@ -127,10 +124,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { XCTAssertEqual(count, 0) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -145,7 +141,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let expectation = self.expectation(description: "") let semaphore = DispatchSemaphore(value: 0) let cancellable = writer @@ -164,10 +160,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -182,7 +177,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) { + func test(writer: Writer) { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 // value + completion let cancellable = writer @@ -203,10 +198,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -221,7 +215,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) { + func test(writer: Writer) { let queue = DispatchQueue(label: "test") let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 // value + completion @@ -243,10 +237,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -263,7 +256,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer .writePublisher( updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) }, @@ -273,10 +266,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { XCTAssertEqual(count, 1) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -286,7 +278,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer .writePublisher( updates: { _ in }, @@ -299,10 +291,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } // MARK: - @@ -312,7 +303,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher( updates: { db in try db.execute(sql: "THIS IS NOT SQL") }, thenRead: { _, _ in XCTFail("Should not read") }) @@ -325,10 +316,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testWriteThenReadPublisherWriteErrorRollbacksTransaction() throws { @@ -341,7 +331,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher( updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) @@ -359,10 +349,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { XCTAssertEqual(count, 0) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -374,7 +363,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher( updates: { _ in }, thenRead: { db, _ in try Row.fetchAll(db, sql: "THIS IS NOT SQL") }) @@ -387,10 +376,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } // MARK: - Regression tests @@ -425,10 +413,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { XCTAssertEqual(count, 1) } - try Test(repeatCount: 100, test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(repeatCount: 100, test).run { try setUp(DatabaseQueue()) } + try Test(repeatCount: 100, test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(repeatCount: 100, test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } } #endif diff --git a/Tests/GRDBCombineTests/Support.swift b/Tests/GRDBCombineTests/Support.swift index 88e194c50..bf9c1d3a7 100644 --- a/Tests/GRDBCombineTests/Support.swift +++ b/Tests/GRDBCombineTests/Support.swift @@ -51,7 +51,6 @@ final class Test { } } -#if compiler(>=5.6) && canImport(_Concurrency) @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) final class AsyncTest { // Raise the repeatCount in order to help spotting flaky tests. @@ -100,34 +99,7 @@ final class AsyncTest { } } } -#endif -#if compiler(>=5.3) -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) -public func assertNoFailure( - _ completion: Subscribers.Completion, - file: StaticString = #filePath, - line: UInt = #line) -{ - if case let .failure(error) = completion { - XCTFail("Unexpected completion failure: \(error)", file: file, line: line) - } -} - -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) -public func assertFailure( - _ completion: Subscribers.Completion, - file: StaticString = #filePath, - line: UInt = #line, - test: (ExpectedFailure) -> Void) -{ - if case let .failure(error) = completion, let expectedError = error as? ExpectedFailure { - test(expectedError) - } else { - XCTFail("Expected \(ExpectedFailure.self), got \(completion)", file: file, line: line) - } -} -#else @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func assertNoFailure( _ completion: Subscribers.Completion, @@ -153,5 +125,4 @@ public func assertFailure( } } #endif -#endif diff --git a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift index a30ed393a..eedd4afc3 100644 --- a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift +++ b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift @@ -31,7 +31,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = ValueObservation .trackingConstantRegion(Player.fetchCount) .publisher(in: writer) @@ -58,10 +58,9 @@ class ValueObservationPublisherTests : XCTestCase { } } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testDefaultSchedulerFirstValueIsEmittedAsynchronously() throws { @@ -74,7 +73,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let expectation = self.expectation(description: "") let semaphore = DispatchSemaphore(value: 0) let cancellable = ValueObservation @@ -92,10 +91,9 @@ class ValueObservationPublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testDefaultSchedulerError() throws { @@ -103,7 +101,7 @@ class ValueObservationPublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = ValueObservation .trackingConstantRegion { try $0.execute(sql: "THIS IS NOT SQL") } .publisher(in: writer) @@ -117,10 +115,9 @@ class ValueObservationPublisherTests : XCTestCase { } } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } // MARK: - Immediate Scheduler @@ -135,7 +132,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = ValueObservation .trackingConstantRegion(Player.fetchCount) .publisher(in: writer, scheduling: .immediate) @@ -162,10 +159,9 @@ class ValueObservationPublisherTests : XCTestCase { } } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testImmediateSchedulerEmitsFirstValueSynchronously() throws { @@ -178,7 +174,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let semaphore = DispatchSemaphore(value: 0) let testSubject = PassthroughSubject() let testCancellable = testSubject @@ -199,10 +195,9 @@ class ValueObservationPublisherTests : XCTestCase { observationCancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testImmediateSchedulerError() throws { @@ -210,7 +205,7 @@ class ValueObservationPublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = ValueObservation .trackingConstantRegion { try $0.execute(sql: "THIS IS NOT SQL") } .publisher(in: writer, scheduling: .immediate) @@ -224,10 +219,9 @@ class ValueObservationPublisherTests : XCTestCase { } } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } // MARK: - Demand @@ -272,7 +266,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let subscriber = DemandSubscriber() let expectation = self.expectation(description: "") @@ -292,10 +286,9 @@ class ValueObservationPublisherTests : XCTestCase { subscriber.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testDemandOneReceivesOneElement() throws { @@ -308,7 +301,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let subscriber = DemandSubscriber() let expectation = self.expectation(description: "") @@ -331,10 +324,9 @@ class ValueObservationPublisherTests : XCTestCase { subscriber.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testDemandOneDoesNotReceiveTwoElements() throws { @@ -347,7 +339,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let subscriber = DemandSubscriber() let expectation = self.expectation(description: "") expectation.isInverted = true @@ -374,10 +366,9 @@ class ValueObservationPublisherTests : XCTestCase { subscriber.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testDemandTwoReceivesTwoElements() throws { @@ -390,7 +381,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let subscriber = DemandSubscriber() let expectation = self.expectation(description: "") @@ -418,10 +409,9 @@ class ValueObservationPublisherTests : XCTestCase { subscriber.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - Regression Tests @@ -439,7 +429,7 @@ class ValueObservationPublisherTests : XCTestCase { var configuration = Configuration() configuration.targetQueue = DispatchQueue(label: "crash.test", qos: .userInitiated) - let database = DatabaseQueue(configuration: configuration) + let database = try DatabaseQueue(configuration: configuration) var migrator = DatabaseMigrator() migrator.registerMigration("v1") { (db) in diff --git a/Tests/GRDBTests/AssociationAggregateTests.swift b/Tests/GRDBTests/AssociationAggregateTests.swift index e16f00ab8..8f6338e92 100644 --- a/Tests/GRDBTests/AssociationAggregateTests.swift +++ b/Tests/GRDBTests/AssociationAggregateTests.swift @@ -43,7 +43,7 @@ private struct CustomTeamInfo: Decodable, FetchableRecord { class AssociationAggregateTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "team") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift index d68fdb353..a61ae6401 100644 --- a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift @@ -32,7 +32,7 @@ private struct PlayerWithTeamName: Decodable, FetchableRecord { var teamName: String? } -extension QueryInterfaceRequest where RowDecoder == Player { +private extension QueryInterfaceRequest { func filter(teamName: String) -> QueryInterfaceRequest { joining(required: PlayerWithOptionalTeam.team.filter(Column("name") == teamName)) } @@ -47,7 +47,7 @@ extension QueryInterfaceRequest where RowDecoder == Player { /// Test support for Decodable records class AssociationBelongsToDecodableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "teams") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift index 8c4eb67f5..b7569d318 100644 --- a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -20,8 +20,8 @@ private struct PlayerWithRequiredTeam: FetchableRecord { var player: Player var team: Team - init(row: Row) { - player = Player(row: row) + init(row: Row) throws { + player = try Player(row: row) team = row[Player.teamScope] } } @@ -30,8 +30,8 @@ private struct PlayerWithOptionalTeam: FetchableRecord { var player: Player var team: Team? - init(row: Row) { - player = Player(row: row) + init(row: Row) throws { + player = try Player(row: row) team = row[Player.teamScope] } } @@ -40,8 +40,8 @@ private struct PlayerWithTeamName: FetchableRecord { var player: Player var teamName: String? - init(row: Row) { - player = Player(row: row) + init(row: Row) throws { + player = try Player(row: row) teamName = row["teamName"] } } @@ -49,7 +49,7 @@ private struct PlayerWithTeamName: FetchableRecord { /// Test support for FetchableRecord records class AssociationBelongsToFetchableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "teams") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift index 11cbaf274..8b04ac643 100644 --- a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift @@ -19,7 +19,7 @@ private struct Player: Codable, FetchableRecord, PersistableRecord { /// Test row scopes class AssociationBelongsToRowScopeTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "teams") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift index 05f2a71cf..187de9ae9 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift @@ -27,7 +27,7 @@ private struct ExtendedB : TableRecord { /// Test SQL generation class AssociationBelongsToSQLDerivationTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationChainRowScopesTests.swift b/Tests/GRDBTests/AssociationChainRowScopesTests.swift index 582a74456..987d4047b 100644 --- a/Tests/GRDBTests/AssociationChainRowScopesTests.swift +++ b/Tests/GRDBTests/AssociationChainRowScopesTests.swift @@ -35,7 +35,7 @@ private struct D: Codable, FetchableRecord, PersistableRecord { /// Test row scopes class AssociationChainRowScopesTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationChainSQLTests.swift b/Tests/GRDBTests/AssociationChainSQLTests.swift index e00f12776..e944fe86c 100644 --- a/Tests/GRDBTests/AssociationChainSQLTests.swift +++ b/Tests/GRDBTests/AssociationChainSQLTests.swift @@ -30,7 +30,7 @@ private struct D: TableRecord { /// Test SQL generation class AssociationChainSQLTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationHasManyOrderingTests.swift b/Tests/GRDBTests/AssociationHasManyOrderingTests.swift index a66fb3061..40cada2b6 100644 --- a/Tests/GRDBTests/AssociationHasManyOrderingTests.swift +++ b/Tests/GRDBTests/AssociationHasManyOrderingTests.swift @@ -28,7 +28,7 @@ private struct TeamWithOptionalPlayers: Decodable, FetchableRecord, Equatable { /// A usage test for ordered hasMany association class AssociationHasManyOrderingTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "team") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift b/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift index 2db26ac54..52522c233 100644 --- a/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift +++ b/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift @@ -29,7 +29,7 @@ private struct TeamInfo: Decodable, FetchableRecord, Equatable { /// A usage test for ordered hasManyThrough association class AssociationHasManyThroughOrderingTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "team") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift index a1518b07a..8d24f0a37 100644 --- a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift @@ -27,7 +27,7 @@ private struct ExtendedB : TableRecord { /// Test SQL generation class AssociationHasOneSQLDerivationTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationHasOneThroughDecodableRecordTests.swift b/Tests/GRDBTests/AssociationHasOneThroughDecodableRecordTests.swift index ff7bb134d..dccbce7b4 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughDecodableRecordTests.swift @@ -41,7 +41,7 @@ private struct AWithRequiredBAndOptionalC: Decodable, FetchableRecord { /// Test support for FetchableRecord records class AssociationHasOneThroughDecodableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") diff --git a/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift b/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift index feb415424..ee45837bd 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift @@ -25,8 +25,8 @@ private struct AWithRequiredC: FetchableRecord { var a: A var c: C - init(row: Row) { - a = A(row: row) + init(row: Row) throws { + a = try A(row: row) c = row["c"] } } @@ -35,8 +35,8 @@ private struct AWithOptionalC: FetchableRecord { var a: A var c: C? - init(row: Row) { - a = A(row: row) + init(row: Row) throws { + a = try A(row: row) c = row["c"] } } @@ -46,8 +46,8 @@ private struct AWithRequiredBAndOptionalC: FetchableRecord { var b: B var c: C? - init(row: Row) { - a = A(row: row) + init(row: Row) throws { + a = try A(row: row) b = row["b"] c = row["c"] } @@ -57,8 +57,8 @@ private struct AWithCName: FetchableRecord { var a: A var cName: String? - init(row: Row) { - a = A(row: row) + init(row: Row) throws { + a = try A(row: row) cName = row["cName"] } } @@ -68,8 +68,8 @@ private struct AWithRequiredBNameAndOptionalCName: FetchableRecord { var bName: String var cName: String? - init(row: Row) { - a = A(row: row) + init(row: Row) throws { + a = try A(row: row) bName = row["bName"] cName = row["cName"] } @@ -78,7 +78,7 @@ private struct AWithRequiredBNameAndOptionalCName: FetchableRecord { /// Test support for FetchableRecord records class AssociationHasOneThroughFetchableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") diff --git a/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift b/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift index f07532c22..05981b01f 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift @@ -27,7 +27,7 @@ private struct C: Codable, FetchableRecord, PersistableRecord { /// Test row scopes class AssociationHasOneThroughRowscopeTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift index 1bfae259b..a9f4d9f07 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift @@ -30,7 +30,7 @@ private struct ExtendedC : TableRecord { /// Test SQL generation class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") diff --git a/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift index b2782e91b..b27807b79 100644 --- a/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift @@ -45,7 +45,7 @@ private struct AWithOptionalBD: Decodable, FetchableRecord { /// Test support for Decodable records class AssociationParallelDecodableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationParallelRowScopesTests.swift b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift index e05ab4fa3..17f9c4e57 100644 --- a/Tests/GRDBTests/AssociationParallelRowScopesTests.swift +++ b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift @@ -43,7 +43,7 @@ private struct D: Codable, FetchableRecord, PersistableRecord { /// Test row scopes class AssociationParallelRowScopesTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationParallelSQLTests.swift b/Tests/GRDBTests/AssociationParallelSQLTests.swift index 15aaa7610..9c1b42562 100644 --- a/Tests/GRDBTests/AssociationParallelSQLTests.swift +++ b/Tests/GRDBTests/AssociationParallelSQLTests.swift @@ -28,7 +28,7 @@ private struct D: TableRecord { /// Test SQL generation class AssociationParallelSQLTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift index 7db9f641f..f981209ba 100644 --- a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift @@ -21,7 +21,7 @@ private struct D: TableRecord, FetchableRecord, Decodable, Equatable { } class AssociationPrefetchingCodableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("cola1") @@ -93,7 +93,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: nil), @@ -109,7 +109,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: nil)) } @@ -141,7 +141,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: nil), @@ -157,7 +157,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: nil)) } @@ -185,7 +185,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ @@ -206,7 +206,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), @@ -225,7 +225,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ @@ -246,7 +246,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), @@ -265,7 +265,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ @@ -286,7 +286,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), @@ -321,7 +321,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ @@ -342,7 +342,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), @@ -377,7 +377,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs1: [ @@ -398,7 +398,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs1: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), @@ -434,7 +434,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [1]), @@ -450,7 +450,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [1])) } @@ -466,7 +466,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [1]), @@ -482,7 +482,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [1])) } @@ -517,7 +517,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ @@ -551,7 +551,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ Record.CInfo( @@ -587,7 +587,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: []), @@ -603,7 +603,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [])) } @@ -659,7 +659,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], @@ -705,7 +705,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], cs2: [ @@ -747,7 +747,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ @@ -777,7 +777,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ Record.CInfo( @@ -811,7 +811,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: []), @@ -827,7 +827,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [])) } @@ -883,7 +883,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], @@ -917,7 +917,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], cs2: [ @@ -950,7 +950,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), ds: [ @@ -972,7 +972,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), ds: [ D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), @@ -1010,7 +1010,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), ds1: [], @@ -1037,7 +1037,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), ds1: [], ds2: [ @@ -1077,7 +1077,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a: Record.AInfo( @@ -1109,7 +1109,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a: Record.AInfo( a: A(row: ["cola1": 1, "cola2": "a1"]), @@ -1130,7 +1130,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a: A(row: ["cola1": 1, "cola2": "a1"]), @@ -1160,7 +1160,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ @@ -1217,7 +1217,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a1: Record.AInfo( @@ -1257,7 +1257,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a1: Record.AInfo( a: A(row: ["cola1": 1, "cola2": "a1"]), @@ -1294,7 +1294,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), bs: [ @@ -1325,7 +1325,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), @@ -1447,7 +1447,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { .orderByPrimaryKey() let records = try XRecord.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ XRecord( xa: XA(row: ["cola1": 1, "cola2": "a1"]), xbs: [ @@ -1478,7 +1478,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { .orderByPrimaryKey() let records = try XRecord.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ XRecord( xa: XA(row: ["cola1": 1, "cola2": "a1"]), bs: [ @@ -1509,7 +1509,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { .orderByPrimaryKey() let records = try XRecord.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ XRecord( a: A(row: ["cola1": 1, "cola2": "a1"]), xbs: [ diff --git a/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift index 8589d33cd..6b597fe7b 100644 --- a/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift @@ -43,7 +43,7 @@ private struct D: TableRecord, FetchableRecord, Equatable { } class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("cola1") diff --git a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift index 7ea9a8095..b97580fbe 100644 --- a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift @@ -9,11 +9,11 @@ private struct CompoundPrimaryKey: TableRecord { } private struct CompoundPrimaryKeyChild: TableRecord { } class AssociationPrefetchingObservationTests: GRDBTestCase { - private func _assertRequestRegionEqual( + private func assertRequestRegionEqual( _ db: Database, _ request: QueryInterfaceRequest, - _ expectedDescriptions: [String], - file: StaticString, line: UInt) throws + _ expectedDescriptions: String..., + file: StaticString = #file, line: UInt = #line) throws { // Test DatabaseRegionConvertible do { @@ -31,28 +31,7 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { } } - // #file vs. #filePath dance - #if compiler(>=5.3) - private func assertRequestRegionEqual( - _ db: Database, - _ request: QueryInterfaceRequest, - _ expectedDescriptions: String..., - file: StaticString = #filePath, line: UInt = #line) throws - { - try _assertRequestRegionEqual(db, request, expectedDescriptions, file: file, line: line) - } - #else - private func assertRequestRegionEqual( - _ db: Database, - _ request: QueryInterfaceRequest, - _ expectedDescriptions: String..., - file: StaticString = #file, line: UInt = #line) throws - { - try _assertRequestRegionEqual(db, request, expectedDescriptions, file: file, line: line) - } - #endif - - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("cola1") diff --git a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift index 5cab99c6d..5962b2e7b 100644 --- a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift @@ -7,7 +7,7 @@ private struct C: TableRecord { } private struct D: TableRecord { } class AssociationPrefetchingRowTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("cola1") diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 6ac24fd6b..5a96828c6 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -7,7 +7,7 @@ private struct C: TableRecord { } private struct D: TableRecord { } class AssociationPrefetchingSQLTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { // A.hasMany(B) // A.hasMany(C) // B.belongsTo(A) @@ -1898,43 +1898,6 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } - func testLimit() throws { - struct Player: TableRecord { } - struct Team: TableRecord { - static let players = hasMany(Player.self) - } - - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { db in - try db.create(table: "team") { t in - t.autoIncrementedPrimaryKey("teamId") - } - try db.create(table: "player") { t in - t.autoIncrementedPrimaryKey("playerId") - t.column("parentId", .integer).references("team") - } - try db.execute(sql: "INSERT INTO team DEFAULT VALUES") - - do { - sqlQueries.removeAll() - let association = Team.players.limit(10, offset: 5) - let request = Team.including(all: association) - _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter(isSelectQuery) - XCTAssertEqual(selectQueries, [ - """ - SELECT * FROM "team" - """, - """ - SELECT *, "parentId" AS "grdb_parentId" \ - FROM "player" \ - WHERE "parentId" = 1 \ - LIMIT 10 OFFSET 5 - """]) - } - } - } - func testCTE() throws { struct Player: TableRecord { } struct Team: TableRecord { diff --git a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift index aa6bdf2f8..ba579efc3 100644 --- a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift +++ b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift @@ -30,7 +30,7 @@ private struct D: TableRecord, FetchableRecord, Decodable { } class AssociationRowScopeSearchTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in // 1. Prepare data try db.create(table: "a") { t in @@ -97,8 +97,8 @@ class AssociationRowScopeSearchTests: GRDBTestCase { var b: B var c: C var d: D - init(row: Row) { - a = A(row: row) + init(row: Row) throws { + a = try A(row: row) b = row["b"] c = row["c"] d = row["d"] diff --git a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift index 4948224c4..7dce1d24e 100644 --- a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift +++ b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift @@ -21,7 +21,7 @@ private struct B : TableRecord { /// user-defined table aliases, and expressions that involve several tables. class AssociationTableAliasTestsSQLTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/BackupTestCase.swift b/Tests/GRDBTests/BackupTestCase.swift index f4474f9b9..1d969c6cb 100644 --- a/Tests/GRDBTests/BackupTestCase.swift +++ b/Tests/GRDBTests/BackupTestCase.swift @@ -4,9 +4,9 @@ import XCTest class BackupTestCase: GRDBTestCase { // A "user" error simply for testing purposes - private class AbandonBackupError: Error {} + private struct AbandonBackupError: Error {} - private func setupBackupSource(_ writer: DatabaseWriter) throws -> Int { + private func setupBackupSource(_ writer: some DatabaseWriter) throws -> Int { try writer.write { db in try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") try db.execute(sql: "INSERT INTO items (id) VALUES (0)") @@ -22,14 +22,14 @@ class BackupTestCase: GRDBTestCase { return pageCount } - private func setupBackupDestination(_ writer: DatabaseWriter) throws { + private func setupBackupDestination(_ writer: some DatabaseWriter) throws { try writer.write { db in try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") try db.execute(sql: "INSERT INTO items (id) VALUES (1)") } } - func testDatabaseWriterBackup(from source: DatabaseWriter, to destination: DatabaseWriter) throws { + func testDatabaseWriterBackup(from source: some DatabaseWriter, to destination: some DatabaseWriter) throws { let sourceDbPageCount = try setupBackupSource(source) try setupBackupDestination(destination) @@ -80,7 +80,7 @@ class BackupTestCase: GRDBTestCase { } } - func testDatabaseBackup(from source: DatabaseWriter, to destination: DatabaseWriter) throws { + func testDatabaseBackup(from source: some DatabaseWriter, to destination: some DatabaseWriter) throws { let sourceDbPageCount = try setupBackupSource(source) try setupBackupDestination(destination) diff --git a/Tests/GRDBTests/ColumnExpressionTests.swift b/Tests/GRDBTests/ColumnExpressionTests.swift index eb1bdddcf..0cc77811b 100644 --- a/Tests/GRDBTests/ColumnExpressionTests.swift +++ b/Tests/GRDBTests/ColumnExpressionTests.swift @@ -172,7 +172,7 @@ class ColumnExpressionTests: GRDBTestCase { try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "player(full_name,id,score)[1,2,3]") // Test specific column updates - let player = Player(row: ["id": 1, "full_name": "Arthur", "score": 1000]) + let player = try Player(row: ["id": 1, "full_name": "Arthur", "score": 1000]) try? player.update(db, columns: [Player.Columns.name, Player.Columns.score]) XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"full_name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") @@ -220,7 +220,7 @@ class ColumnExpressionTests: GRDBTestCase { try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.CodingKeys.id)).databaseRegion(db).description, "player(full_name,id,score)[1,2,3]") // Test specific column updates - let player = Player(row: ["id": 1, "full_name": "Arthur", "score": 1000]) + let player = try Player(row: ["id": 1, "full_name": "Arthur", "score": 1000]) try? player.update(db, columns: [Player.CodingKeys.name, Player.CodingKeys.score]) XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"full_name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") diff --git a/Tests/GRDBTests/ColumnInfoTests.swift b/Tests/GRDBTests/ColumnInfoTests.swift index 31de2168c..87b759d7c 100644 --- a/Tests/GRDBTests/ColumnInfoTests.swift +++ b/Tests/GRDBTests/ColumnInfoTests.swift @@ -28,25 +28,7 @@ class ColumnInfoTests: GRDBTestCase { XCTAssertEqual(columns[0].name, "a") XCTAssertEqual(columns[0].isNotNull, false) XCTAssertEqual(columns[0].type, "INT") - // D. Richard Hipp wrote in SQLite mailing list on Tue Apr 30 22:43:47 EDT 2013 (http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html): - // - // > Re: Incorrect documentation for PRAGMA table_info (pk column) - // > - // > For SQLite 3.7.15 and earlier, the "pk" columns meaning was undocumented - // > and hence undefined. As it happened it was always 1. Beginning with - // > SQLite 3.7.16 we defined the meaning of the "pk" column to be the 1-based - // > index of the column in the primary key. - // - // https://sqlite.org/releaselog/3_7_16.html - // - // > Enhance the PRAGMA table_info command so that the "pk" column - // > is an increasing integer to show the order of columns in the - // > primary key. - if sqlite3_libversion_number() < 3007016 { - XCTAssertEqual(columns[0].primaryKeyIndex, 1) - } else { - XCTAssertEqual(columns[0].primaryKeyIndex, 2) - } + XCTAssertEqual(columns[0].primaryKeyIndex, 2) XCTAssertNil(columns[0].defaultValueSQL) XCTAssertEqual(columns[1].name, "b") @@ -176,6 +158,98 @@ class ColumnInfoTests: GRDBTestCase { #endif } + func testViews() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: """ + CREATE TABLE t ( + a INT, + b TEXT, + c VARCHAR(10), + d int DEFAULT NULL, + e Text NOT NULL DEFAULT 'foo', + "fooéı👨👨🏿🇫🇷🇨🇮" INT DEFAULT 0, + g INT DEFAULT 1e6, + h REAL DEFAULT 1.0, + i DATETIME DEFAULT CURRENT_TIMESTAMP, + j DATE DEFAULT (DATETIME('now', 'localtime')), + "" fooéı👨👨🏿🇫🇷🇨🇮, + PRIMARY KEY(c, a) + ); + CREATE VIEW v AS SELECT * FROM t; + """) + + let columns = try db.columns(in: "v") + XCTAssertEqual(columns.count, 11) + + XCTAssertEqual(columns[0].name, "a") + XCTAssertEqual(columns[0].isNotNull, false) + XCTAssertEqual(columns[0].type, "INT") + XCTAssertEqual(columns[0].primaryKeyIndex, 0) + XCTAssertNil(columns[0].defaultValueSQL) + + XCTAssertEqual(columns[1].name, "b") + XCTAssertEqual(columns[1].isNotNull, false) + XCTAssertEqual(columns[1].type, "TEXT") + XCTAssertEqual(columns[1].primaryKeyIndex, 0) + XCTAssertNil(columns[1].defaultValueSQL) + + XCTAssertEqual(columns[2].name, "c") + XCTAssertEqual(columns[2].isNotNull, false) + XCTAssertEqual(columns[2].type, "VARCHAR(10)") + XCTAssertEqual(columns[2].primaryKeyIndex, 0) + XCTAssertNil(columns[2].defaultValueSQL) + + XCTAssertEqual(columns[3].name, "d") + XCTAssertEqual(columns[3].isNotNull, false) + XCTAssertEqual(columns[3].type.uppercased(), "INT") // "int" or "INT" depending of SQLite version + XCTAssertEqual(columns[3].primaryKeyIndex, 0) + XCTAssertNil(columns[3].defaultValueSQL) + + XCTAssertEqual(columns[4].name, "e") + XCTAssertEqual(columns[3].isNotNull, false) + XCTAssertEqual(columns[4].type.uppercased(), "TEXT") // "Text" or "TEXT" depending of SQLite version + XCTAssertEqual(columns[4].primaryKeyIndex, 0) + XCTAssertNil(columns[4].defaultValueSQL) + + XCTAssertEqual(columns[5].name, "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual(columns[5].isNotNull, false) + XCTAssertEqual(columns[5].type, "INT") + XCTAssertEqual(columns[5].primaryKeyIndex, 0) + XCTAssertNil(columns[5].defaultValueSQL) + + XCTAssertEqual(columns[6].name, "g") + XCTAssertEqual(columns[6].isNotNull, false) + XCTAssertEqual(columns[6].type, "INT") + XCTAssertEqual(columns[6].primaryKeyIndex, 0) + XCTAssertNil(columns[6].defaultValueSQL) + + XCTAssertEqual(columns[7].name, "h") + XCTAssertEqual(columns[7].isNotNull, false) + XCTAssertEqual(columns[7].type, "REAL") + XCTAssertEqual(columns[7].primaryKeyIndex, 0) + XCTAssertNil(columns[7].defaultValueSQL) + + XCTAssertEqual(columns[8].name, "i") + XCTAssertEqual(columns[8].isNotNull, false) + XCTAssertEqual(columns[8].type, "DATETIME") + XCTAssertEqual(columns[8].primaryKeyIndex, 0) + XCTAssertNil(columns[8].defaultValueSQL) + + XCTAssertEqual(columns[9].name, "j") + XCTAssertEqual(columns[9].isNotNull, false) + XCTAssertEqual(columns[9].type, "DATE") + XCTAssertEqual(columns[9].primaryKeyIndex, 0) + XCTAssertNil(columns[9].defaultValueSQL) + + XCTAssertEqual(columns[10].name, "") + XCTAssertEqual(columns[10].isNotNull, false) + XCTAssertEqual(columns[10].type, "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual(columns[10].primaryKeyIndex, 0) + XCTAssertNil(columns[10].defaultValueSQL) + } + } + // Regression test for https://github.com/groue/GRDB.swift/issues/1124 // See also https://sqlite.org/forum/forumpost/721da02ba2 func testIssue1124() throws { diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index b0bd21231..589627683 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -52,7 +52,7 @@ private class UserDatabaseValueConvertible2 : DatabaseValueConvertible { #if SQLITE_ENABLE_FTS5 private class UserFTS5Tokenizer : FTS5Tokenizer { - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { preconditionFailure() } + func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt { preconditionFailure() } } #endif @@ -62,7 +62,7 @@ private class UserFTS5Tokenizer : FTS5Tokenizer { private class UserFTS5CustomTokenizer : FTS5CustomTokenizer { static let name: String = "UserFTS5CustomTokenizer" required init(db: Database, arguments: [String]) throws { preconditionFailure() } - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { preconditionFailure() } + func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt { preconditionFailure() } } #endif @@ -111,22 +111,26 @@ private class UserFetchableRecord2 : FetchableRecord { required init(row: Row) { } } +private struct UserFetchableRecord3 : FetchableRecord { + init(row: Row) throws { } +} + // MARK: - StatementColumnConvertible private struct UserStatementColumnConvertible1 : StatementColumnConvertible { - init?(sqliteStatement: SQLiteStatement, index: Int32) { } + init?(sqliteStatement: SQLiteStatement, index: CInt) { } } private struct UserStatementColumnConvertible2 : StatementColumnConvertible { - init(sqliteStatement: SQLiteStatement, index: Int32) { } + init(sqliteStatement: SQLiteStatement, index: CInt) { } } private class UserStatementColumnConvertible3 : StatementColumnConvertible { - required init?(sqliteStatement: SQLiteStatement, index: Int32) { } + required init?(sqliteStatement: SQLiteStatement, index: CInt) { } } private class UserStatementColumnConvertible4 : StatementColumnConvertible { - required init(sqliteStatement: SQLiteStatement, index: Int32) { } + required init(sqliteStatement: SQLiteStatement, index: CInt) { } } // MARK: - TableRecord @@ -153,7 +157,7 @@ private class UserTransactionObserver : TransactionObserver { private struct UserVirtualTableModule1 : VirtualTableModule { struct CustomTableDefinition { } let moduleName = "UserVirtualTableModule1" - func makeTableDefinition() -> CustomTableDefinition { preconditionFailure() } + func makeTableDefinition(configuration: VirtualTableConfiguration) -> CustomTableDefinition { preconditionFailure() } func moduleArguments(for definition: CustomTableDefinition, in db: Database) throws -> [String] { preconditionFailure() } func database(_ db: Database, didCreate tableName: String, using definition: CustomTableDefinition) throws { } } @@ -161,7 +165,7 @@ private struct UserVirtualTableModule1 : VirtualTableModule { private class UserVirtualTableModule2 : VirtualTableModule { struct CustomTableDefinition { } let moduleName = "UserVirtualTableModule2" - func makeTableDefinition() -> CustomTableDefinition { preconditionFailure() } + func makeTableDefinition(configuration: VirtualTableConfiguration) -> CustomTableDefinition { preconditionFailure() } func moduleArguments(for definition: CustomTableDefinition, in db: Database) throws -> [String] { preconditionFailure() } func database(_ db: Database, didCreate tableName: String, using definition: CustomTableDefinition) throws { } } diff --git a/Tests/GRDBTests/CompilationSubClassTests.swift b/Tests/GRDBTests/CompilationSubClassTests.swift index 37ba8f720..4dfe564dc 100644 --- a/Tests/GRDBTests/CompilationSubClassTests.swift +++ b/Tests/GRDBTests/CompilationSubClassTests.swift @@ -7,14 +7,57 @@ import GRDB private class UserRecord : Record { override init() { super.init() } - required init(row: Row) { super.init(row: row) } + required init(row: Row) throws { try super.init(row: row) } override class var databaseTableName: String { super.databaseTableName } override class var persistenceConflictPolicy: PersistenceConflictPolicy { super.persistenceConflictPolicy } - override class var databaseSelection: [SQLSelectable] { super.databaseSelection } - override func encode(to container: inout PersistenceContainer) { super.encode(to: &container) } - override func didInsert(with rowID: Int64, for column: String?) { super.didInsert(with: rowID, for: column) } - override func copy() -> Self { preconditionFailure() } - override func insert(_ db: Database) throws { try super.insert(db) } - override func update(_ db: Database, columns: Set) throws { try super.update(db, columns: columns) } - override func delete(_ db: Database) throws -> Bool { try super.delete(db) } + override class var databaseSelection: [any SQLSelectable] { super.databaseSelection } + override func encode(to container: inout PersistenceContainer) throws { try super.encode(to: &container) } + + override func willInsert(_ db: Database) throws { + try super.willInsert(db) + } + + override func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + try super.aroundInsert(db, insert: insert) + } + + override func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + } + + override func willUpdate(_ db: Database, columns: Set) throws { + try super.willUpdate(db, columns: columns) + } + + override func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + try super.aroundUpdate(db, columns: columns, update: update) + } + + override func didUpdate(_ updated: PersistenceSuccess) { + super.didUpdate(updated) + } + + override func willSave(_ db: Database) throws { + try super.willSave(db) + } + + override func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + try super.aroundSave(db, save: save) + } + + override func didSave(_ saved: PersistenceSuccess) { + super.didSave(saved) + } + + override func willDelete(_ db: Database) throws { + try super.willDelete(db) + } + + override func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + try super.aroundDelete(db, delete: delete) + } + + override func didDelete(deleted: Bool) { + super.didDelete(deleted: deleted) + } } diff --git a/Tests/GRDBTests/CursorTests.swift b/Tests/GRDBTests/CursorTests.swift index 3174db7b7..29930f223 100644 --- a/Tests/GRDBTests/CursorTests.swift +++ b/Tests/GRDBTests/CursorTests.swift @@ -5,13 +5,20 @@ private struct TestError : Error { } class CursorTests: GRDBTestCase { + func testIsEmpty() { + XCTAssertTrue(try AnyCursor([Int]()).isEmpty) + XCTAssertFalse(try AnyCursor([1]).isEmpty) + } + func testContainsEquatable() { XCTAssertTrue(try AnyCursor([1, 2]).contains(1)) + XCTAssertTrue(try AnyCursor([1, 2]).contains(2)) XCTAssertFalse(try AnyCursor([1, 2]).contains(3)) } func testContainsClosure() { XCTAssertTrue(try AnyCursor([1, 2]).contains { $0 == 1 }) + XCTAssertTrue(try AnyCursor([1, 2]).contains { $0 == 2 }) XCTAssertFalse(try AnyCursor([1, 2]).contains { $0 == 3 }) do { _ = try AnyCursor([1, 2]).contains { _ -> Bool in throw TestError() } @@ -195,6 +202,13 @@ class CursorTests: GRDBTestCase { let collection: [Int] = try collect(cursor, minimumCapacity: 100) XCTAssertEqual(collection, [1, 2, 1, 3]) } + + do { + let cursor = AnyCursor([1, 2, 1, 3]) + var collection = [0, 4] + try collection.append(contentsOf: cursor) + XCTAssertEqual(collection, [0, 4, 1, 2, 1, 3]) + } } func testSet() throws { diff --git a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift index a88eb8dd7..55d929fff 100644 --- a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift +++ b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift @@ -91,7 +91,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { } return dbWriter } - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let semaphore1 = DispatchSemaphore(value: 0) let semaphore2 = DispatchSemaphore(value: 0) @@ -138,7 +138,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { } return dbWriter } - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let semaphore1 = DispatchSemaphore(value: 0) let semaphore2 = DispatchSemaphore(value: 0) @@ -216,7 +216,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { } return dbWriter } - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let semaphore1 = DispatchSemaphore(value: 0) let semaphore2 = DispatchSemaphore(value: 0) @@ -267,7 +267,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { } return dbWriter } - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { do { try dbWriter.write { db in do { diff --git a/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift b/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift index 6d75276da..3daa8f55c 100644 --- a/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift +++ b/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift @@ -42,27 +42,28 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in - var transactionCount = 0 + var commitCount = 0 weak var deallocationWitness: Witness? = nil do { let witness = Witness() deallocationWitness = witness - db.afterNextTransactionCommit { _ in + // Usage test: single closure (the onCommit one) + db.afterNextTransaction { _ in // use witness withExtendedLifetime(witness, { }) - transactionCount += 1 + commitCount += 1 } } XCTAssertNotNil(deallocationWitness) - XCTAssertEqual(transactionCount, 0) + XCTAssertEqual(commitCount, 0) try db.execute(sql: startSQL) try db.execute(sql: endSQL) switch expectedCompletion { case .commit: - XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") case .rollback: - XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") } XCTAssertNil(deallocationWitness) @@ -72,9 +73,9 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { } switch expectedCompletion { case .commit: - XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") case .rollback: - XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") } } } @@ -84,28 +85,38 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in - var transactionCount = 0 + var commitCount = 0 + var rollbackCount = 0 try db.execute(sql: startSQL) weak var deallocationWitness: Witness? = nil do { let witness = Witness() deallocationWitness = witness - db.afterNextTransactionCommit { _ in - // use witness - withExtendedLifetime(witness, { }) - transactionCount += 1 - } + // Usage test: both closure + db.afterNextTransaction( + onCommit: { _ in + // use witness + withExtendedLifetime(witness, { }) + commitCount += 1 + }, + onRollback: { _ in + // use witness + withExtendedLifetime(witness, { }) + rollbackCount += 1 + }) } XCTAssertNotNil(deallocationWitness) - XCTAssertEqual(transactionCount, 0) + XCTAssertEqual(commitCount, 0) try db.execute(sql: endSQL) switch expectedCompletion { case .commit: - XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(rollbackCount, 0, "\(startSQL); \(endSQL)") case .rollback: - XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(rollbackCount, 1, "\(startSQL); \(endSQL)") } XCTAssertNil(deallocationWitness) @@ -115,9 +126,11 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { } switch expectedCompletion { case .commit: - XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(rollbackCount, 0, "\(startSQL); \(endSQL)") case .rollback: - XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(rollbackCount, 1, "\(startSQL); \(endSQL)") } } } diff --git a/Tests/GRDBTests/DatabaseColumnEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseColumnEncodingStrategyTests.swift index bc8e8e818..979557c05 100644 --- a/Tests/GRDBTests/DatabaseColumnEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseColumnEncodingStrategyTests.swift @@ -13,20 +13,20 @@ private struct ConvertToSnakeCaseRecord: PersistableRecord, Encodable { } class DatabaseColumnEncodingStrategyTests: GRDBTestCase { - func testUseDefaultKeys() { + func testUseDefaultKeys() throws { let record = UseDefaultKeysRecord(recordID: "test") var container = PersistenceContainer() - record.encode(to: &container) + try record.encode(to: &container) XCTAssertNil(container["record_id"]?.databaseValue.storage) XCTAssertEqual(container["recordID"]?.databaseValue.storage, "test".databaseValue.storage) } - func testConvertToSnakeCase() { + func testConvertToSnakeCase() throws { let record = ConvertToSnakeCaseRecord(recordID: "test") var container = PersistenceContainer() - record.encode(to: &container) + try record.encode(to: &container) XCTAssertNil(container["recordID"]?.databaseValue.storage) XCTAssertEqual(container["record_id"]?.databaseValue.storage, "test".databaseValue.storage) } diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index 9db22be08..79a5dcfbf 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -12,7 +12,7 @@ class DatabaseConfigurationTests: GRDBTestCase { connectionCount += 1 } - _ = DatabaseQueue(configuration: configuration) + _ = try DatabaseQueue(configuration: configuration) XCTAssertEqual(connectionCount, 1) _ = try makeDatabaseQueue(configuration: configuration) @@ -96,10 +96,8 @@ class DatabaseConfigurationTests: GRDBTestCase { XCTAssertEqual(foo, "foo") // Test SQLITE_DBCONFIG_DQS_DDL - if sqlite3_libversion_number() > 3008010 { - try dbQueue.inDatabase { db in - try db.execute(sql: "CREATE INDEX i ON player(\"foo\")") - } + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE INDEX i ON player(\"foo\")") } } diff --git a/Tests/GRDBTests/DatabaseCursorTests.swift b/Tests/GRDBTests/DatabaseCursorTests.swift index 8000ee6ef..d18191488 100644 --- a/Tests/GRDBTests/DatabaseCursorTests.swift +++ b/Tests/GRDBTests/DatabaseCursorTests.swift @@ -128,8 +128,8 @@ class DatabaseCursorTests: GRDBTestCase { self.isFlagged = isFlagged } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -260,7 +260,7 @@ class DatabaseCursorTests: GRDBTestCase { func testNullableDatabaseValueCursorStep() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in - let cursor: NullableDatabaseValueCursor = try Optional.fetchCursor(db, sql: profilingSQL) + let cursor: DatabaseValueCursor = try Optional.fetchCursor(db, sql: profilingSQL) while let _ = try cursor.next() { } } } @@ -269,7 +269,7 @@ class DatabaseCursorTests: GRDBTestCase { func testNullableDatabaseValueCursorForEach() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in - let cursor: NullableDatabaseValueCursor = try Optional.fetchCursor(db, sql: profilingSQL) + let cursor: DatabaseValueCursor = try Optional.fetchCursor(db, sql: profilingSQL) try cursor.forEach { _ in } } } @@ -296,7 +296,7 @@ class DatabaseCursorTests: GRDBTestCase { func testFastNullableDatabaseValueCursorStep() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in - let cursor: FastNullableDatabaseValueCursor = try Optional.fetchCursor(db, sql: profilingSQL) + let cursor: FastDatabaseValueCursor = try Optional.fetchCursor(db, sql: profilingSQL) while let _ = try cursor.next() { } } } @@ -305,7 +305,7 @@ class DatabaseCursorTests: GRDBTestCase { func testFastNullableDatabaseValueCursorForEach() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in - let cursor: FastNullableDatabaseValueCursor = try Optional.fetchCursor(db, sql: profilingSQL) + let cursor: FastDatabaseValueCursor = try Optional.fetchCursor(db, sql: profilingSQL) try cursor.forEach { _ in } } } diff --git a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift index b390ee7b7..fb97465bc 100644 --- a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift @@ -1,6 +1,6 @@ import Foundation import XCTest -import GRDB +@testable import GRDB // TODO: remove @testable when RowDecodingError is public private protocol StrategyProvider { static var strategy: DatabaseDateDecodingStrategy { get } @@ -22,7 +22,6 @@ private enum StrategyMillisecondsSince1970: StrategyProvider { static let strategy: DatabaseDateDecodingStrategy = .millisecondsSince1970 } -@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private enum StrategyIso8601: StrategyProvider { static let strategy: DatabaseDateDecodingStrategy = .iso8601 } @@ -191,27 +190,26 @@ extension DatabaseDateDecodingStrategyTests { XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the DateComponents -> Date conversion. Not a big deal. } - // TODO GRDB6: uncomment test -// // error -// do { -// try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "Yesterday") { date in -// XCTFail("Unexpected Date") -// } -// } catch let error as RowDecodingError { -// switch error { -// case .valueMismatch: -// XCTAssertEqual(error.description, """ -// could not decode Date from database value "Yesterday" - \ -// column: "date", \ -// column index: 0, \ -// row: [date:"Yesterday"], \ -// sql: `SELECT ? AS date`, \ -// arguments: ["Yesterday"] -// """) -// default: -// XCTFail("Unexpected Error") -// } -// } + // error + do { + try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "Yesterday") { date in + XCTFail("Unexpected Date") + } + } catch let error as RowDecodingError { + switch error { + case .valueMismatch: + XCTAssertEqual(error.description, """ + could not decode Date from database value "Yesterday" - \ + column: "date", \ + column index: 0, \ + row: [date:"Yesterday"], \ + sql: `SELECT ? AS date`, \ + arguments: ["Yesterday"] + """) + default: + XCTFail("Unexpected Error") + } + } } } } @@ -234,29 +232,28 @@ extension DatabaseDateDecodingStrategyTests { XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 123.456)) } - // TODO GRDB6: uncomment test -// // error -// do { -// try test(db, strategy: StrategyTimeIntervalSinceReferenceDate.self, databaseValue: "Yesterday") { date in -// // Decoding from SQLite statement works: -// // "Yesterday" is decoded as 0. -// XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 0)) -// } -// } catch let error as RowDecodingError { -// // Decoding from DatabaseValue does not work: -// // "Yesterday" is not decoded as 0. -// switch error { -// case .valueMismatch: -// XCTAssertEqual(error.description, """ -// could not decode Date from database value "Yesterday" - \ -// column: "date", \ -// column index: 0, \ -// row: [date:"Yesterday"] -// """) -// default: -// XCTFail("Unexpected Error") -// } -// } + // error + do { + try test(db, strategy: StrategyTimeIntervalSinceReferenceDate.self, databaseValue: "Yesterday") { date in + // Decoding from SQLite statement works: + // "Yesterday" is decoded as 0. + XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 0)) + } + } catch let error as RowDecodingError { + // Decoding from DatabaseValue does not work: + // "Yesterday" is not decoded as 0. + switch error { + case .valueMismatch: + XCTAssertEqual(error.description, """ + could not decode Date from database value "Yesterday" - \ + column: "date", \ + column index: 0, \ + row: [date:"Yesterday"] + """) + default: + XCTFail("Unexpected Error") + } + } } } } @@ -279,29 +276,28 @@ extension DatabaseDateDecodingStrategyTests { XCTAssertEqual(date, Date(timeIntervalSince1970: 123.456)) } - // TODO GRDB6: uncomment test -// // error -// do { -// try test(db, strategy: StrategyTimeIntervalSince1970.self, databaseValue: "Yesterday") { date in -// // Decoding from SQLite statement works: -// // "Yesterday" is decoded as 0. -// XCTAssertEqual(date, Date(timeIntervalSince1970: 0)) -// } -// } catch let error as RowDecodingError { -// // Decoding from DatabaseValue does not work: -// // "Yesterday" is not decoded as 0. -// switch error { -// case .valueMismatch: -// XCTAssertEqual(error.description, """ -// could not decode Date from database value "Yesterday" - \ -// column: "date", \ -// column index: 0, \ -// row: [date:"Yesterday"] -// """) -// default: -// XCTFail("Unexpected Error") -// } -// } + // error + do { + try test(db, strategy: StrategyTimeIntervalSince1970.self, databaseValue: "Yesterday") { date in + // Decoding from SQLite statement works: + // "Yesterday" is decoded as 0. + XCTAssertEqual(date, Date(timeIntervalSince1970: 0)) + } + } catch let error as RowDecodingError { + // Decoding from DatabaseValue does not work: + // "Yesterday" is not decoded as 0. + switch error { + case .valueMismatch: + XCTAssertEqual(error.description, """ + could not decode Date from database value "Yesterday" - \ + column: "date", \ + column index: 0, \ + row: [date:"Yesterday"] + """) + default: + XCTFail("Unexpected Error") + } + } } } } @@ -334,29 +330,28 @@ extension DatabaseDateDecodingStrategyTests { XCTAssertEqual(date, Date(timeIntervalSince1970: 123456.789 / 1000)) } - // TODO GRDB6: uncomment test -// // error -// do { -// try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: "Yesterday") { date in -// // Decoding from SQLite statement works: -// // "Yesterday" is decoded as 0. -// XCTAssertEqual(date, Date(timeIntervalSince1970: 0)) -// } -// } catch let error as RowDecodingError { -// // Decoding from DatabaseValue does not work: -// // "Yesterday" is not decoded as 0. -// switch error { -// case .valueMismatch: -// XCTAssertEqual(error.description, """ -// could not decode Date from database value "Yesterday" - \ -// column: "date", \ -// column index: 0, \ -// row: [date:"Yesterday"] -// """) -// default: -// XCTFail("Unexpected Error") -// } -// } + // error + do { + try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: "Yesterday") { date in + // Decoding from SQLite statement works: + // "Yesterday" is decoded as 0. + XCTAssertEqual(date, Date(timeIntervalSince1970: 0)) + } + } catch let error as RowDecodingError { + // Decoding from DatabaseValue does not work: + // "Yesterday" is not decoded as 0. + switch error { + case .valueMismatch: + XCTAssertEqual(error.description, """ + could not decode Date from database value "Yesterday" - \ + column: "date", \ + column index: 0, \ + row: [date:"Yesterday"] + """) + default: + XCTFail("Unexpected Error") + } + } } } } @@ -366,46 +361,43 @@ extension DatabaseDateDecodingStrategyTests { extension DatabaseDateDecodingStrategyTests { func testIso8601() throws { // check ISO8601DateFormatter availabiliity - if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { - try makeDatabaseQueue().read { db in - var calendar = Calendar(identifier: .gregorian) - calendar.timeZone = TimeZone(secondsFromGMT: 0)! - - // Null - try testNullDecoding(db, strategy: StrategyIso8601.self) - - // Date - try test(db, strategy: StrategyIso8601.self, databaseValue: "2018-08-19T17:18:07Z") { date in - XCTAssertEqual(calendar.component(.year, from: date), 2018) - XCTAssertEqual(calendar.component(.month, from: date), 8) - XCTAssertEqual(calendar.component(.day, from: date), 19) - XCTAssertEqual(calendar.component(.hour, from: date), 17) - XCTAssertEqual(calendar.component(.minute, from: date), 18) - XCTAssertEqual(calendar.component(.second, from: date), 7) - XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) + try makeDatabaseQueue().read { db in + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(secondsFromGMT: 0)! + + // Null + try testNullDecoding(db, strategy: StrategyIso8601.self) + + // Date + try test(db, strategy: StrategyIso8601.self, databaseValue: "2018-08-19T17:18:07Z") { date in + XCTAssertEqual(calendar.component(.year, from: date), 2018) + XCTAssertEqual(calendar.component(.month, from: date), 8) + XCTAssertEqual(calendar.component(.day, from: date), 19) + XCTAssertEqual(calendar.component(.hour, from: date), 17) + XCTAssertEqual(calendar.component(.minute, from: date), 18) + XCTAssertEqual(calendar.component(.second, from: date), 7) + XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) + } + + // error + do { + try test(db, strategy: StrategyIso8601.self, databaseValue: "Yesterday") { date in + XCTFail("Unexpected Date") + } + } catch let error as RowDecodingError { + switch error { + case .valueMismatch: + XCTAssertEqual(error.description, """ + could not decode Date from database value "Yesterday" - \ + column: "date", \ + column index: 0, \ + row: [date:"Yesterday"], \ + sql: `SELECT ? AS date`, \ + arguments: ["Yesterday"] + """) + default: + XCTFail("Unexpected Error") } - - // TODO GRDB6: uncomment test -// // error -// do { -// try test(db, strategy: StrategyIso8601.self, databaseValue: "Yesterday") { date in -// XCTFail("Unexpected Date") -// } -// } catch let error as RowDecodingError { -// switch error { -// case .valueMismatch: -// XCTAssertEqual(error.description, """ -// could not decode Date from database value "Yesterday" - \ -// column: "date", \ -// column index: 0, \ -// row: [date:"Yesterday"], \ -// sql: `SELECT ? AS date`, \ -// arguments: ["Yesterday"] -// """) -// default: -// XCTFail("Unexpected Error") -// } -// } } } } @@ -433,27 +425,26 @@ extension DatabaseDateDecodingStrategyTests { XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) } - // TODO GRDB6: uncomment test -// // error -// do { -// try test(db, strategy: StrategyFormatted.self, databaseValue: "Yesterday") { date in -// XCTFail("Unexpected Date") -// } -// } catch let error as RowDecodingError { -// switch error { -// case .valueMismatch: -// XCTAssertEqual(error.description, """ -// could not decode Date from database value "Yesterday" - \ -// column: "date", \ -// column index: 0, \ -// row: [date:"Yesterday"], \ -// sql: `SELECT ? AS date`, \ -// arguments: ["Yesterday"] -// """) -// default: -// XCTFail("Unexpected Error") -// } -// } + // error + do { + try test(db, strategy: StrategyFormatted.self, databaseValue: "Yesterday") { date in + XCTFail("Unexpected Date") + } + } catch let error as RowDecodingError { + switch error { + case .valueMismatch: + XCTAssertEqual(error.description, """ + could not decode Date from database value "Yesterday" - \ + column: "date", \ + column index: 0, \ + row: [date:"Yesterday"], \ + sql: `SELECT ? AS date`, \ + arguments: ["Yesterday"] + """) + default: + XCTFail("Unexpected Error") + } + } } } } @@ -471,27 +462,26 @@ extension DatabaseDateDecodingStrategyTests { XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 123456)) } - // TODO GRDB6: uncomment test -// // error -// do { -// try test(db, strategy: StrategyCustom.self, databaseValue: "invalid") { date in -// XCTFail("Unexpected Date") -// } -// } catch let error as RowDecodingError { -// switch error { -// case .valueMismatch: -// XCTAssertEqual(error.description, """ -// could not decode Date from database value "invalid" - \ -// column: "date", \ -// column index: 0, \ -// row: [date:"invalid"], \ -// sql: `SELECT ? AS date`, \ -// arguments: ["invalid"] -// """) -// default: -// XCTFail("Unexpected Error") -// } -// } + // error + do { + try test(db, strategy: StrategyCustom.self, databaseValue: "invalid") { date in + XCTFail("Unexpected Date") + } + } catch let error as RowDecodingError { + switch error { + case .valueMismatch: + XCTAssertEqual(error.description, """ + could not decode Date from database value "invalid" - \ + column: "date", \ + column index: 0, \ + row: [date:"invalid"], \ + sql: `SELECT ? AS date`, \ + arguments: ["invalid"] + """) + default: + XCTFail("Unexpected Error") + } + } } } } diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index 4247fb829..322310e7e 100644 --- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -26,7 +26,6 @@ private enum StrategyMillisecondsSince1970: StrategyProvider { static let strategy: DatabaseDateEncodingStrategy = .millisecondsSince1970 } -@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private enum StrategyIso8601: StrategyProvider { static let strategy: DatabaseDateEncodingStrategy = .iso8601 } @@ -51,14 +50,19 @@ private struct RecordWithDate: EncodableRecord, Enco var date: Date } +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension RecordWithDate: Identifiable { + var id: Date { date } +} + private struct RecordWithOptionalDate: EncodableRecord, Encodable { static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { Strategy.strategy } var date: Date? } @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) -extension RecordWithDate: Identifiable { - var id: Date { date } +extension RecordWithOptionalDate: Identifiable { + var id: Date? { date } } class DatabaseDateEncodingStrategyTests: GRDBTestCase { @@ -72,9 +76,10 @@ class DatabaseDateEncodingStrategyTests: GRDBTestCase { private func test( record: T, expectedStorage: DatabaseValue.Storage) + throws { var container = PersistenceContainer() - record.encode(to: &container) + try record.encode(to: &container) if let dbValue = container["date"]?.databaseValue { XCTAssertEqual(dbValue.storage, expectedStorage) } else { @@ -82,88 +87,88 @@ class DatabaseDateEncodingStrategyTests: GRDBTestCase { } } - private func test(strategy: Strategy.Type, encodesDate date: Date, as value: DatabaseValueConvertible) { - test(record: RecordWithDate(date: date), expectedStorage: value.databaseValue.storage) - test(record: RecordWithOptionalDate(date: date), expectedStorage: value.databaseValue.storage) + private func test(strategy: Strategy.Type, encodesDate date: Date, as value: DatabaseValueConvertible) throws { + try test(record: RecordWithDate(date: date), expectedStorage: value.databaseValue.storage) + try test(record: RecordWithOptionalDate(date: date), expectedStorage: value.databaseValue.storage) } - private func testNullEncoding(strategy: Strategy.Type) { - test(record: RecordWithOptionalDate(date: nil), expectedStorage: .null) + private func testNullEncoding(strategy: Strategy.Type) throws { + try test(record: RecordWithOptionalDate(date: nil), expectedStorage: .null) } } // MARK: - deferredToDate extension DatabaseDateEncodingStrategyTests { - func testDeferredToDate() { - testNullEncoding(strategy: StrategyDeferredToDate.self) + func testDeferredToDate() throws { + try testNullEncoding(strategy: StrategyDeferredToDate.self) for (date, value) in zip(testedDates, [ "1969-12-20 13:39:05.679", "1970-01-02 10:17:36.789", "2001-01-01 00:00:00.000", "2001-01-02 10:17:36.789", - ]) { test(strategy: StrategyDeferredToDate.self, encodesDate: date, as: value) } + ]) { try test(strategy: StrategyDeferredToDate.self, encodesDate: date, as: value) } } } // MARK: - timeIntervalSinceReferenceDate extension DatabaseDateEncodingStrategyTests { - func testTimeIntervalSinceReferenceDate() { - testNullEncoding(strategy: StrategyTimeIntervalSinceReferenceDate.self) + func testTimeIntervalSinceReferenceDate() throws { + try testNullEncoding(strategy: StrategyTimeIntervalSinceReferenceDate.self) for (date, value) in zip(testedDates, [ -979294854.321, -978183743.211, 0.0, 123456.789, - ]) { test(strategy: StrategyTimeIntervalSinceReferenceDate.self, encodesDate: date, as: value) } + ]) { try test(strategy: StrategyTimeIntervalSinceReferenceDate.self, encodesDate: date, as: value) } } } // MARK: - timeIntervalSince1970 extension DatabaseDateEncodingStrategyTests { - func testTimeIntervalSince1970() { - testNullEncoding(strategy: StrategyTimeIntervalSince1970.self) + func testTimeIntervalSince1970() throws { + try testNullEncoding(strategy: StrategyTimeIntervalSince1970.self) for (date, value) in zip(testedDates, [ -987654.32099997997, 123456.78900003433, 978307200.0, 978430656.789, - ]) { test(strategy: StrategyTimeIntervalSince1970.self, encodesDate: date, as: value) } + ]) { try test(strategy: StrategyTimeIntervalSince1970.self, encodesDate: date, as: value) } } } // MARK: - secondsSince1970 extension DatabaseDateEncodingStrategyTests { - func testSecondsSince1970() { - testNullEncoding(strategy: StrategySecondsSince1970.self) + func testSecondsSince1970() throws { + try testNullEncoding(strategy: StrategySecondsSince1970.self) for (date, value) in zip(testedDates, [ -987655, 123456, 978307200, 978430656, - ]) { test(strategy: StrategySecondsSince1970.self, encodesDate: date, as: value) } + ]) { try test(strategy: StrategySecondsSince1970.self, encodesDate: date, as: value) } } } // MARK: - millisecondsSince1970 extension DatabaseDateEncodingStrategyTests { - func testMillisecondsSince1970() { - testNullEncoding(strategy: StrategyMillisecondsSince1970.self) + func testMillisecondsSince1970() throws { + try testNullEncoding(strategy: StrategyMillisecondsSince1970.self) for (date, value) in zip(testedDates, [ -987654321, 123456789, 978307200000, 978430656789, - ] as [Int64]) { test(strategy: StrategyMillisecondsSince1970.self, encodesDate: date, as: value) } + ] as [Int64]) { try test(strategy: StrategyMillisecondsSince1970.self, encodesDate: date, as: value) } } } @@ -171,48 +176,44 @@ extension DatabaseDateEncodingStrategyTests { extension DatabaseDateEncodingStrategyTests { func testIso8601() throws { - guard #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) else { - throw XCTSkip("ISO8601DateFormatter is not available") - } - - testNullEncoding(strategy: StrategyIso8601.self) + try testNullEncoding(strategy: StrategyIso8601.self) for (date, value) in zip(testedDates, [ "1969-12-20T13:39:05Z", "1970-01-02T10:17:36Z", "2001-01-01T00:00:00Z", "2001-01-02T10:17:36Z", - ]) { test(strategy: StrategyIso8601.self, encodesDate: date, as: value) } + ]) { try test(strategy: StrategyIso8601.self, encodesDate: date, as: value) } } } // MARK: - formatted(DateFormatter) extension DatabaseDateEncodingStrategyTests { - func testFormatted() { - testNullEncoding(strategy: StrategyFormatted.self) + func testFormatted() throws { + try testNullEncoding(strategy: StrategyFormatted.self) for (date, value) in zip(testedDates, [ "Saturday, December 20, 1969 at 1:39:05 PM", "Friday, January 2, 1970 at 10:17:36 AM", "Monday, January 1, 2001 at 12:00:00 AM", "Tuesday, January 2, 2001 at 10:17:36 AM", - ]) { test(strategy: StrategyFormatted.self, encodesDate: date, as: value) } + ]) { try test(strategy: StrategyFormatted.self, encodesDate: date, as: value) } } } // MARK: - custom((Date) -> DatabaseValueConvertible?) extension DatabaseDateEncodingStrategyTests { - func testCustom() { - testNullEncoding(strategy: StrategyCustom.self) + func testCustom() throws { + try testNullEncoding(strategy: StrategyCustom.self) for (date, value) in zip(testedDates, [ "custom", "custom", "custom", "custom", - ]) { test(strategy: StrategyCustom.self, encodesDate: date, as: value) } + ]) { try test(strategy: StrategyCustom.self, encodesDate: date, as: value) } } } @@ -288,6 +289,48 @@ extension DatabaseDateEncodingStrategyTests { SELECT * FROM "t" WHERE "id" IN (-979294854.321, -978183743.211, 0.0, 123456.789) """) } + + do { + let request = Table>("t").filter(id: nil) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE 0 + """) + } + + do { + let request = Table>("t").filter(id: testedDates[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = '1969-12-20 13:39:05.679' + """) + } + + do { + let request = Table>("t").filter(ids: testedDates) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN ('1969-12-20 13:39:05.679', '1970-01-02 10:17:36.789', '2001-01-01 00:00:00.000', '2001-01-02 10:17:36.789') + """) + } + + do { + let request = Table>("t").filter(id: nil) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE 0 + """) + } + + do { + let request = Table>("t").filter(id: testedDates[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = -979294854.321 + """) + } + + do { + let request = Table>("t").filter(ids: testedDates) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN (-979294854.321, -978183743.211, 0.0, 123456.789) + """) + } } } @@ -326,6 +369,46 @@ extension DatabaseDateEncodingStrategyTests { DELETE FROM "t" WHERE "id" IN (-979294854.321, -978183743.211, 0.0, 123456.789) """) } + + do { + sqlQueries.removeAll() + try Table>("t").deleteOne(db, id: nil) + XCTAssertNil(lastSQLQuery) // Database not hit + } + + do { + try Table>("t").deleteOne(db, id: testedDates[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = '1969-12-20 13:39:05.679' + """) + } + + do { + try Table>("t").deleteAll(db, ids: testedDates) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN ('1969-12-20 13:39:05.679', '1970-01-02 10:17:36.789', '2001-01-01 00:00:00.000', '2001-01-02 10:17:36.789') + """) + } + + do { + sqlQueries.removeAll() + try Table>("t").deleteOne(db, id: nil) + XCTAssertNil(lastSQLQuery) // Database not hit + } + + do { + try Table>("t").deleteOne(db, id: testedDates[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = -979294854.321 + """) + } + + do { + try Table>("t").deleteAll(db, ids: testedDates) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN (-979294854.321, -978183743.211, 0.0, 123456.789) + """) + } } } } diff --git a/Tests/GRDBTests/DatabaseFunctionTests.swift b/Tests/GRDBTests/DatabaseFunctionTests.swift index cf1ed6335..8d252c6a8 100644 --- a/Tests/GRDBTests/DatabaseFunctionTests.swift +++ b/Tests/GRDBTests/DatabaseFunctionTests.swift @@ -31,18 +31,16 @@ class DatabaseFunctionTests: GRDBTestCase { let uppercase = DatabaseFunction.uppercase XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(uppercase.name)('jérÔME')"), "JÉRÔME") - if #available(OSX 10.11, *) { - // Locale-dependent tests. Are they fragile? - - let localizedCapitalize = DatabaseFunction.localizedCapitalize - XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(localizedCapitalize.name)('jérÔME')"), "Jérôme") - - let localizedLowercase = DatabaseFunction.localizedLowercase - XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(localizedLowercase.name)('jérÔME')"), "jérôme") - - let localizedUppercase = DatabaseFunction.localizedUppercase - XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(localizedUppercase.name)('jérÔME')"), "JÉRÔME") - } + // Locale-dependent tests. Are they fragile? + + let localizedCapitalize = DatabaseFunction.localizedCapitalize + XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(localizedCapitalize.name)('jérÔME')"), "Jérôme") + + let localizedLowercase = DatabaseFunction.localizedLowercase + XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(localizedLowercase.name)('jérÔME')"), "jérôme") + + let localizedUppercase = DatabaseFunction.localizedUppercase + XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(localizedUppercase.name)('jérÔME')"), "JÉRÔME") } } diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index c1384c914..144686272 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -4,24 +4,24 @@ import GRDB class DatabaseMigratorTests : GRDBTestCase { func testEmptyMigratorSync() throws { - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let migrator = DatabaseMigrator() try migrator.migrate(writer) } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testEmptyMigratorAsync() throws { - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let expectation = self.expectation(description: "") let migrator = DatabaseMigrator() - migrator.asyncMigrate(writer, completion: { db, error in + migrator.asyncMigrate(writer, completion: { dbResult in // No migration error - XCTAssertNil(error) + let db = try! dbResult.get() + // Write access try! db.execute(sql: "CREATE TABLE t(a)") expectation.fulfill() @@ -29,10 +29,9 @@ class DatabaseMigratorTests : GRDBTestCase { waitForExpectations(timeout: 5, handler: nil) } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testEmptyMigratorPublisher() throws { @@ -40,21 +39,20 @@ class DatabaseMigratorTests : GRDBTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let migrator = DatabaseMigrator() let publisher = migrator.migratePublisher(writer) let recorder = publisher.record() try wait(for: recorder.single, timeout: 1) } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testNonEmptyMigratorSync() throws { - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ @@ -92,14 +90,13 @@ class DatabaseMigratorTests : GRDBTestCase { } } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testNonEmptyMigratorAsync() throws { - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ @@ -125,16 +122,16 @@ class DatabaseMigratorTests : GRDBTestCase { } let expectation = self.expectation(description: "") - migrator.asyncMigrate(writer, completion: { (db, error) in + migrator.asyncMigrate(writer, completion: { dbResult in // No migration error - XCTAssertNil(error) + let db = try! dbResult.get() XCTAssertTrue(try! db.tableExists("persons")) XCTAssertTrue(try! db.tableExists("pets")) - migrator2.asyncMigrate(writer, completion: { db, error in + migrator2.asyncMigrate(writer, completion: { dbResult in // No migration error - XCTAssertNil(error) + let db = try! dbResult.get() XCTAssertTrue(try! db.tableExists("persons")) XCTAssertFalse(try! db.tableExists("pets")) @@ -144,10 +141,9 @@ class DatabaseMigratorTests : GRDBTestCase { waitForExpectations(timeout: 5, handler: nil) } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testNonEmptyMigratorPublisher() throws { @@ -155,7 +151,7 @@ class DatabaseMigratorTests : GRDBTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ @@ -201,10 +197,9 @@ class DatabaseMigratorTests : GRDBTestCase { } } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testEmptyMigratorPublisherIsAsynchronous() throws { @@ -212,7 +207,7 @@ class DatabaseMigratorTests : GRDBTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let migrator = DatabaseMigrator() let expectation = self.expectation(description: "") let semaphore = DispatchSemaphore(value: 0) @@ -228,10 +223,9 @@ class DatabaseMigratorTests : GRDBTestCase { cancellable.cancel() } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testNonEmptyMigratorPublisherIsAsynchronous() throws { @@ -239,7 +233,7 @@ class DatabaseMigratorTests : GRDBTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("first", migrate: { _ in }) let expectation = self.expectation(description: "") @@ -256,10 +250,9 @@ class DatabaseMigratorTests : GRDBTestCase { cancellable.cancel() } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testMigratorPublisherDefaultScheduler() throws { @@ -267,7 +260,7 @@ class DatabaseMigratorTests : GRDBTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) { + func test(writer: Writer) { var migrator = DatabaseMigrator() migrator.registerMigration("first", migrate: { _ in }) let expectation = self.expectation(description: "") @@ -286,10 +279,9 @@ class DatabaseMigratorTests : GRDBTestCase { cancellable.cancel() } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testMigratorPublisherCustomScheduler() throws { @@ -297,7 +289,7 @@ class DatabaseMigratorTests : GRDBTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) { + func test(writer: Writer) { var migrator = DatabaseMigrator() migrator.registerMigration("first", migrate: { _ in }) let queue = DispatchQueue(label: "test") @@ -317,14 +309,13 @@ class DatabaseMigratorTests : GRDBTestCase { cancellable.cancel() } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testMigrateUpTo() throws { - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("a") { db in try db.execute(sql: "CREATE TABLE a (id INTEGER PRIMARY KEY)") @@ -369,10 +360,9 @@ class DatabaseMigratorTests : GRDBTestCase { // try migrator.migrate(writer, upTo: "b") } - try Test(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testMigrationFailureTriggersRollback() throws { @@ -413,19 +403,26 @@ class DatabaseMigratorTests : GRDBTestCase { do { let expectation = self.expectation(description: "") let dbQueue = try makeDatabaseQueue() - migrator.asyncMigrate(dbQueue, completion: { db, error in + migrator.asyncMigrate(dbQueue, completion: { dbResult in // The first migration should be committed. // The second migration should be rollbacked. - let error = error as! DatabaseError + guard case let .failure(error as DatabaseError) = dbResult else { + XCTFail("Expected DatabaseError") + expectation.fulfill() + return + } + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.message, #"FOREIGN KEY constraint violation - from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) - let names = try! String.fetchAll(db, sql: "SELECT name FROM persons") - XCTAssertEqual(names, ["Arthur"]) - - expectation.fulfill() + dbQueue.asyncRead { dbResult in + let names = try! String.fetchAll(dbResult.get(), sql: "SELECT name FROM persons") + XCTAssertEqual(names, ["Arthur"]) + + expectation.fulfill() + } }) waitForExpectations(timeout: 5, handler: nil) } diff --git a/Tests/GRDBTests/DatabasePoolBackupTests.swift b/Tests/GRDBTests/DatabasePoolBackupTests.swift index 12eaac17e..c9a3287c4 100644 --- a/Tests/GRDBTests/DatabasePoolBackupTests.swift +++ b/Tests/GRDBTests/DatabasePoolBackupTests.swift @@ -4,14 +4,14 @@ class DatabasePoolBackupTests: BackupTestCase { func testDatabaseWriterBackup() throws { // SQLCipher can't backup encrypted databases: use a pristine Configuration - let source: DatabaseWriter = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) - let destination: DatabaseWriter = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) + let source = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) + let destination = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) try testDatabaseWriterBackup(from: source, to: destination) } func testDatabaseBackup() throws { - let source: DatabaseWriter = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) - let destination: DatabaseWriter = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) + let source = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) + let destination = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) try testDatabaseBackup(from: source, to: destination) } diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 87ce7c2e0..33327ba72 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -967,10 +967,6 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } func testTargetQueue() throws { - guard #available(OSX 10.12, tvOS 10.0, *) else { - throw XCTSkip("dispatchPrecondition(condition:) is not available") - } - func test(targetQueue: DispatchQueue) throws { dbConfiguration.targetQueue = targetQueue let dbPool = try makeDatabasePool() @@ -995,10 +991,6 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } func testWriteTargetQueue() throws { - guard #available(OSX 10.12, tvOS 10.0, *) else { - throw XCTSkip("dispatchPrecondition(condition:) is not available") - } - func test(targetQueue: DispatchQueue, writeTargetQueue: DispatchQueue) throws { dbConfiguration.targetQueue = targetQueue dbConfiguration.writeTargetQueue = writeTargetQueue @@ -1024,10 +1016,6 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } func testWriteTargetQueueReadOnly() throws { - guard #available(OSX 10.12, tvOS 10.0, *) else { - throw XCTSkip("dispatchPrecondition(condition:) is not available") - } - // Create a database before we perform read-only accesses _ = try makeDatabasePool(filename: "test") @@ -1049,10 +1037,6 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } func testQoS() throws { - guard #available(OSX 10.12, tvOS 10.0, *) else { - throw XCTSkip("dispatchPrecondition(condition:) is not available") - } - func test(qos: DispatchQoS) throws { // https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5 // @@ -1320,7 +1304,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { // Wait for read to start s1.wait() - dbPool.barrierWriteWithoutTransaction { _ in } + try! dbPool.barrierWriteWithoutTransaction { _ in } expectation.fulfill() s4.signal() } diff --git a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift index d12e73776..6e338372a 100644 --- a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift @@ -59,7 +59,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { // Simulate memory warning. NotificationCenter.default.post( - name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"), + name: UIApplication.didReceiveMemoryWarningNotification, object: nil) // Postcondition: reader connection was closed @@ -87,7 +87,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { // Simulate memory warning. NotificationCenter.default.post( - name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"), + name: UIApplication.didReceiveMemoryWarningNotification, object: nil) // Postcondition: no reader connection was closed @@ -108,7 +108,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { // Simulate memory warning. NotificationCenter.default.post( - name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"), + name: UIApplication.didReceiveMemoryWarningNotification, object: nil) // Make sure we can read diff --git a/Tests/GRDBTests/DatabaseQueueBackupTests.swift b/Tests/GRDBTests/DatabaseQueueBackupTests.swift index 2af8fc5dc..4bc739fd2 100644 --- a/Tests/GRDBTests/DatabaseQueueBackupTests.swift +++ b/Tests/GRDBTests/DatabaseQueueBackupTests.swift @@ -4,14 +4,14 @@ class DatabaseQueueBackupTests: BackupTestCase { func testDatabaseWriterBackup() throws { // SQLCipher can't backup encrypted databases: use a pristine Configuration - let source: DatabaseWriter = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) - let destination: DatabaseWriter = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) + let source = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) + let destination = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) try testDatabaseWriterBackup(from: source, to: destination) } func testDatabaseBackup() throws { - let source: DatabaseWriter = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) - let destination: DatabaseWriter = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) + let source = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) + let destination = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) try testDatabaseBackup(from: source, to: destination) } } diff --git a/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift b/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift index a325648b8..6de662006 100644 --- a/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift +++ b/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift @@ -4,7 +4,7 @@ import GRDB class DatabaseQueueInMemoryTests : GRDBTestCase { func testInMemoryDatabase() throws { - let dbQueue = DatabaseQueue() + let dbQueue = try DatabaseQueue() try dbQueue.inTransaction { db in try db.execute(sql: "CREATE TABLE foo (bar TEXT)") try db.execute(sql: "INSERT INTO foo (bar) VALUES ('baz')") diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 2e0331844..2c3f26d07 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -4,11 +4,8 @@ import GRDB class DatabaseQueueTests: GRDBTestCase { - // Until SPM tests can load resources, disable this test for SPM. - #if !SWIFT_PACKAGE func testInvalidFileFormat() throws { do { - let testBundle = Bundle(for: type(of: self)) let url = testBundle.url(forResource: "Betty", withExtension: "jpeg")! guard (try? Data(contentsOf: url)) != nil else { XCTFail("Missing file") @@ -23,7 +20,6 @@ class DatabaseQueueTests: GRDBTestCase { "file is not a database"].contains(error.message!)) } } - #endif func testAddRemoveFunction() throws { // Adding a function and then removing it should succeed @@ -125,10 +121,6 @@ class DatabaseQueueTests: GRDBTestCase { } func testTargetQueue() throws { - guard #available(OSX 10.12, tvOS 10.0, *) else { - throw XCTSkip("dispatchPrecondition(condition:) is not available") - } - func test(targetQueue: DispatchQueue) throws { dbConfiguration.targetQueue = targetQueue let dbQueue = try makeDatabaseQueue() @@ -153,10 +145,6 @@ class DatabaseQueueTests: GRDBTestCase { } func testWriteTargetQueue() throws { - guard #available(OSX 10.12, tvOS 10.0, *) else { - throw XCTSkip("dispatchPrecondition(condition:) is not available") - } - func test(targetQueue: DispatchQueue, writeTargetQueue: DispatchQueue) throws { dbConfiguration.targetQueue = targetQueue // unused dbConfiguration.writeTargetQueue = writeTargetQueue @@ -182,10 +170,6 @@ class DatabaseQueueTests: GRDBTestCase { } func testWriteTargetQueueReadOnly() throws { - guard #available(OSX 10.12, tvOS 10.0, *) else { - throw XCTSkip("dispatchPrecondition(condition:) is not available") - } - // Create a database before we perform read-only accesses _ = try makeDatabaseQueue(filename: "test") @@ -206,10 +190,6 @@ class DatabaseQueueTests: GRDBTestCase { } func testQoS() throws { - guard #available(OSX 10.12, tvOS 10.0, *) else { - throw XCTSkip("dispatchPrecondition(condition:) is not available") - } - func test(qos: DispatchQoS) throws { // https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5 // diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index d16284f8a..d2935629b 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -3,10 +3,10 @@ import GRDB class DatabaseReaderTests : GRDBTestCase { - func testAnyDatabaseReader() { + func testAnyDatabaseReader() throws { // This test passes if this code compiles. - let reader: DatabaseReader = DatabaseQueue() - let _: DatabaseReader = AnyDatabaseReader(reader) + let dbQueue = try DatabaseQueue() + let _: any DatabaseReader = AnyDatabaseReader(dbQueue) } // MARK: - Read @@ -30,7 +30,6 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabasePool()).makeSnapshot()) } -#if compiler(>=5.6) && canImport(_Concurrency) @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_ReadCanRead() async throws { func setup(_ dbWriter: T) throws -> T { @@ -50,7 +49,6 @@ class DatabaseReaderTests : GRDBTestCase { try await test(setup(makeDatabasePool())) try await test(setup(makeDatabasePool()).makeSnapshot()) } -#endif func testReadPreventsDatabaseModification() throws { func test(_ dbReader: DatabaseReader) throws { @@ -68,7 +66,6 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabasePool().makeSnapshot()) } -#if compiler(>=5.6) && canImport(_Concurrency) @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_ReadPreventsDatabaseModification() async throws { func test(_ dbReader: DatabaseReader) async throws { @@ -85,7 +82,7 @@ class DatabaseReaderTests : GRDBTestCase { try await test(makeDatabasePool()) try await test(makeDatabasePool().makeSnapshot()) } -#endif + // MARK: - UnsafeRead func testUnsafeReadCanRead() throws { @@ -107,7 +104,6 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabasePool()).makeSnapshot()) } -#if compiler(>=5.6) && canImport(_Concurrency) @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_UnsafeReadCanRead() async throws { func setup(_ dbWriter: T) throws -> T { @@ -127,7 +123,6 @@ class DatabaseReaderTests : GRDBTestCase { try await test(setup(makeDatabasePool())) try await test(setup(makeDatabasePool()).makeSnapshot()) } -#endif // MARK: - UnsafeReentrantRead diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift index dd62435d3..9e6f69fc7 100644 --- a/Tests/GRDBTests/DatabaseRegionObservationTests.swift +++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift @@ -8,33 +8,64 @@ class DatabaseRegionObservationTests: GRDBTestCase { try $0.execute(sql: "CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") try $0.execute(sql: "CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - + let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 3 - var observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase) - observation.extent = .databaseLifetime - + let observation = DatabaseRegionObservation(tracking: .fullDatabase) + var count = 0 - _ = try observation.start(in: dbQueue) { db in - count += 1 - notificationExpectation.fulfill() + let cancellable = observation.start( + in: dbQueue, + onError: { XCTFail("Unexpected error: \($0)") }, + onChange: { db in + count += 1 + notificationExpectation.fulfill() + }) + + try withExtendedLifetime(cancellable) { + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (2, 'foo')") + try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (2, 'foo')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 3) + } + } + + func testDatabaseRegionObservation_ImmediateCancellation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (1, 'foo')") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (1, 'foo')") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (2, 'foo')") - try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (2, 'foo')") - } - waitForExpectations(timeout: 1, handler: nil) + let notificationExpectation = expectation(description: "notification") + notificationExpectation.isInverted = true - XCTAssertEqual(count, 3) + let observation = DatabaseRegionObservation(tracking: .fullDatabase) + + let cancellable = observation.start( + in: dbQueue, + onError: { XCTFail("Unexpected error: \($0)") }, + onChange: { db in + notificationExpectation.fulfill() + }) + cancellable.cancel() + + try withExtendedLifetime(cancellable) { + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + } + waitForExpectations(timeout: 0.1, handler: nil) + } } func testDatabaseRegionObservationVariadic() throws { @@ -43,7 +74,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { try $0.execute(sql: "CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") try $0.execute(sql: "CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - + let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 3 @@ -51,28 +82,32 @@ class DatabaseRegionObservationTests: GRDBTestCase { let request1 = SQLRequest(sql: "SELECT * FROM t1 ORDER BY id") let request2 = SQLRequest(sql: "SELECT * FROM t2 ORDER BY id") - var observation = DatabaseRegionObservation(tracking: request1, request2) - observation.extent = .databaseLifetime - + let observation = DatabaseRegionObservation(tracking: request1, request2) + var count = 0 - _ = try observation.start(in: dbQueue) { db in - count += 1 - notificationExpectation.fulfill() - } + let cancellable = observation.start( + in: dbQueue, + onError: { XCTFail("Unexpected error: \($0)") }, + onChange: { db in + count += 1 + notificationExpectation.fulfill() + }) - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (1, 'foo')") + try withExtendedLifetime(cancellable) { + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (2, 'foo')") + try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (2, 'foo')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 3) } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (1, 'foo')") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (2, 'foo')") - try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (2, 'foo')") - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(count, 3) } func testDatabaseRegionObservationArray() throws { @@ -89,31 +124,35 @@ class DatabaseRegionObservationTests: GRDBTestCase { let request1 = SQLRequest(sql: "SELECT * FROM t1 ORDER BY id") let request2 = SQLRequest(sql: "SELECT * FROM t2 ORDER BY id") - var observation = DatabaseRegionObservation(tracking: [request1, request2]) - observation.extent = .databaseLifetime + let observation = DatabaseRegionObservation(tracking: [request1, request2]) var count = 0 - _ = try observation.start(in: dbQueue) { db in - count += 1 - notificationExpectation.fulfill() - } + let cancellable = observation.start( + in: dbQueue, + onError: { XCTFail("Unexpected error: \($0)") }, + onChange: { db in + count += 1 + notificationExpectation.fulfill() + }) - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (1, 'foo')") + try withExtendedLifetime(cancellable) { + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (2, 'foo')") + try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (2, 'foo')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 3) } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (1, 'foo')") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (2, 'foo')") - try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (2, 'foo')") - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(count, 3) } - func testDatabaseRegionDefaultExtent() throws { + func testDatabaseRegionDefaultCancellation() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } @@ -125,12 +164,15 @@ class DatabaseRegionObservationTests: GRDBTestCase { var count = 0 do { - let observer = try observation.start(in: dbQueue) { db in - count += 1 - notificationExpectation.fulfill() - } + let cancellable = observation.start( + in: dbQueue, + onError: { XCTFail("Unexpected error: \($0)") }, + onChange: { db in + count += 1 + notificationExpectation.fulfill() + }) - try withExtendedLifetime(observer) { + try withExtendedLifetime(cancellable) { try dbQueue.write { db in try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") } @@ -156,29 +198,38 @@ class DatabaseRegionObservationTests: GRDBTestCase { notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 1 - var observation = DatabaseRegionObservation(tracking: SQLRequest(sql: "SELECT * FROM t ORDER BY id")) - observation.extent = .nextTransaction + let observation = DatabaseRegionObservation(tracking: SQLRequest(sql: "SELECT * FROM t ORDER BY id")) var count = 0 - _ = try observation.start(in: dbQueue) { db in - count += 1 - notificationExpectation.fulfill() - } + var cancellable: AnyDatabaseCancellable? + cancellable = observation.start( + in: dbQueue, + onError: { XCTFail("Unexpected error: \($0)") }, + onChange: { db in + cancellable?.cancel() + count += 1 + notificationExpectation.fulfill() + }) - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try withExtendedLifetime(cancellable) { + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + } + // not notified + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 1) } - // not notified - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(count, 1) } // Regression test for https://github.com/groue/GRDB.swift/issues/514 // TODO: uncomment and make this test pass. + // Well, actually, selecting only the rowid has SQLite authorizer advertise + // that we select the whole table. This creates undesired database + // observation notifications. // func testIssue514() throws { // let dbQueue = try makeDatabaseQueue() // try dbQueue.write { db in @@ -192,11 +243,14 @@ class DatabaseRegionObservationTests: GRDBTestCase { // let observation = DatabaseRegionObservation(tracking: Gallery.select(Column("id"))) // // var notificationCount = 0 -// let observer = try observation.start(in: dbQueue) { _ in -// notificationCount += 1 -// } +// let cancellable = observation.start( +// in: dbQueue, +// onError: { XCTFail("Unexpected error: \($0)") }, +// onChange: { _ in +// notificationCount += 1 +// }) // -// try withExtendedLifetime(observer) { +// try withExtendedLifetime(cancellable) { // try dbQueue.write { db in // try db.execute(sql: "INSERT INTO gallery (id, status) VALUES (NULL, 0)") // } diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 860ab1d17..11a02dedd 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -8,12 +8,12 @@ class DatabaseRegionTests : GRDBTestCase { let regions = [ DatabaseRegion.fullDatabase, DatabaseRegion(), - DatabaseRegion.fullTable("foo"), + DatabaseRegion(table: "foo"), DatabaseRegion(table: "foo", columns: ["a", "b"]), DatabaseRegion(table: "foo", columns: ["b", "c"]), DatabaseRegion(table: "foo", rowIds: [1, 2]), DatabaseRegion(table: "foo", rowIds: [2, 3]), - DatabaseRegion.fullTable("bar")] + DatabaseRegion(table: "bar")] for (i1, s1) in regions.enumerated() { for (i2, s2) in regions.enumerated() { @@ -27,8 +27,8 @@ class DatabaseRegionTests : GRDBTestCase { // Case insensitivity XCTAssertEqual( - DatabaseRegion.fullTable("foo"), - DatabaseRegion.fullTable("FOO")) + DatabaseRegion(table: "foo"), + DatabaseRegion(table: "FOO")) XCTAssertEqual( DatabaseRegion(table: "foo", columns: ["a", "b"]), DatabaseRegion(table: "FOO", columns: ["A", "B"])) @@ -38,12 +38,12 @@ class DatabaseRegionTests : GRDBTestCase { let regions = [ DatabaseRegion.fullDatabase, DatabaseRegion(), - DatabaseRegion.fullTable("foo"), + DatabaseRegion(table: "foo"), DatabaseRegion(table: "foo", columns: ["a", "b"]), DatabaseRegion(table: "foo", columns: ["b", "c"]), DatabaseRegion(table: "foo", rowIds: [1, 2]), DatabaseRegion(table: "foo", rowIds: [2, 3]), - DatabaseRegion.fullTable("bar")] + DatabaseRegion(table: "bar")] var unions: [DatabaseRegion] = [] for s1 in regions { @@ -146,12 +146,12 @@ class DatabaseRegionTests : GRDBTestCase { let regions = [ DatabaseRegion.fullDatabase, DatabaseRegion(), - DatabaseRegion.fullTable("foo"), + DatabaseRegion(table: "foo"), DatabaseRegion(table: "foo", columns: ["a", "b"]), DatabaseRegion(table: "foo", columns: ["b", "c"]), DatabaseRegion(table: "foo", rowIds: [1, 2]), DatabaseRegion(table: "foo", rowIds: [2, 3]), - DatabaseRegion.fullTable("bar")] + DatabaseRegion(table: "bar")] var intersection: [DatabaseRegion] = [] for s1 in regions { @@ -251,14 +251,6 @@ class DatabaseRegionTests : GRDBTestCase { } func testSelectStatement_rowid() throws { - guard #available(iOS 11, *, tvOS 11) else { - // iOS 10.3.1 is not testable on Big Sur :-( - // This test breaks on iOS 10.3.1, with no known bad consequence. - // However this test is useful as a reminder of the behavior of - // the SQLite authorizer (rowid is not *precisely* observable). - throw XCTSkip("Skip test for rowid region with old SQLite version") - } - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (id INTEGER PRIMARY KEY, name TEXT)") @@ -266,13 +258,13 @@ class DatabaseRegionTests : GRDBTestCase { do { // Select the rowid let statement = try db.makeStatement(sql: "SELECT id FROM foo") - let expectedRegion = DatabaseRegion.fullTable("foo") + let expectedRegion = DatabaseRegion(table: "foo") XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(*)") } do { let statement = try db.makeStatement(sql: "SELECT ID FROM FOO") - let expectedRegion = DatabaseRegion.fullTable("foo") + let expectedRegion = DatabaseRegion(table: "foo") XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(*)") } @@ -313,27 +305,15 @@ class DatabaseRegionTests : GRDBTestCase { } do { let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM foo") - if sqlite3_libversion_number() < 3019000 { - let expectedRegion = DatabaseRegion.fullDatabase - XCTAssertEqual(statement.databaseRegion, expectedRegion) - XCTAssertEqual(statement.databaseRegion.description, "full database") - } else { - let expectedRegion = DatabaseRegion.fullTable("foo") - XCTAssertEqual(statement.databaseRegion, expectedRegion) - XCTAssertEqual(statement.databaseRegion.description, "foo(*)") - } + let expectedRegion = DatabaseRegion(table: "foo") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "foo(*)") } do { let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM FOO") - if sqlite3_libversion_number() < 3019000 { - let expectedRegion = DatabaseRegion.fullDatabase - XCTAssertEqual(statement.databaseRegion, expectedRegion) - XCTAssertEqual(statement.databaseRegion.description, "full database") - } else { - let expectedRegion = DatabaseRegion.fullTable("foo") - XCTAssertEqual(statement.databaseRegion, expectedRegion) - XCTAssertEqual(statement.databaseRegion.description, "FOO(*)") - } + let expectedRegion = DatabaseRegion(table: "foo") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "FOO(*)") } } } @@ -544,8 +524,8 @@ class DatabaseRegionTests : GRDBTestCase { do { 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 { + XCTAssertEqual(statement.authorizerEventKinds.count, 1) + guard case .update(let tableName, let columnNames) = statement.authorizerEventKinds[0] else { XCTFail() return } @@ -555,8 +535,8 @@ class DatabaseRegionTests : GRDBTestCase { do { 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 { + XCTAssertEqual(statement.authorizerEventKinds.count, 1) + guard case .update(let tableName, let columnNames) = statement.authorizerEventKinds[0] else { XCTFail() return } @@ -612,8 +592,8 @@ class DatabaseRegionTests : GRDBTestCase { try db.execute(sql: "CREATE TABLE foo (name TEXT)") do { 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 { + XCTAssertEqual(statement.authorizerEventKinds.count, 1) + guard case .update(let tableName, let columnNames) = statement.authorizerEventKinds[0] else { XCTFail() return } @@ -622,8 +602,8 @@ class DatabaseRegionTests : GRDBTestCase { } do { 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 { + XCTAssertEqual(statement.authorizerEventKinds.count, 1) + guard case .update(let tableName, let columnNames) = statement.authorizerEventKinds[0] else { XCTFail() return } @@ -632,8 +612,8 @@ class DatabaseRegionTests : GRDBTestCase { } do { 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 { + XCTAssertEqual(statement.authorizerEventKinds.count, 1) + guard case .update(let tableName, let columnNames) = statement.authorizerEventKinds[0] else { XCTFail() return } @@ -649,8 +629,8 @@ class DatabaseRegionTests : GRDBTestCase { try db.execute(sql: "CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)") 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 { + XCTAssertEqual(statement.authorizerEventKinds.count, 1) + guard case .insert(let tableName) = statement.authorizerEventKinds[0] else { XCTFail() return } @@ -664,8 +644,8 @@ class DatabaseRegionTests : GRDBTestCase { try db.execute(sql: "CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)") 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 { + XCTAssertEqual(statement.authorizerEventKinds.count, 1) + guard case .delete(let tableName) = statement.authorizerEventKinds[0] else { XCTFail() return } @@ -755,7 +735,7 @@ class DatabaseRegionTests : GRDBTestCase { do { // Complex selection - let region = DatabaseRegion.fullTable("foo") + let region = DatabaseRegion(table: "foo") .union(DatabaseRegion(table: "bar", columns: ["a"]) .intersection(DatabaseRegion(table: "bar", rowIds: [1]))) XCTAssertEqual(region.description, "bar(a)[1],foo(*)") diff --git a/Tests/GRDBTests/DatabaseSavepointTests.swift b/Tests/GRDBTests/DatabaseSavepointTests.swift index d1235cc04..b1858773f 100644 --- a/Tests/GRDBTests/DatabaseSavepointTests.swift +++ b/Tests/GRDBTests/DatabaseSavepointTests.swift @@ -43,7 +43,7 @@ private class Observer : TransactionObserver { class DatabaseSavepointTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE items (name TEXT)") } diff --git a/Tests/GRDBTests/DatabaseTests.swift b/Tests/GRDBTests/DatabaseTests.swift index 51335b2c0..635b852c0 100644 --- a/Tests/GRDBTests/DatabaseTests.swift +++ b/Tests/GRDBTests/DatabaseTests.swift @@ -522,11 +522,6 @@ class DatabaseTests : GRDBTestCase { // Test an internal API func testReadOnly() throws { - // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - guard sqlite3_libversion_number() >= 3008000 else { - return - } - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE t (id INTEGER PRIMARY KEY)") @@ -567,11 +562,6 @@ class DatabaseTests : GRDBTestCase { } func testReadOnlyTransaction() throws { - // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - guard sqlite3_libversion_number() >= 3008000 else { - return - } - dbConfiguration.defaultTransactionKind = .immediate let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/DatabaseTimestampTests.swift b/Tests/GRDBTests/DatabaseTimestampTests.swift index ee844f2c8..81a7ee926 100644 --- a/Tests/GRDBTests/DatabaseTimestampTests.swift +++ b/Tests/GRDBTests/DatabaseTimestampTests.swift @@ -15,7 +15,7 @@ struct DatabaseTimestamp: DatabaseValueConvertible { /// Creates a DatabaseTimestamp from an Date. /// The result is nil if and only if *date* is nil. init?(_ date: Date?) { - guard let date = date else { + guard let date else { return nil } self.date = date diff --git a/Tests/GRDBTests/DatabaseTraceTests.swift b/Tests/GRDBTests/DatabaseTraceTests.swift index 478a7b15e..df9d73119 100644 --- a/Tests/GRDBTests/DatabaseTraceTests.swift +++ b/Tests/GRDBTests/DatabaseTraceTests.swift @@ -23,10 +23,6 @@ class DatabaseTraceTests : GRDBTestCase { } func testTraceStatementSQL() throws { - guard #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) else { - throw XCTSkip("sqlite3_trace_v2 is not available") - } - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var lastSQL: String? @@ -55,10 +51,6 @@ class DatabaseTraceTests : GRDBTestCase { } func testTraceProfile() throws { - guard #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) else { - throw XCTSkip("sqlite3_trace_v2 is not available") - } - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var lastSQL: String? @@ -110,10 +102,6 @@ class DatabaseTraceTests : GRDBTestCase { } func testTraceMultiple() throws { - guard #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) else { - throw XCTSkip("sqlite3_trace_v2 is not available") - } - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var events: [String] = [] diff --git a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift index 268ec77e4..80686cfc5 100644 --- a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift @@ -23,23 +23,29 @@ private struct RecordWithUUID: EncodableRecord, Enco var uuid: UUID } +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension RecordWithUUID: Identifiable { + var id: UUID { uuid } +} + private struct RecordWithOptionalUUID: EncodableRecord, Encodable { static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { Strategy.strategy } var uuid: UUID? } @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) -extension RecordWithUUID: Identifiable { - var id: UUID { uuid } +extension RecordWithOptionalUUID: Identifiable { + var id: UUID? { uuid } } class DatabaseUUIDEncodingStrategyTests: GRDBTestCase { private func test( record: T, expectedStorage: DatabaseValue.Storage) + throws { var container = PersistenceContainer() - record.encode(to: &container) + try record.encode(to: &container) if let dbValue = container["uuid"]?.databaseValue { XCTAssertEqual(dbValue.storage, expectedStorage) } else { @@ -47,23 +53,23 @@ class DatabaseUUIDEncodingStrategyTests: GRDBTestCase { } } - private func test(strategy: Strategy.Type, encodesUUID uuid: UUID, as value: DatabaseValueConvertible) { - test(record: RecordWithUUID(uuid: uuid), expectedStorage: value.databaseValue.storage) - test(record: RecordWithOptionalUUID(uuid: uuid), expectedStorage: value.databaseValue.storage) + private func test(strategy: Strategy.Type, encodesUUID uuid: UUID, as value: DatabaseValueConvertible) throws { + try test(record: RecordWithUUID(uuid: uuid), expectedStorage: value.databaseValue.storage) + try test(record: RecordWithOptionalUUID(uuid: uuid), expectedStorage: value.databaseValue.storage) } - private func testNullEncoding(strategy: Strategy.Type) { - test(record: RecordWithOptionalUUID(uuid: nil), expectedStorage: .null) + private func testNullEncoding(strategy: Strategy.Type) throws { + try test(record: RecordWithOptionalUUID(uuid: nil), expectedStorage: .null) } } // MARK: - deferredToUUID extension DatabaseUUIDEncodingStrategyTests { - func testDeferredToUUID() { - testNullEncoding(strategy: StrategyDeferredToUUID.self) + func testDeferredToUUID() throws { + try testNullEncoding(strategy: StrategyDeferredToUUID.self) - test( + try test( strategy: StrategyDeferredToUUID.self, encodesUUID: UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!, as: "abcdefghijklmnop".data(using: .utf8)!) @@ -73,21 +79,21 @@ extension DatabaseUUIDEncodingStrategyTests { // MARK: - UppercaseString extension DatabaseUUIDEncodingStrategyTests { - func testUppercaseString() { - testNullEncoding(strategy: StrategyUppercaseString.self) + func testUppercaseString() throws { + try testNullEncoding(strategy: StrategyUppercaseString.self) - test( + try test( strategy: StrategyUppercaseString.self, encodesUUID: UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!, as: "61626364-6566-6768-696A-6B6C6D6E6F70") - test( + try test( strategy: StrategyUppercaseString.self, encodesUUID: UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!, as: "56E7D8D3-E9E4-48B6-968E-8D102833AF00") let uuid = UUID() - test( + try test( strategy: StrategyUppercaseString.self, encodesUUID: uuid, as: uuid.uuidString.uppercased()) // Assert stable casing @@ -97,21 +103,21 @@ extension DatabaseUUIDEncodingStrategyTests { // MARK: - LowercaseString extension DatabaseUUIDEncodingStrategyTests { - func testLowercaseString() { - testNullEncoding(strategy: StrategyLowercaseString.self) + func testLowercaseString() throws { + try testNullEncoding(strategy: StrategyLowercaseString.self) - test( + try test( strategy: StrategyLowercaseString.self, encodesUUID: UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!, as: "61626364-6566-6768-696a-6b6c6d6e6f70") - test( + try test( strategy: StrategyLowercaseString.self, encodesUUID: UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!, as: "56e7d8d3-e9e4-48b6-968e-8d102833af00") let uuid = UUID() - test( + try test( strategy: StrategyLowercaseString.self, encodesUUID: uuid, as: uuid.uuidString.lowercased()) // Assert stable casing @@ -226,6 +232,69 @@ extension DatabaseUUIDEncodingStrategyTests { SELECT * FROM "t" WHERE "id" IN ('61626364-6566-6768-696a-6b6c6d6e6f70', '56e7d8d3-e9e4-48b6-968e-8d102833af00') """) } + + do { + let request = Table>("t").filter(id: nil) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE 0 + """) + } + + do { + let request = Table>("t").filter(id: uuids[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = x'6162636465666768696a6b6c6d6e6f70' + """) + } + + do { + let request = Table>("t").filter(ids: uuids) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN (x'6162636465666768696a6b6c6d6e6f70', x'56e7d8d3e9e448b6968e8d102833af00') + """) + } + + do { + let request = Table>("t").filter(id: nil) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE 0 + """) + } + + do { + let request = Table>("t").filter(id: uuids[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = '61626364-6566-6768-696A-6B6C6D6E6F70' + """) + } + + do { + let request = Table>("t").filter(ids: uuids) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN ('61626364-6566-6768-696A-6B6C6D6E6F70', '56E7D8D3-E9E4-48B6-968E-8D102833AF00') + """) + } + + do { + let request = Table>("t").filter(id: nil) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE 0 + """) + } + + do { + let request = Table>("t").filter(id: uuids[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = '61626364-6566-6768-696a-6b6c6d6e6f70' + """) + } + + do { + let request = Table>("t").filter(ids: uuids) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN ('61626364-6566-6768-696a-6b6c6d6e6f70', '56e7d8d3-e9e4-48b6-968e-8d102833af00') + """) + } } } @@ -282,6 +351,66 @@ extension DatabaseUUIDEncodingStrategyTests { DELETE FROM "t" WHERE "id" IN ('61626364-6566-6768-696a-6b6c6d6e6f70', '56e7d8d3-e9e4-48b6-968e-8d102833af00') """) } + + do { + sqlQueries.removeAll() + try Table>("t").deleteOne(db, id: nil) + XCTAssertNil(lastSQLQuery) // Database not hit + } + + do { + try Table>("t").deleteOne(db, id: uuids[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = x'6162636465666768696a6b6c6d6e6f70' + """) + } + + do { + try Table>("t").deleteAll(db, ids: uuids) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN (x'6162636465666768696a6b6c6d6e6f70', x'56e7d8d3e9e448b6968e8d102833af00') + """) + } + + do { + sqlQueries.removeAll() + try Table>("t").deleteOne(db, id: nil) + XCTAssertNil(lastSQLQuery) // Database not hit + } + + do { + try Table>("t").deleteOne(db, id: uuids[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = '61626364-6566-6768-696A-6B6C6D6E6F70' + """) + } + + do { + try Table>("t").deleteAll(db, ids: uuids) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN ('61626364-6566-6768-696A-6B6C6D6E6F70', '56E7D8D3-E9E4-48B6-968E-8D102833AF00') + """) + } + + do { + sqlQueries.removeAll() + try Table>("t").deleteOne(db, id: nil) + XCTAssertNil(lastSQLQuery) // Database not hit + } + + do { + try Table>("t").deleteOne(db, id: uuids[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = '61626364-6566-6768-696a-6b6c6d6e6f70' + """) + } + + do { + try Table>("t").deleteAll(db, ids: uuids) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN ('61626364-6566-6768-696a-6b6c6d6e6f70', '56e7d8d3-e9e4-48b6-968e-8d102833af00') + """) + } } } } diff --git a/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift b/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift index 34cb521f5..a639d83dc 100644 --- a/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift +++ b/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift @@ -3,7 +3,7 @@ import XCTest class DatabaseValueConversionErrorTests: GRDBTestCase { func testFetchableRecord1() throws { - struct Record /* TODO GRDB6: FetchableRecord */ { + struct Record: FetchableRecord { var name: String init(row: Row) throws { @@ -41,10 +41,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { } do { - // TODO GRDB6: _ = try Record.fetchOne(statement) - _ = try Row.fetchCursor(statement) - .map { try Record(row: $0) } - .next() + _ = try Record.fetchOne(statement) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -94,10 +91,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { } do { - // TODO GRDB6: _ = try Record.fetchOne(statement) - _ = try Row.fetchCursor(statement) - .map { try Record(row: $0) } - .next() + _ = try Record.fetchOne(statement) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -125,7 +119,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { case valid } - struct Record /* TODO GRDB6: FetchableRecord */ { + struct Record: FetchableRecord { var value: Value init(row: Row) throws { @@ -163,10 +157,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { } do { - // TODO GRDB6: _ = try Record.fetchOne(statement) - _ = try Row.fetchCursor(statement) - .map { try Record(row: $0) } - .next() + _ = try Record.fetchOne(statement) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -216,10 +207,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { } do { - // TODO GRDB6: _ = try Record.fetchOne(statement) - _ = try Row.fetchCursor(statement) - .map { try Record(row: $0) } - .next() + _ = try Record.fetchOne(statement) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -257,8 +245,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { do { let row = try Row.fetchOne(statement)! - // TODO GRDB6: _ = try Record(row: row) - _ = try RowDecoder().decode(Record.self, from: row) + _ = try Record(row: row) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -279,11 +266,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { } do { - // TODO GRDB6: _ = try Record.fetchOne(statement) - let rows = try Row.fetchCursor(statement) - while let row = try rows.next() { - _ = try RowDecoder().decode(Record.self, from: row) - } + _ = try Record.fetchOne(statement) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -313,8 +296,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { do { let row = try Row.fetchOne(statement)! - // TODO GRDB6: _ = try Record(row: row) - _ = try RowDecoder().decode(Record.self, from: row) + _ = try Record(row: row) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -334,11 +316,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { } do { - // TODO GRDB6: _ = try Record.fetchOne(statement) - let rows = try Row.fetchCursor(statement) - while let row = try rows.next() { - _ = try RowDecoder().decode(Record.self, from: row) - } + _ = try Record.fetchOne(statement) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -379,8 +357,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { do { let row = try Row.fetchOne(statement)! - // TODO GRDB6: _ = try Record(row: row) - _ = try RowDecoder().decode(Record.self, from: row) + _ = try Record(row: row) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -401,11 +378,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { } do { - // TODO GRDB6: _ = try Record.fetchOne(statement) - let rows = try Row.fetchCursor(statement) - while let row = try rows.next() { - _ = try RowDecoder().decode(Record.self, from: row) - } + _ = try Record.fetchOne(statement) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -435,8 +408,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { do { let row = try Row.fetchOne(statement)! - // TODO GRDB6: _ = try Record(row: row) - _ = try RowDecoder().decode(Record.self, from: row) + _ = try Record(row: row) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -456,11 +428,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { } do { - // TODO GRDB6: _ = try Record.fetchOne(statement) - let rows = try Row.fetchCursor(statement) - while let row = try rows.next() { - _ = try RowDecoder().decode(Record.self, from: row) - } + _ = try Record.fetchOne(statement) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -501,8 +469,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { do { let row = try Row.fetchOne(statement)! - // TODO GRDB6: _ = try Record(row: row) - _ = try RowDecoder().decode(Record.self, from: row) + _ = try Record(row: row) XCTFail("Expected error") } catch let error as DecodingError { switch error { @@ -514,11 +481,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { } do { - // TODO GRDB6: _ = try Record.fetchOne(statement) - let rows = try Row.fetchCursor(statement) - while let row = try rows.next() { - _ = try RowDecoder().decode(Record.self, from: row) - } + _ = try Record.fetchOne(statement) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -555,8 +518,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { do { let row = try Row.fetchOne(statement)! - // TODO GRDB6: _ = try Record(row: row) - _ = try RowDecoder().decode(Record.self, from: row) + _ = try Record(row: row) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -576,11 +538,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { } do { - // TODO GRDB6: _ = try Record.fetchOne(statement) - let rows = try Row.fetchCursor(statement) - while let row = try rows.next() { - _ = try RowDecoder().decode(Record.self, from: row) - } + _ = try Record.fetchOne(statement) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -610,10 +568,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { statement.arguments = ["invalid"] do { - // TODO GRDB6: _ = try String.fetchAll(statement) - _ = try Row.fetchCursor(statement) - .map { try String.fastDecode(fromRow: $0, atUncheckedIndex: 0) } - .next() + _ = try String.fetchAll(statement) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -712,10 +667,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { } do { - // TODO GRDB6: _ = try Int8.fetchAll(statement) - _ = try Row.fetchCursor(statement) - .map { try Int8.fastDecode(fromRow: $0, atUncheckedIndex: 0) } - .next() + _ = try Int8.fetchAll(statement) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -794,10 +746,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { statement.arguments = ["invalid"] do { - // TODO GRDB6: _ = try Value.fetchAll(statement) - _ = try Row.fetchCursor(statement) - .map { try Value.decode(fromRow: $0, atUncheckedIndex: 0) } - .next() + _ = try Value.fetchAll(statement) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -820,10 +769,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { } do { - // TODO GRDB6: _ = try Value.fetchOne(statement, adapter: SuffixRowAdapter(fromIndex: 1)) - _ = try Row.fetchCursor(statement) - .map { try Value.decode(fromRow: $0, atUncheckedIndex: 1) } - .next() + _ = try Value.fetchOne(statement, adapter: SuffixRowAdapter(fromIndex: 1)) XCTFail("Expected error") } catch let error as RowDecodingError { switch error { @@ -833,7 +779,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team") XCTAssertEqual(context.statementArguments, ["invalid"]) XCTAssertEqual(error.description, """ - could not decode \(Value.self) from database value "invalid" - \ + could not decode \(Optional.self) from database value "invalid" - \ column: "team", \ column index: 1, \ row: [name:NULL team:"invalid"], \ diff --git a/Tests/GRDBTests/DatabaseValueConversionTests.swift b/Tests/GRDBTests/DatabaseValueConversionTests.swift index 82c246cd0..7ea09e374 100644 --- a/Tests/GRDBTests/DatabaseValueConversionTests.swift +++ b/Tests/GRDBTests/DatabaseValueConversionTests.swift @@ -27,24 +27,21 @@ private let emojiString = "'fooéı👨👨🏿🇫🇷🇨🇮'" private let emojiData = emojiString.data(using: .utf8) private let nonUTF8Data = Data([0x80]) private let invalidString = "\u{FFFD}" // decoded from nonUTF8Data -// Until SPM tests can load resources, disable this test for SPM. -#if !SWIFT_PACKAGE -private let jpegData = try! Data(contentsOf: Bundle(for: DatabaseValueConversionTests.self).url(forResource: "Betty", withExtension: "jpeg")!) -#endif +private let jpegData = try! Data(contentsOf: testBundle.url(forResource: "Betty", withExtension: "jpeg")!) class DatabaseValueConversionTests : GRDBTestCase { - private func _assertDecoding( + private func assertDecoding( _ db: Database, _ sql: String, _ type: T.Type, expectedSQLiteConversion: T?, expectedDatabaseValueConversion: T?, - file: StaticString, - line: UInt) throws + file: StaticString = #file, + line: UInt = #line) throws { func stringRepresentation(_ value: T?) -> String { - guard let value = value else { return "nil" } + guard let value else { return "nil" } return String(reflecting: value) } @@ -86,12 +83,12 @@ class DatabaseValueConversionTests : GRDBTestCase { } } - private func _assertFailedDecoding( + private func assertFailedDecoding( _ db: Database, _ sql: String, _ type: T.Type, - file: StaticString, - line: UInt) throws + file: StaticString = #file, + line: UInt = #line) throws { // We can only test failed decoding from database value, since // StatementColumnConvertible only supports optimistic decoding which @@ -100,64 +97,9 @@ class DatabaseValueConversionTests : GRDBTestCase { XCTAssertNil(T.fromDatabaseValue(dbValue), file: file, line: line) } - // #file vs. #filePath dance - #if compiler(>=5.3) - private func assertDecoding( - _ db: Database, - _ sql: String, - _ type: T.Type, - expectedSQLiteConversion: T?, - expectedDatabaseValueConversion: T?, - file: StaticString = #filePath, - line: UInt = #line) throws - { - try _assertDecoding( - db, sql, type, - expectedSQLiteConversion: expectedSQLiteConversion, - expectedDatabaseValueConversion: expectedDatabaseValueConversion, - file: file, line: line) - } - - private func assertFailedDecoding( - _ db: Database, - _ sql: String, - _ type: T.Type, - file: StaticString = #filePath, - line: UInt = #line) throws - { - try _assertFailedDecoding(db, sql, type, file: file, line: line) - } - #else - private func assertDecoding( - _ db: Database, - _ sql: String, - _ type: T.Type, - expectedSQLiteConversion: T?, - expectedDatabaseValueConversion: T?, - file: StaticString = #file, - line: UInt = #line) throws - { - try _assertDecoding( - db, sql, type, - expectedSQLiteConversion: expectedSQLiteConversion, - expectedDatabaseValueConversion: expectedDatabaseValueConversion, - file: file, line: line) - } - - private func assertFailedDecoding( - _ db: Database, - _ sql: String, - _ type: T.Type, - file: StaticString = #file, - line: UInt = #line) throws - { - try _assertFailedDecoding(db, sql, type, file: file, line: line) - } - #endif - // Datatypes In SQLite Version 3: https://www.sqlite.org/datatype3.html - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ @@ -343,7 +285,6 @@ class DatabaseValueConversionTests : GRDBTestCase { return .rollback } - #if !SWIFT_PACKAGE // jpegData is turned to Blob try dbQueue.inTransaction { db in @@ -360,7 +301,6 @@ class DatabaseValueConversionTests : GRDBTestCase { try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: jpegData, expectedDatabaseValueConversion: jpegData) return .rollback } - #endif } func testNumericAffinity() throws { @@ -604,7 +544,6 @@ class DatabaseValueConversionTests : GRDBTestCase { return .rollback } - #if !SWIFT_PACKAGE // jpegData is turned to Blob try dbQueue.inTransaction { db in @@ -621,7 +560,6 @@ class DatabaseValueConversionTests : GRDBTestCase { try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: jpegData, expectedDatabaseValueConversion: jpegData) return .rollback } - #endif } func testNoneAffinity() throws { @@ -793,7 +731,6 @@ class DatabaseValueConversionTests : GRDBTestCase { return .rollback } - #if !SWIFT_PACKAGE // jpegData is turned to Blob try dbQueue.inTransaction { db in @@ -810,7 +747,6 @@ class DatabaseValueConversionTests : GRDBTestCase { try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: jpegData, expectedDatabaseValueConversion: jpegData) return .rollback } - #endif } func testNumericAffinity(_ columnName: String) throws { @@ -1028,7 +964,6 @@ class DatabaseValueConversionTests : GRDBTestCase { return .rollback } - #if !SWIFT_PACKAGE // jpegData is turned to Blob try dbQueue.inTransaction { db in @@ -1045,6 +980,5 @@ class DatabaseValueConversionTests : GRDBTestCase { try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: jpegData, expectedDatabaseValueConversion: jpegData) return .rollback } - #endif } } diff --git a/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift index 3a80e683a..c1dd3fe36 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift @@ -99,7 +99,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } } } - + func testFetchCursorCompilationFailure() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -131,7 +131,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } } } - + func testFetchAll() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -200,7 +200,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } } } - + func testFetchAllCompilationFailure() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -232,7 +232,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } } } - + func testFetchSet() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -301,7 +301,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } } } - + func testFetchSetCompilationFailure() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -333,7 +333,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } } } - + func testFetchOne() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -448,7 +448,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } } } - + func testFetchOneCompilationFailure() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -480,13 +480,13 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } } } - + // MARK: - Optional.fetch - + func testOptionalFetchCursor() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - func test(_ cursor: NullableDatabaseValueCursor) throws { + func test(_ cursor: DatabaseValueCursor) throws { XCTAssertEqual(try cursor.next()!!.int, 1) XCTAssertTrue(try cursor.next()! == nil) XCTAssertTrue(try cursor.next() == nil) // end @@ -527,7 +527,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { try dbQueue.inDatabase { db in let customError = NSError(domain: "Custom", code: 0xDEAD) db.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError }) - func test(_ cursor: NullableDatabaseValueCursor, sql: String) throws { + func test(_ cursor: DatabaseValueCursor, sql: String) throws { do { _ = try cursor.next() XCTFail() @@ -562,11 +562,11 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } } } - + func testOptionalFetchCursorCompilationFailure() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - func test(_ cursor: @autoclosure () throws -> NullableDatabaseValueCursor, sql: String) throws { + func test(_ cursor: @autoclosure () throws -> DatabaseValueCursor, sql: String) throws { do { _ = try cursor() XCTFail() @@ -665,7 +665,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } } } - + func testOptionalFetchAllCompilationFailure() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -766,7 +766,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } } } - + func testOptionalFetchSetCompilationFailure() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -798,4 +798,157 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { } } } + + func testOptionalFetchOne() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + func test(_ nilBecauseMissingRow: Fetched??) { + switch nilBecauseMissingRow { + case .none: break + default: XCTFail("Expected nil because missing row") + } + } + do { + let sql = "SELECT 1 WHERE 0" + let statement = try db.makeStatement(sql: sql) + try test(Optional.fetchOne(db, sql: sql)) + try test(Optional.fetchOne(statement)) + try test(Optional.fetchOne(db, SQLRequest(sql: sql))) + try test(SQLRequest(sql: sql).fetchOne(db)) + } + do { + let sql = "SELECT 0, 1 WHERE 0" + let statement = try db.makeStatement(sql: sql) + let adapter = SuffixRowAdapter(fromIndex: 1) + try test(Optional.fetchOne(db, sql: sql, adapter: adapter)) + try test(Optional.fetchOne(statement, adapter: adapter)) + try test(Optional.fetchOne(db, SQLRequest(sql: sql, adapter: adapter))) + try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db)) + } + } + do { + func test(_ nilBecauseNull: Fetched??) { + switch nilBecauseNull { + case .some(.none): break + default: XCTFail("Expected .some(nil) because NULL") + } + } + do { + let sql = "SELECT NULL" + let statement = try db.makeStatement(sql: sql) + try test(Optional.fetchOne(db, sql: sql)) + try test(Optional.fetchOne(statement)) + try test(Optional.fetchOne(db, SQLRequest(sql: sql))) + try test(SQLRequest(sql: sql).fetchOne(db)) + } + do { + let sql = "SELECT 0, NULL" + let statement = try db.makeStatement(sql: sql) + let adapter = SuffixRowAdapter(fromIndex: 1) + try test(Optional.fetchOne(db, sql: sql, adapter: adapter)) + try test(Optional.fetchOne(statement, adapter: adapter)) + try test(Optional.fetchOne(db, SQLRequest(sql: sql, adapter: adapter))) + try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db)) + } + } + do { + func test(_ value: Fetched??) { + XCTAssertEqual(value!!.int, 1) + } + do { + let sql = "SELECT 1" + let statement = try db.makeStatement(sql: sql) + try test(Optional.fetchOne(db, sql: sql)) + try test(Optional.fetchOne(statement)) + try test(Optional.fetchOne(db, SQLRequest(sql: sql))) + try test(SQLRequest(sql: sql).fetchOne(db)) + } + do { + let sql = "SELECT 0, 1" + let statement = try db.makeStatement(sql: sql) + let adapter = SuffixRowAdapter(fromIndex: 1) + try test(Optional.fetchOne(db, sql: sql, adapter: adapter)) + try test(Optional.fetchOne(statement, adapter: adapter)) + try test(Optional.fetchOne(db, SQLRequest(sql: sql, adapter: adapter))) + try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db)) + } + } + } + } + + func testOptionalFetchOneWithInterpolation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request: SQLRequest = "SELECT \(42)" + let fetched = try request.fetchOne(db) + XCTAssertEqual(fetched!!.int, 42) + } + } + + func testOptionalFetchOneStepFailure() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let customError = NSError(domain: "Custom", code: 0xDEAD) + db.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError }) + func test(_ value: @autoclosure () throws -> Fetched??, sql: String) throws { + do { + _ = try value() + XCTFail() + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "\(customError)") + XCTAssertEqual(error.sql!, sql) + XCTAssertEqual(error.description, "SQLite error 1: \(customError) - while executing `\(sql)`") + } + } + do { + let sql = "SELECT throw()" + try test(Optional.fetchOne(db, sql: sql), sql: sql) + try test(Optional.fetchOne(db.makeStatement(sql: sql)), sql: sql) + try test(Optional.fetchOne(db, SQLRequest(sql: sql)), sql: sql) + try test(SQLRequest(sql: sql).fetchOne(db), sql: sql) + } + do { + let sql = "SELECT 0, throw()" + let adapter = SuffixRowAdapter(fromIndex: 1) + try test(Optional.fetchOne(db, sql: sql, adapter: adapter), sql: sql) + try test(Optional.fetchOne(db.makeStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.fetchOne(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db), sql: sql) + } + } + } + + func testOptionalFetchOneCompilationFailure() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + func test(_ value: @autoclosure () throws -> Fetched??, sql: String) throws { + do { + _ = try value() + XCTFail() + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "no such table: nonExistingTable") + XCTAssertEqual(error.sql!, sql) + XCTAssertEqual(error.description, "SQLite error 1: no such table: nonExistingTable - while executing `\(sql)`") + } + } + do { + let sql = "SELECT * FROM nonExistingTable" + try test(Optional.fetchOne(db, sql: sql), sql: sql) + try test(Optional.fetchOne(db.makeStatement(sql: sql)), sql: sql) + try test(Optional.fetchOne(db, SQLRequest(sql: sql)), sql: sql) + try test(SQLRequest(sql: sql).fetchOne(db), sql: sql) + } + do { + let sql = "SELECT * FROM nonExistingTable" + let adapter = SuffixRowAdapter(fromIndex: 1) + try test(Optional.fetchOne(db, sql: sql, adapter: adapter), sql: sql) + try test(Optional.fetchOne(db.makeStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.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/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 5a7b4c433..8f2e4b1e3 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -40,7 +40,7 @@ class DatabaseWriterTests : GRDBTestCase { } func testAsyncWriteWithoutTransactionSuccess() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) dbWriter.asyncWriteWithoutTransaction { db in @@ -65,7 +65,7 @@ class DatabaseWriterTests : GRDBTestCase { } func testAsyncWriteWithoutTransactionError() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) dbWriter.asyncWriteWithoutTransaction { db in @@ -90,7 +90,7 @@ class DatabaseWriterTests : GRDBTestCase { } func testAsyncWriteSuccess() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) dbWriter.asyncWrite({ db in @@ -119,7 +119,7 @@ class DatabaseWriterTests : GRDBTestCase { } func testAsyncWriteError() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) dbWriter.asyncWrite({ db in @@ -148,10 +148,10 @@ class DatabaseWriterTests : GRDBTestCase { try test(makeDatabasePool()) } - func testAnyDatabaseWriter() { + func testAnyDatabaseWriter() throws { // This test passes if this code compiles. - let writer: DatabaseWriter = DatabaseQueue() - let _: DatabaseWriter = AnyDatabaseWriter(writer) + let dbQueue = try DatabaseQueue() + let _: any DatabaseWriter = AnyDatabaseWriter(dbQueue) } func testEraseAndVacuum() throws { @@ -159,7 +159,7 @@ class DatabaseWriterTests : GRDBTestCase { try testEraseAndVacuum(writer: makeDatabasePool()) } - private func testEraseAndVacuum(writer: DatabaseWriter) throws { + private func testEraseAndVacuum(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("init") { db in // Create a database with recursive constraints, so that we test @@ -203,7 +203,7 @@ class DatabaseWriterTests : GRDBTestCase { throw XCTSkip("VACUUM INTO is not available") } - func testVacuumInto(writer: DatabaseWriter) throws { + func testVacuumInto(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("init") { db in try db.execute(sql: """ @@ -266,7 +266,6 @@ class DatabaseWriterTests : GRDBTestCase { try DatabaseQueue().backup(to: dbQueue) } -#if compiler(>=5.6) && canImport(_Concurrency) @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_write() async throws { func setup(_ dbWriter: T) throws -> T { @@ -286,9 +285,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) } -#endif -#if compiler(>=5.6) && canImport(_Concurrency) @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_writeWithoutTransaction() async throws { func setup(_ dbWriter: T) throws -> T { @@ -311,9 +308,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) } -#endif -#if compiler(>=5.6) && canImport(_Concurrency) @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_barrierWriteWithoutTransaction() async throws { func setup(_ dbWriter: T) throws -> T { @@ -336,9 +331,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) } -#endif -#if compiler(>=5.6) && canImport(_Concurrency) @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_erase() async throws { func setup(_ dbWriter: T) throws -> T { @@ -356,9 +349,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) } -#endif -#if compiler(>=5.6) && canImport(_Concurrency) @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_vacuum() async throws { func setup(_ dbWriter: T) throws -> T { @@ -374,9 +365,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) } -#endif -#if compiler(>=5.6) && canImport(_Concurrency) @available(macOS 10.16, iOS 14, tvOS 14, watchOS 7, *) // async + vacuum into func testAsyncAwait_vacuumInto() async throws { // Prevent SQLCipher failures @@ -406,5 +395,4 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) } -#endif } diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift index 7d9c96cc2..fb360a85d 100644 --- a/Tests/GRDBTests/DerivableRequestTests.swift +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -25,17 +25,9 @@ private struct Book: FetchableRecord, PersistableRecord, Codable { static let databaseTableName = "book" static let author = belongsTo(Author.self) - #if compiler(>=5.5) static let bookFts4 = hasOne(BookFts4.self, using: ForeignKey([.rowID])) - #else - static let bookFts4 = hasOne(BookFts4.self, using: ForeignKey([Column.rowID])) - #endif #if SQLITE_ENABLE_FTS5 - #if compiler(>=5.5) static let bookFts5 = hasOne(BookFts5.self, using: ForeignKey([.rowID])) - #else - static let bookFts5 = hasOne(BookFts5.self, using: ForeignKey([Column.rowID])) - #endif #endif var author: QueryInterfaceRequest { request(for: Book.author) } @@ -82,7 +74,7 @@ private var libraryMigrator: DatabaseMigrator = { }() // Define DerivableRequest extensions -extension DerivableRequest where RowDecoder == Author { +extension DerivableRequest { // SelectionRequest func selectCountry() -> Self { select(Column("country")) @@ -101,7 +93,7 @@ extension DerivableRequest where RowDecoder == Author { } } -extension DerivableRequest where RowDecoder == Book { +extension DerivableRequest { // OrderedRequest func orderByTitle() -> Self { order(Column("title").collating(.localizedCaseInsensitiveCompare)) diff --git a/Tests/GRDBTests/FTS3PatternTests.swift b/Tests/GRDBTests/FTS3PatternTests.swift index 2e79a0f5c..0bcbb5638 100644 --- a/Tests/GRDBTests/FTS3PatternTests.swift +++ b/Tests/GRDBTests/FTS3PatternTests.swift @@ -3,7 +3,7 @@ import GRDB class FTS3PatternTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(virtualTable: "books", using: FTS3()) { t in t.column("title") diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index d7f3ff400..036fb5da4 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -10,11 +10,7 @@ private struct Book { extension Book : FetchableRecord { init(row: Row) { - #if compiler(>=5.5) id = row[.rowID] - #else - id = row[Column.rowID] - #endif title = row["title"] author = row["author"] body = row["body"] @@ -26,23 +22,19 @@ extension Book : MutablePersistableRecord { static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] func encode(to container: inout PersistenceContainer) { - #if compiler(>=5.5) container[.rowID] = id - #else - container[Column.rowID] = id - #endif container["title"] = title container["author"] = author container["body"] = body } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } class FTS3RecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(virtualTable: "books", using: FTS3()) { t in t.column("title") diff --git a/Tests/GRDBTests/FTS3TokenizerTests.swift b/Tests/GRDBTests/FTS3TokenizerTests.swift index 4e140db87..3d61a6c8d 100644 --- a/Tests/GRDBTests/FTS3TokenizerTests.swift +++ b/Tests/GRDBTests/FTS3TokenizerTests.swift @@ -145,89 +145,89 @@ class FTS3TokenizerTests: GRDBTestCase { } } - func testTokenize() { + func testTokenize() throws { // Empty query - XCTAssertEqual(FTS3.tokenize(""), []) - XCTAssertEqual(FTS3.tokenize("", withTokenizer: .simple), []) - XCTAssertEqual(FTS3.tokenize("", withTokenizer: .porter), []) - XCTAssertEqual(FTS3.tokenize("", withTokenizer: .unicode61()), []) - XCTAssertEqual(FTS3.tokenize("", withTokenizer: .unicode61(diacritics: .keep)), []) + try XCTAssertEqual(FTS3.tokenize(""), []) + try XCTAssertEqual(FTS3.tokenize("", withTokenizer: .simple), []) + try XCTAssertEqual(FTS3.tokenize("", withTokenizer: .porter), []) + try XCTAssertEqual(FTS3.tokenize("", withTokenizer: .unicode61()), []) + try XCTAssertEqual(FTS3.tokenize("", withTokenizer: .unicode61(diacritics: .keep)), []) - XCTAssertEqual(FTS3.tokenize("?!"), []) - XCTAssertEqual(FTS3.tokenize("?!", withTokenizer: .simple), []) - XCTAssertEqual(FTS3.tokenize("?!", withTokenizer: .porter), []) - XCTAssertEqual(FTS3.tokenize("?!", withTokenizer: .unicode61()), []) - XCTAssertEqual(FTS3.tokenize("?!", withTokenizer: .unicode61(diacritics: .keep)), []) + try XCTAssertEqual(FTS3.tokenize("?!"), []) + try XCTAssertEqual(FTS3.tokenize("?!", withTokenizer: .simple), []) + try XCTAssertEqual(FTS3.tokenize("?!", withTokenizer: .porter), []) + try XCTAssertEqual(FTS3.tokenize("?!", withTokenizer: .unicode61()), []) + try XCTAssertEqual(FTS3.tokenize("?!", withTokenizer: .unicode61(diacritics: .keep)), []) // Token queries - XCTAssertEqual(FTS3.tokenize("Moby"), ["moby"]) - XCTAssertEqual(FTS3.tokenize("Moby", withTokenizer: .simple), ["moby"]) - XCTAssertEqual(FTS3.tokenize("Moby", withTokenizer: .porter), ["mobi"]) - XCTAssertEqual(FTS3.tokenize("Moby", withTokenizer: .unicode61()), ["moby"]) - XCTAssertEqual(FTS3.tokenize("Moby", withTokenizer: .unicode61(diacritics: .keep)), ["moby"]) + try XCTAssertEqual(FTS3.tokenize("Moby"), ["moby"]) + try XCTAssertEqual(FTS3.tokenize("Moby", withTokenizer: .simple), ["moby"]) + try XCTAssertEqual(FTS3.tokenize("Moby", withTokenizer: .porter), ["mobi"]) + try XCTAssertEqual(FTS3.tokenize("Moby", withTokenizer: .unicode61()), ["moby"]) + try XCTAssertEqual(FTS3.tokenize("Moby", withTokenizer: .unicode61(diacritics: .keep)), ["moby"]) - XCTAssertEqual(FTS3.tokenize("écarlates"), ["écarlates"]) - XCTAssertEqual(FTS3.tokenize("écarlates", withTokenizer: .simple), ["écarlates"]) - XCTAssertEqual(FTS3.tokenize("écarlates", withTokenizer: .porter), ["écarlates"]) - XCTAssertEqual(FTS3.tokenize("écarlates", withTokenizer: .unicode61()), ["ecarlates"]) - XCTAssertEqual(FTS3.tokenize("écarlates", withTokenizer: .unicode61(diacritics: .keep)), ["écarlates"]) + try XCTAssertEqual(FTS3.tokenize("écarlates"), ["écarlates"]) + try XCTAssertEqual(FTS3.tokenize("écarlates", withTokenizer: .simple), ["écarlates"]) + try XCTAssertEqual(FTS3.tokenize("écarlates", withTokenizer: .porter), ["écarlates"]) + try XCTAssertEqual(FTS3.tokenize("écarlates", withTokenizer: .unicode61()), ["ecarlates"]) + try XCTAssertEqual(FTS3.tokenize("écarlates", withTokenizer: .unicode61(diacritics: .keep)), ["écarlates"]) - XCTAssertEqual(FTS3.tokenize("fooéı👨👨🏿🇫🇷🇨🇮"), ["fooéı👨👨🏿🇫🇷🇨🇮"]) - XCTAssertEqual(FTS3.tokenize("fooéı👨👨🏿🇫🇷🇨🇮", withTokenizer: .simple), ["fooéı👨👨🏿🇫🇷🇨🇮"]) - XCTAssertEqual(FTS3.tokenize("fooéı👨👨🏿🇫🇷🇨🇮", withTokenizer: .porter), ["fooéı👇�🇨🇮"]) // ¯\_(ツ)_/¯ - XCTAssertEqual(FTS3.tokenize("fooéı👨👨🏿🇫🇷🇨🇮", withTokenizer: .unicode61()), ["fooeı", "🏿"]) // ¯\_(ツ)_/¯ - XCTAssertEqual(FTS3.tokenize("fooéı👨👨🏿🇫🇷🇨🇮", withTokenizer: .unicode61(diacritics: .keep)), ["fooéı", "🏿"]) // ¯\_(ツ)_/¯ + try XCTAssertEqual(FTS3.tokenize("fooéı👨👨🏿🇫🇷🇨🇮"), ["fooéı👨👨🏿🇫🇷🇨🇮"]) + try XCTAssertEqual(FTS3.tokenize("fooéı👨👨🏿🇫🇷🇨🇮", withTokenizer: .simple), ["fooéı👨👨🏿🇫🇷🇨🇮"]) + try XCTAssertEqual(FTS3.tokenize("fooéı👨👨🏿🇫🇷🇨🇮", withTokenizer: .porter), ["fooéı👇�🇨🇮"]) // ¯\_(ツ)_/¯ + try XCTAssertEqual(FTS3.tokenize("fooéı👨👨🏿🇫🇷🇨🇮", withTokenizer: .unicode61()), ["fooeı", "🏿"]) // ¯\_(ツ)_/¯ + try XCTAssertEqual(FTS3.tokenize("fooéı👨👨🏿🇫🇷🇨🇮", withTokenizer: .unicode61(diacritics: .keep)), ["fooéı", "🏿"]) // ¯\_(ツ)_/¯ - XCTAssertEqual(FTS3.tokenize("SQLite database"), ["sqlite", "database"]) - XCTAssertEqual(FTS3.tokenize("SQLite database", withTokenizer: .simple), ["sqlite", "database"]) - XCTAssertEqual(FTS3.tokenize("SQLite database", withTokenizer: .porter), ["sqlite", "databas"]) - XCTAssertEqual(FTS3.tokenize("SQLite database", withTokenizer: .unicode61()), ["sqlite", "database"]) - XCTAssertEqual(FTS3.tokenize("SQLite database", withTokenizer: .unicode61(diacritics: .keep)), ["sqlite", "database"]) + try XCTAssertEqual(FTS3.tokenize("SQLite database"), ["sqlite", "database"]) + try XCTAssertEqual(FTS3.tokenize("SQLite database", withTokenizer: .simple), ["sqlite", "database"]) + try XCTAssertEqual(FTS3.tokenize("SQLite database", withTokenizer: .porter), ["sqlite", "databas"]) + try XCTAssertEqual(FTS3.tokenize("SQLite database", withTokenizer: .unicode61()), ["sqlite", "database"]) + try XCTAssertEqual(FTS3.tokenize("SQLite database", withTokenizer: .unicode61(diacritics: .keep)), ["sqlite", "database"]) - XCTAssertEqual(FTS3.tokenize("Édouard Manet"), ["Édouard", "manet"]) - XCTAssertEqual(FTS3.tokenize("Édouard Manet", withTokenizer: .simple), ["Édouard", "manet"]) - XCTAssertEqual(FTS3.tokenize("Édouard Manet", withTokenizer: .porter), ["Édouard", "manet"]) - XCTAssertEqual(FTS3.tokenize("Édouard Manet", withTokenizer: .unicode61()), ["edouard", "manet"]) - XCTAssertEqual(FTS3.tokenize("Édouard Manet", withTokenizer: .unicode61(diacritics: .keep)), ["édouard", "manet"]) + try XCTAssertEqual(FTS3.tokenize("Édouard Manet"), ["Édouard", "manet"]) + try XCTAssertEqual(FTS3.tokenize("Édouard Manet", withTokenizer: .simple), ["Édouard", "manet"]) + try XCTAssertEqual(FTS3.tokenize("Édouard Manet", withTokenizer: .porter), ["Édouard", "manet"]) + try XCTAssertEqual(FTS3.tokenize("Édouard Manet", withTokenizer: .unicode61()), ["edouard", "manet"]) + try XCTAssertEqual(FTS3.tokenize("Édouard Manet", withTokenizer: .unicode61(diacritics: .keep)), ["édouard", "manet"]) // Prefix queries - XCTAssertEqual(FTS3.tokenize("*"), []) - XCTAssertEqual(FTS3.tokenize("*", withTokenizer: .simple), []) - XCTAssertEqual(FTS3.tokenize("*", withTokenizer: .porter), []) - XCTAssertEqual(FTS3.tokenize("*", withTokenizer: .unicode61()), []) - XCTAssertEqual(FTS3.tokenize("*", withTokenizer: .unicode61(diacritics: .keep)), []) + try XCTAssertEqual(FTS3.tokenize("*"), []) + try XCTAssertEqual(FTS3.tokenize("*", withTokenizer: .simple), []) + try XCTAssertEqual(FTS3.tokenize("*", withTokenizer: .porter), []) + try XCTAssertEqual(FTS3.tokenize("*", withTokenizer: .unicode61()), []) + try XCTAssertEqual(FTS3.tokenize("*", withTokenizer: .unicode61(diacritics: .keep)), []) - XCTAssertEqual(FTS3.tokenize("Robin*"), ["robin"]) - XCTAssertEqual(FTS3.tokenize("Robin*", withTokenizer: .simple), ["robin"]) - XCTAssertEqual(FTS3.tokenize("Robin*", withTokenizer: .porter), ["robin"]) - XCTAssertEqual(FTS3.tokenize("Robin*", withTokenizer: .unicode61()), ["robin"]) - XCTAssertEqual(FTS3.tokenize("Robin*", withTokenizer: .unicode61(diacritics: .keep)), ["robin"]) + try XCTAssertEqual(FTS3.tokenize("Robin*"), ["robin"]) + try XCTAssertEqual(FTS3.tokenize("Robin*", withTokenizer: .simple), ["robin"]) + try XCTAssertEqual(FTS3.tokenize("Robin*", withTokenizer: .porter), ["robin"]) + try XCTAssertEqual(FTS3.tokenize("Robin*", withTokenizer: .unicode61()), ["robin"]) + try XCTAssertEqual(FTS3.tokenize("Robin*", withTokenizer: .unicode61(diacritics: .keep)), ["robin"]) // Phrase queries - XCTAssertEqual(FTS3.tokenize("\"foulent muscles\""), ["foulent", "muscles"]) - XCTAssertEqual(FTS3.tokenize("\"foulent muscles\"", withTokenizer: .simple), ["foulent", "muscles"]) - XCTAssertEqual(FTS3.tokenize("\"foulent muscles\"", withTokenizer: .porter), ["foulent", "muscl"]) - XCTAssertEqual(FTS3.tokenize("\"foulent muscles\"", withTokenizer: .unicode61()), ["foulent", "muscles"]) - XCTAssertEqual(FTS3.tokenize("\"foulent muscles\"", withTokenizer: .unicode61(diacritics: .keep)), ["foulent", "muscles"]) + try XCTAssertEqual(FTS3.tokenize("\"foulent muscles\""), ["foulent", "muscles"]) + try XCTAssertEqual(FTS3.tokenize("\"foulent muscles\"", withTokenizer: .simple), ["foulent", "muscles"]) + try XCTAssertEqual(FTS3.tokenize("\"foulent muscles\"", withTokenizer: .porter), ["foulent", "muscl"]) + try XCTAssertEqual(FTS3.tokenize("\"foulent muscles\"", withTokenizer: .unicode61()), ["foulent", "muscles"]) + try XCTAssertEqual(FTS3.tokenize("\"foulent muscles\"", withTokenizer: .unicode61(diacritics: .keep)), ["foulent", "muscles"]) - XCTAssertEqual(FTS3.tokenize("\"Kim Stan* Robin*\""), ["kim", "stan", "robin"]) - XCTAssertEqual(FTS3.tokenize("\"Kim Stan* Robin*\"", withTokenizer: .simple), ["kim", "stan", "robin"]) - XCTAssertEqual(FTS3.tokenize("\"Kim Stan* Robin*\"", withTokenizer: .porter), ["kim", "stan", "robin"]) - XCTAssertEqual(FTS3.tokenize("\"Kim Stan* Robin*\"", withTokenizer: .unicode61()), ["kim", "stan", "robin"]) - XCTAssertEqual(FTS3.tokenize("\"Kim Stan* Robin*\"", withTokenizer: .unicode61(diacritics: .keep)), ["kim", "stan", "robin"]) + try XCTAssertEqual(FTS3.tokenize("\"Kim Stan* Robin*\""), ["kim", "stan", "robin"]) + try XCTAssertEqual(FTS3.tokenize("\"Kim Stan* Robin*\"", withTokenizer: .simple), ["kim", "stan", "robin"]) + try XCTAssertEqual(FTS3.tokenize("\"Kim Stan* Robin*\"", withTokenizer: .porter), ["kim", "stan", "robin"]) + try XCTAssertEqual(FTS3.tokenize("\"Kim Stan* Robin*\"", withTokenizer: .unicode61()), ["kim", "stan", "robin"]) + try XCTAssertEqual(FTS3.tokenize("\"Kim Stan* Robin*\"", withTokenizer: .unicode61(diacritics: .keep)), ["kim", "stan", "robin"]) // Logical queries - XCTAssertEqual(FTS3.tokenize("years AND months"), ["years", "and", "months"]) - XCTAssertEqual(FTS3.tokenize("years AND months", withTokenizer: .simple), ["years", "and", "months"]) - XCTAssertEqual(FTS3.tokenize("years AND months", withTokenizer: .porter), ["year", "and", "month"]) - XCTAssertEqual(FTS3.tokenize("years AND months", withTokenizer: .unicode61()), ["years", "and", "months"]) - XCTAssertEqual(FTS3.tokenize("years AND months", withTokenizer: .unicode61(diacritics: .keep)), ["years", "and", "months"]) + try XCTAssertEqual(FTS3.tokenize("years AND months"), ["years", "and", "months"]) + try XCTAssertEqual(FTS3.tokenize("years AND months", withTokenizer: .simple), ["years", "and", "months"]) + try XCTAssertEqual(FTS3.tokenize("years AND months", withTokenizer: .porter), ["year", "and", "month"]) + try XCTAssertEqual(FTS3.tokenize("years AND months", withTokenizer: .unicode61()), ["years", "and", "months"]) + try XCTAssertEqual(FTS3.tokenize("years AND months", withTokenizer: .unicode61(diacritics: .keep)), ["years", "and", "months"]) // column queries - XCTAssertEqual(FTS3.tokenize("title:brest"), ["title", "brest"]) - XCTAssertEqual(FTS3.tokenize("title:brest", withTokenizer: .simple), ["title", "brest"]) - XCTAssertEqual(FTS3.tokenize("title:brest", withTokenizer: .porter), ["titl", "brest"]) - XCTAssertEqual(FTS3.tokenize("title:brest", withTokenizer: .unicode61()), ["title", "brest"]) - XCTAssertEqual(FTS3.tokenize("title:brest", withTokenizer: .unicode61(diacritics: .keep)), ["title", "brest"]) + try XCTAssertEqual(FTS3.tokenize("title:brest"), ["title", "brest"]) + try XCTAssertEqual(FTS3.tokenize("title:brest", withTokenizer: .simple), ["title", "brest"]) + try XCTAssertEqual(FTS3.tokenize("title:brest", withTokenizer: .porter), ["titl", "brest"]) + try XCTAssertEqual(FTS3.tokenize("title:brest", withTokenizer: .unicode61()), ["title", "brest"]) + try XCTAssertEqual(FTS3.tokenize("title:brest", withTokenizer: .unicode61(diacritics: .keep)), ["title", "brest"]) } } diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index 8f322063b..f6c2eb6f0 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -10,11 +10,7 @@ private struct Book { extension Book : FetchableRecord { init(row: Row) { - #if compiler(>=5.5) id = row[.rowID] - #else - id = row[Column.rowID] - #endif title = row["title"] author = row["author"] body = row["body"] @@ -26,23 +22,19 @@ extension Book : MutablePersistableRecord { static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] func encode(to container: inout PersistenceContainer) { - #if compiler(>=5.5) container[.rowID] = id - #else - container[Column.rowID] = id - #endif container["title"] = title container["author"] = author container["body"] = body } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } class FTS4RecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(virtualTable: "books", using: FTS4()) { t in t.column("title") diff --git a/Tests/GRDBTests/FTS5PatternTests.swift b/Tests/GRDBTests/FTS5PatternTests.swift index ec9478c29..fc7e1a0bf 100644 --- a/Tests/GRDBTests/FTS5PatternTests.swift +++ b/Tests/GRDBTests/FTS5PatternTests.swift @@ -4,7 +4,7 @@ import GRDB class FTS5PatternTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(virtualTable: "books", using: FTS5()) { t in t.column("title") diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index 2e23f03f4..eac65c0a2 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -11,11 +11,7 @@ private struct Book { extension Book : FetchableRecord { init(row: Row) { - #if compiler(>=5.5) id = row[.rowID] - #else - id = row[Column.rowID] - #endif title = row["title"] author = row["author"] body = row["body"] @@ -27,23 +23,19 @@ extension Book : MutablePersistableRecord { static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] func encode(to container: inout PersistenceContainer) { - #if compiler(>=5.5) container[.rowID] = id - #else - container[Column.rowID] = id - #endif container["title"] = title container["author"] = author container["body"] = body } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } class FTS5RecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(virtualTable: "books", using: FTS5()) { t in t.column("title") diff --git a/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift b/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift index 56ba346dc..b7861e525 100644 --- a/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift +++ b/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift @@ -37,15 +37,8 @@ private final class LatinAsciiTokenizer : FTS5WrapperTokenizer { func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws { // Convert token to Latin-ASCII and lowercase - if #available(OSX 10.11, *) { - if let token = token.applyingTransform(StringTransform("Latin-ASCII; Lower"), reverse: false) { - try tokenCallback(token, flags) - } - } else { - if let token = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, token as CFString) { - CFStringTransform(token, nil, "Latin-ASCII; Lower" as CFString, false) - try tokenCallback(token as String, flags) - } + if let token = token.applyingTransform(StringTransform("Latin-ASCII; Lower"), reverse: false) { + try tokenCallback(token, flags) } } } diff --git a/Tests/GRDBTests/FailureTestCase.swift b/Tests/GRDBTests/FailureTestCase.swift index 2425b41e9..9dfb9770b 100644 --- a/Tests/GRDBTests/FailureTestCase.swift +++ b/Tests/GRDBTests/FailureTestCase.swift @@ -4,16 +4,8 @@ import XCTest /// A XCTestCase subclass that can test its own failures. class FailureTestCase: XCTestCase { private struct Failure: Hashable { - #if compiler(>=5.3) let issue: XCTIssue - #else - var description: String - var file: String - var line: Int - var expected: Bool - #endif - #if compiler(>=5.3) func issue(prefix: String = "") -> XCTIssue { if prefix.isEmpty { return issue @@ -27,22 +19,10 @@ class FailureTestCase: XCTestCase { attachments: issue.attachments) } } - #else - func failure(prefix: String = "") -> (description: String, file: String, line: Int, expected: Bool) { - let prefix = prefix.isEmpty ? "" : "\(prefix): " - return ( - description: prefix + description, - file: file, - line: line, - expected: expected) - } - #endif - #if compiler(>=5.3) private var description: String { return issue.compactDescription } - #endif func hash(into hasher: inout Hasher) { hasher.combine(0) @@ -60,7 +40,6 @@ class FailureTestCase: XCTestCase { let recordedFailures = try recordingFailures(execute) if prefixes.isEmpty { if recordedFailures.isEmpty { - #if compiler(>=5.3) record(XCTIssue( type: .assertionFailure, compactDescription: "No failure did happen", @@ -71,17 +50,9 @@ class FailureTestCase: XCTestCase { lineNumber: Int(line))), associatedError: nil, attachments: [])) - #else - recordFailure( - withDescription: "No failure did happen", - inFile: file.description, - atLine: Int(line), - expected: true) - #endif } } else { let expectedFailures = prefixes.map { prefix -> Failure in - #if compiler(>=5.3) return Failure(issue: XCTIssue( type: .assertionFailure, compactDescription: prefix, @@ -92,13 +63,6 @@ class FailureTestCase: XCTestCase { lineNumber: Int(line))), associatedError: nil, attachments: [])) - #else - return Failure( - description: prefix, - file: String(describing: file), - line: Int(line), - expected: true) - #endif } assertMatch( recordedFailures: recordedFailures, @@ -112,7 +76,6 @@ class FailureTestCase: XCTestCase { recordedFailures = [] } - #if compiler(>=5.3) override func record(_ issue: XCTIssue) { if isRecordingFailures { recordedFailures.append(Failure(issue: issue)) @@ -120,23 +83,6 @@ class FailureTestCase: XCTestCase { super.record(issue) } } - #else - override func recordFailure(withDescription description: String, inFile filePath: String, atLine lineNumber: Int, expected: Bool) { - if isRecordingFailures { - recordedFailures.append(Failure( - description: description, - file: filePath, - line: lineNumber, - expected: expected)) - } else { - super.recordFailure( - withDescription: description, - inFile: filePath, - atLine: lineNumber, - expected: expected) - } - } - #endif private func recordingFailures(_ execute: () throws -> Void) rethrows -> [Failure] { let oldRecordingFailures = isRecordingFailures @@ -161,16 +107,7 @@ class FailureTestCase: XCTestCase { if let index = expectedFailures.firstIndex(of: failure) { expectedFailures.remove(at: index) } else { - #if compiler(>=5.3) record(failure.issue()) - #else - let failure = failure.failure() - recordFailure( - withDescription: failure.description, - inFile: failure.file, - atLine: failure.line, - expected: failure.expected) - #endif } } @@ -179,16 +116,7 @@ class FailureTestCase: XCTestCase { if let index = recordedFailures.firstIndex(of: failure) { recordedFailures.remove(at: index) } else { - #if compiler(>=5.3) record(failure.issue(prefix: "Failure did not happen")) - #else - let failure = failure.failure(prefix: "Failure did not happen") - recordFailure( - withDescription: failure.description, - inFile: failure.file, - atLine: failure.line, - expected: failure.expected) - #endif } } } diff --git a/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift index 52004ac3e..8fd39c92b 100644 --- a/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift @@ -24,8 +24,8 @@ extension Reader : MutablePersistableRecord { container["age"] = age } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -46,7 +46,7 @@ extension AltReader : FetchableRecord { class FetchableRecordQueryInterfaceRequestTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/FetchableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift index 36c6c76ab..6c8113a33 100644 --- a/Tests/GRDBTests/FetchableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -8,18 +8,18 @@ class FetchableRecordDecodableTests: GRDBTestCase { } extension FetchableRecordDecodableTests { - func testTrivialDecodable() { + func testTrivialDecodable() throws { struct Struct : FetchableRecord, Decodable { let value: String } do { - let s = Struct(row: ["value": "foo"]) + let s = try Struct(row: ["value": "foo"]) XCTAssertEqual(s.value, "foo") } } - func testCustomDecodable() { + func testCustomDecodable() throws { struct Struct : FetchableRecord, Decodable { let value: String @@ -34,7 +34,7 @@ extension FetchableRecordDecodableTests { } do { - let s = Struct(row: ["someColumn": "foo"]) + let s = try Struct(row: ["someColumn": "foo"]) XCTAssertEqual(s.value, "foo") } } @@ -59,7 +59,7 @@ extension FetchableRecordDecodableTests { extension FetchableRecordDecodableTests { - func testTrivialProperty() { + func testTrivialProperty() throws { struct Struct : FetchableRecord, Decodable { let int64: Int64 let optionalInt64: Int64? @@ -67,25 +67,25 @@ extension FetchableRecordDecodableTests { do { // No null values - let s = Struct(row: ["int64": 1, "optionalInt64": 2]) + let s = try Struct(row: ["int64": 1, "optionalInt64": 2]) XCTAssertEqual(s.int64, 1) XCTAssertEqual(s.optionalInt64, 2) } do { // Null values - let s = Struct(row: ["int64": 2, "optionalInt64": nil]) + let s = try Struct(row: ["int64": 2, "optionalInt64": nil]) XCTAssertEqual(s.int64, 2) XCTAssertNil(s.optionalInt64) } do { // Missing and extra values - let s = Struct(row: ["int64": 3, "ignored": "?"]) + let s = try Struct(row: ["int64": 3, "ignored": "?"]) XCTAssertEqual(s.int64, 3) XCTAssertNil(s.optionalInt64) } } - func testTrivialSingleValueDecodableProperty() { + func testTrivialSingleValueDecodableProperty() throws { struct Value : Decodable { let string: String @@ -101,27 +101,27 @@ extension FetchableRecordDecodableTests { do { // No null values - let s = Struct(row: ["value": "foo", "optionalValue": "bar"]) + let s = try Struct(row: ["value": "foo", "optionalValue": "bar"]) XCTAssertEqual(s.value.string, "foo") XCTAssertEqual(s.optionalValue!.string, "bar") } do { // Null values - let s = Struct(row: ["value": "foo", "optionalValue": nil]) + let s = try Struct(row: ["value": "foo", "optionalValue": nil]) XCTAssertEqual(s.value.string, "foo") XCTAssertNil(s.optionalValue) } do { // Missing and extra values - let s = Struct(row: ["value": "foo", "ignored": "?"]) + let s = try Struct(row: ["value": "foo", "ignored": "?"]) XCTAssertEqual(s.value.string, "foo") XCTAssertNil(s.optionalValue) } } - func testNonTrivialSingleValueDecodableProperty() { + func testNonTrivialSingleValueDecodableProperty() throws { struct NestedValue : Decodable { let string: String @@ -145,27 +145,27 @@ extension FetchableRecordDecodableTests { do { // No null values - let s = Struct(row: ["value": "foo", "optionalValue": "bar"]) + let s = try Struct(row: ["value": "foo", "optionalValue": "bar"]) XCTAssertEqual(s.value.nestedValue.string, "foo") XCTAssertEqual(s.optionalValue!.nestedValue.string, "bar") } do { // Null values - let s = Struct(row: ["value": "foo", "optionalValue": nil]) + let s = try Struct(row: ["value": "foo", "optionalValue": nil]) XCTAssertEqual(s.value.nestedValue.string, "foo") XCTAssertNil(s.optionalValue) } do { // Missing and extra values - let s = Struct(row: ["value": "foo", "ignored": "?"]) + let s = try Struct(row: ["value": "foo", "ignored": "?"]) XCTAssertEqual(s.value.nestedValue.string, "foo") XCTAssertNil(s.optionalValue) } } - func testDecodableRawRepresentableProperty() { + func testDecodableRawRepresentableProperty() throws { // This test is somewhat redundant with testSingleValueDecodableProperty, // since a RawRepresentable enum is a "single-value" Decodable. // @@ -182,27 +182,27 @@ extension FetchableRecordDecodableTests { do { // No null values - let s = Struct(row: ["value": "foo", "optionalValue": "bar"]) + let s = try Struct(row: ["value": "foo", "optionalValue": "bar"]) XCTAssertEqual(s.value, .foo) XCTAssertEqual(s.optionalValue!, .bar) } do { // Null values - let s = Struct(row: ["value": "foo", "optionalValue": nil]) + let s = try Struct(row: ["value": "foo", "optionalValue": nil]) XCTAssertEqual(s.value, .foo) XCTAssertNil(s.optionalValue) } do { // Missing and extra values - let s = Struct(row: ["value": "foo", "ignored": "?"]) + let s = try Struct(row: ["value": "foo", "ignored": "?"]) XCTAssertEqual(s.value, .foo) XCTAssertNil(s.optionalValue) } } - func testDatabaseValueConvertibleProperty() { + func testDatabaseValueConvertibleProperty() throws { // This test makes sure that Date, for example, can be read from a String. // // Without this preference for fromDatabaseValue(_:) over init(from:Decoder), @@ -238,21 +238,21 @@ extension FetchableRecordDecodableTests { do { // No null values - let s = Struct(row: ["value": "foo", "optionalValue": "bar"]) + let s = try Struct(row: ["value": "foo", "optionalValue": "bar"]) XCTAssertEqual(s.value.string, "foo (DatabaseValueConvertible)") XCTAssertEqual(s.optionalValue!.string, "bar (DatabaseValueConvertible)") } do { // Null values - let s = Struct(row: ["value": "foo", "optionalValue": nil]) + let s = try Struct(row: ["value": "foo", "optionalValue": nil]) XCTAssertEqual(s.value.string, "foo (DatabaseValueConvertible)") XCTAssertNil(s.optionalValue) } do { // Missing and extra values - let s = Struct(row: ["value": "foo", "ignored": "?"]) + let s = try Struct(row: ["value": "foo", "ignored": "?"]) XCTAssertEqual(s.value.string, "foo (DatabaseValueConvertible)") XCTAssertNil(s.optionalValue) } @@ -263,33 +263,33 @@ extension FetchableRecordDecodableTests { extension FetchableRecordDecodableTests { - func testStructWithDate() { + func testStructWithDate() throws { struct StructWithDate : FetchableRecord, Decodable { let date: Date } let date = Date() - let value = StructWithDate(row: ["date": date]) + let value = try StructWithDate(row: ["date": date]) XCTAssert(abs(value.date.timeIntervalSince(date)) < 0.001) } - func testStructWithURL() { + func testStructWithURL() throws { struct StructWithURL : FetchableRecord, Decodable { let url: URL } let url = URL(string: "https://github.com") - let value = StructWithURL(row: ["url": url]) + let value = try StructWithURL(row: ["url": url]) XCTAssertEqual(value.url, url) } - func testStructWithUUID() { + func testStructWithUUID() throws { struct StructWithUUID : FetchableRecord, Decodable { let uuid: UUID } let uuid = UUID() - let value = StructWithUUID(row: ["uuid": uuid]) + let value = try StructWithUUID(row: ["uuid": uuid]) XCTAssertEqual(value.uuid, uuid) } } @@ -585,7 +585,7 @@ extension FetchableRecordDecodableTests { {"firstName":"Bob","lastName":"Dylan"} """] - let model = StructWithNestedType(row: row) + let model = try StructWithNestedType(row: row) XCTAssertEqual(model.nested.firstName, "Bob") XCTAssertEqual(model.nested.lastName, "Dylan") } @@ -1247,7 +1247,7 @@ extension FetchableRecordDecodableTests { test(record) let row = try Row.fetchOne(db, request)! - test(Record(row: row)) + try test(Record(row: row)) } } @@ -1282,7 +1282,7 @@ extension FetchableRecordDecodableTests { test(record) let row = try Row.fetchOne(db, request)! - test(Record(row: row)) + try test(Record(row: row)) } } @@ -1319,7 +1319,7 @@ extension FetchableRecordDecodableTests { test(record) let row = try Row.fetchOne(db, request)! - test(CustomizedRecord(row: row)) + try test(CustomizedRecord(row: row)) } } @@ -1354,7 +1354,7 @@ extension FetchableRecordDecodableTests { test(record) let row = try Row.fetchOne(db, request)! - test(CustomizedRecord(row: row)) + try test(CustomizedRecord(row: row)) } } diff --git a/Tests/GRDBTests/ForeignKeyInfoTests.swift b/Tests/GRDBTests/ForeignKeyInfoTests.swift index 483db5179..4ecb4d5d4 100644 --- a/Tests/GRDBTests/ForeignKeyInfoTests.swift +++ b/Tests/GRDBTests/ForeignKeyInfoTests.swift @@ -3,7 +3,7 @@ import XCTest class ForeignKeyInfoTests: GRDBTestCase { - private func _assertEqual(_ lhs: ForeignKeyInfo, _ rhs: ForeignKeyInfo, file: StaticString, line: UInt) { + private func assertEqual(_ lhs: ForeignKeyInfo, _ rhs: ForeignKeyInfo, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(lhs.destinationTable, rhs.destinationTable, file: file, line: line) XCTAssertEqual(lhs.mapping.count, rhs.mapping.count, file: file, line: line) for (larrow, rarrow) in zip(lhs.mapping, rhs.mapping) { @@ -12,17 +12,6 @@ class ForeignKeyInfoTests: GRDBTestCase { } } - // #file vs. #filePath dance - #if compiler(>=5.3) - private func assertEqual(_ lhs: ForeignKeyInfo, _ rhs: ForeignKeyInfo, file: StaticString = #filePath, line: UInt = #line) { - _assertEqual(lhs, rhs, file: file, line: line) - } - #else - private func assertEqual(_ lhs: ForeignKeyInfo, _ rhs: ForeignKeyInfo, file: StaticString = #file, line: UInt = #line) { - _assertEqual(lhs, rhs, file: file, line: line) - } - #endif - func testForeignKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/FoundationDateComponentsTests.swift b/Tests/GRDBTests/FoundationDateComponentsTests.swift index 9a7b42801..b336a7525 100644 --- a/Tests/GRDBTests/FoundationDateComponentsTests.swift +++ b/Tests/GRDBTests/FoundationDateComponentsTests.swift @@ -3,7 +3,7 @@ import GRDB class FoundationDateComponentsTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createDates") { db in try db.execute(sql: """ @@ -349,7 +349,7 @@ class FoundationDateComponentsTests : GRDBTestCase { } func testDatabaseDateComponentsParsing() { - func _assertParse(_ string: String, _ dateComponent: DatabaseDateComponents, file: StaticString, line: UInt) { + func assertParse(_ string: String, _ dateComponent: DatabaseDateComponents, file: StaticString = #file, line: UInt = #line) { do { // Test DatabaseValueConvertible adoption guard let parsed = DatabaseDateComponents.fromDatabaseValue(string.databaseValue) else { @@ -372,17 +372,6 @@ class FoundationDateComponentsTests : GRDBTestCase { } } - // #file vs. #filePath dance - #if compiler(>=5.3) - func assertParse(_ string: String, _ dateComponent: DatabaseDateComponents, file: StaticString = #filePath, line: UInt = #line) { - _assertParse(string, dateComponent, file: file, line: line) - } - #else - func assertParse(_ string: String, _ dateComponent: DatabaseDateComponents, file: StaticString = #file, line: UInt = #line) { - _assertParse(string, dateComponent, file: file, line: line) - } - #endif - assertParse( "0000-01-01", DatabaseDateComponents( diff --git a/Tests/GRDBTests/FoundationDateTests.swift b/Tests/GRDBTests/FoundationDateTests.swift index 63c7e2c80..024ef4395 100644 --- a/Tests/GRDBTests/FoundationDateTests.swift +++ b/Tests/GRDBTests/FoundationDateTests.swift @@ -3,7 +3,7 @@ import GRDB class FoundationDateTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createDates") { db in try db.execute(sql: """ @@ -322,12 +322,12 @@ class FoundationDateTests : GRDBTestCase { return } - func _assert( + func assert( _ db: Database, _ expression: SQLExpression, equal expectedDate: Date, - file: StaticString, - line: UInt) throws + file: StaticString = #file, + line: UInt = #line) throws { let request: SQLRequest = "SELECT \(expression)" guard let shiftedDate = try request.fetchOne(db).flatMap(Date.init(julianDay:)) else { @@ -339,29 +339,6 @@ class FoundationDateTests : GRDBTestCase { XCTAssertEqual(shiftedInterval, expectedInterval, accuracy: 0.1, file: file, line: line) } - // #file vs. #filePath dance - #if compiler(>=5.3) - func assert( - _ db: Database, - _ expression: SQLExpression, - equal expectedDate: Date, - file: StaticString = #filePath, - line: UInt = #line) throws - { - try _assert(db, expression, equal: expectedDate, file: file, line: line) - } - #else - func assert( - _ db: Database, - _ expression: SQLExpression, - equal expectedDate: Date, - file: StaticString = #file, - line: UInt = #line) throws - { - try _assert(db, expression, equal: expectedDate, file: file, line: line) - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let dbDate = date.databaseValue @@ -394,12 +371,12 @@ class FoundationDateTests : GRDBTestCase { return } - func _assert( + func assert( _ db: Database, _ expression: SQLExpression, equal expectedDate: String, - file: StaticString, - line: UInt) throws + file: StaticString = #file, + line: UInt = #line) throws { let request: SQLRequest = "SELECT \(expression)" guard let shiftedDate = try request.fetchOne(db) else { @@ -409,29 +386,6 @@ class FoundationDateTests : GRDBTestCase { XCTAssertEqual(shiftedDate, expectedDate, file: file, line: line) } - // #file vs. #filePath dance - #if compiler(>=5.3) - func assert( - _ db: Database, - _ expression: SQLExpression, - equal expectedDate: String, - file: StaticString = #filePath, - line: UInt = #line) throws - { - try _assert(db, expression, equal: expectedDate, file: file, line: line) - } - #else - func assert( - _ db: Database, - _ expression: SQLExpression, - equal expectedDate: String, - file: StaticString = #file, - line: UInt = #line) throws - { - try _assert(db, expression, equal: expectedDate, file: file, line: line) - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let dbDate = date.databaseValue diff --git a/Tests/GRDBTests/FoundationNSDateTests.swift b/Tests/GRDBTests/FoundationNSDateTests.swift index f7405715d..d00dbc3c6 100644 --- a/Tests/GRDBTests/FoundationNSDateTests.swift +++ b/Tests/GRDBTests/FoundationNSDateTests.swift @@ -3,7 +3,7 @@ import GRDB class FoundationNSDateTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createDates") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 6c0d5b2e4..6ea977a0d 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -49,7 +49,7 @@ class GRDBTestCase: XCTestCase { // Subclasses can override // Default implementation is empty. - func setup(_ dbWriter: DatabaseWriter) throws { + func setup(_ dbWriter: some DatabaseWriter) throws { } // The default path for database pool directory @@ -121,7 +121,7 @@ class GRDBTestCase: XCTestCase { do { try FileManager.default.removeItem(atPath: dbDirectoryPath) } catch { } } - private func _assertNoError(file: StaticString, line: UInt, _ test: () throws -> Void) { + func assertNoError(file: StaticString = #file, line: UInt = #line, _ test: () throws -> Void) { do { try test() } catch { @@ -129,93 +129,36 @@ class GRDBTestCase: XCTestCase { } } - private func _assertDidExecute(sql: String, file: StaticString, line: UInt) { + func assertDidExecute(sql: String, file: StaticString = #file, line: UInt = #line) { XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)", file: file, line: line) } - private func _assert(_ record: EncodableRecord, isEncodedIn row: Row, file: StaticString, line: UInt) { - let recordDict = record.databaseDictionary + func assert(_ record: some EncodableRecord, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) throws { + let recordDict = try record.databaseDictionary let rowDict = Dictionary(row, uniquingKeysWith: { (left, _) in left }) XCTAssertEqual(recordDict, rowDict, file: file, line: line) } // Compare SQL strings (ignoring leading and trailing white space and semicolons. - private func _assertEqualSQL(_ lhs: String, _ rhs: String, file: StaticString, line: UInt) { + func assertEqualSQL(_ lhs: String, _ rhs: String, file: StaticString = #file, line: UInt = #line) { // Trim white space and ";" let cs = CharacterSet.whitespacesAndNewlines.union(CharacterSet(charactersIn: ";")) XCTAssertEqual(lhs.trimmingCharacters(in: cs), rhs.trimmingCharacters(in: cs), file: file, line: line) } // Compare SQL strings (ignoring leading and trailing white space and semicolons. - private func _assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString, line: UInt) throws { + func assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { try request.makeStatement(db).makeCursor().next() assertEqualSQL(lastSQLQuery!, sql, file: file, line: line) } // Compare SQL strings (ignoring leading and trailing white space and semicolons. - private func _assertEqualSQL(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString, line: UInt) throws { + func assertEqualSQL(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { try databaseReader.unsafeRead { db in try assertEqualSQL(db, request, sql, file: file, line: line) } } - // #file vs. #filePath dance - #if compiler(>=5.3) - func assertNoError(file: StaticString = #filePath, line: UInt = #line, _ test: () throws -> Void) { - _assertNoError(file: file, line: line, test) - } - - func assertDidExecute(sql: String, file: StaticString = #filePath, line: UInt = #line) { - _assertDidExecute(sql: sql, file: file, line: line) - } - - func assert(_ record: EncodableRecord, isEncodedIn row: Row, file: StaticString = #filePath, line: UInt = #line) { - _assert(record, isEncodedIn: row, file: file, line: line) - } - - // Compare SQL strings (ignoring leading and trailing white space and semicolons. - func assertEqualSQL(_ lhs: String, _ rhs: String, file: StaticString = #filePath, line: UInt = #line) { - _assertEqualSQL(lhs, rhs, file: file, line: line) - } - - // Compare SQL strings (ignoring leading and trailing white space and semicolons. - func assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #filePath, line: UInt = #line) throws { - try _assertEqualSQL(db, request, sql, file: file, line: line) - } - - // Compare SQL strings (ignoring leading and trailing white space and semicolons. - func assertEqualSQL(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #filePath, line: UInt = #line) throws { - try _assertEqualSQL(databaseReader, request, sql, file: file, line: line) - } - #else - func assertNoError(file: StaticString = #file, line: UInt = #line, _ test: () throws -> Void) { - _assertNoError(file: file, line: line, test) - } - - func assertDidExecute(sql: String, file: StaticString = #file, line: UInt = #line) { - _assertDidExecute(sql: sql, file: file, line: line) - } - - func assert(_ record: EncodableRecord, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) { - _assert(record, isEncodedIn: row, file: file, line: line) - } - - // Compare SQL strings (ignoring leading and trailing white space and semicolons. - func assertEqualSQL(_ lhs: String, _ rhs: String, file: StaticString = #file, line: UInt = #line) { - _assertEqualSQL(lhs, rhs, file: file, line: line) - } - - // Compare SQL strings (ignoring leading and trailing white space and semicolons. - func assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { - try _assertEqualSQL(db, request, sql, file: file, line: line) - } - - // Compare SQL strings (ignoring leading and trailing white space and semicolons. - func assertEqualSQL(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { - try _assertEqualSQL(databaseReader, request, sql, file: file, line: line) - } - #endif - func sql(_ databaseReader: DatabaseReader, _ request: Request) -> String { try! databaseReader.unsafeRead { db in try request.makeStatement(db).makeCursor().next() @@ -224,6 +167,12 @@ class GRDBTestCase: XCTestCase { } } +#if SWIFT_PACKAGE +let testBundle = Bundle.module +#else +let testBundle = Bundle(for: GRDBTestCase.self) +#endif + extension FetchRequest { /// Turn request into a statement func makeStatement(_ db: Database) throws -> Statement { @@ -259,7 +208,5 @@ public struct AnyValueReducer: ValueReducer { } } -#if swift(>=5.6) && canImport(_Concurrency) // Assume this is correct :-/ extension XCTestExpectation: @unchecked Sendable { } -#endif diff --git a/Tests/GRDBTests/IndexInfoTests.swift b/Tests/GRDBTests/IndexInfoTests.swift index e5f1bde5c..d79ffa1eb 100644 --- a/Tests/GRDBTests/IndexInfoTests.swift +++ b/Tests/GRDBTests/IndexInfoTests.swift @@ -20,6 +20,7 @@ class IndexInfoTests: GRDBTestCase { XCTAssertEqual(indexes.count, 1) XCTAssertEqual(indexes[0].name, "sqlite_autoindex_persons_1") + XCTAssertEqual(indexes[0].origin, .uniqueConstraint) XCTAssertEqual(indexes[0].columns, ["email"]) XCTAssertTrue(indexes[0].isUnique) } @@ -32,6 +33,7 @@ class IndexInfoTests: GRDBTestCase { XCTAssertEqual(indexes.count, 2) if let i = indexes.firstIndex(where: { $0.columns == ["year"] }) { XCTAssertEqual(indexes[i].name, "citizenshipsOnYear") + XCTAssertEqual(indexes[i].origin, .createIndex) XCTAssertEqual(indexes[i].columns, ["year"]) XCTAssertFalse(indexes[i].isUnique) } else { @@ -39,6 +41,7 @@ class IndexInfoTests: GRDBTestCase { } if let i = indexes.firstIndex(where: { $0.columns == ["personId", "countryIsoCode"] }) { XCTAssertEqual(indexes[i].name, "sqlite_autoindex_citizenships_1") + XCTAssertEqual(indexes[i].origin, .primaryKeyConstraint) XCTAssertEqual(indexes[i].columns, ["personId", "countryIsoCode"]) XCTAssertTrue(indexes[i].isUnique) } else { @@ -84,6 +87,7 @@ class IndexInfoTests: GRDBTestCase { let indexes = try db.indexes(on: "player") XCTAssertEqual(indexes.count, 1) XCTAssertEqual(indexes[0].name, "columnIndex") + XCTAssertEqual(indexes[0].origin, .createIndex) XCTAssertEqual(indexes[0].columns, ["name"]) XCTAssertFalse(indexes[0].isUnique) } diff --git a/Tests/GRDBTests/InflectionsTests.swift b/Tests/GRDBTests/InflectionsTests.swift index 7c3a31c78..5736b8463 100644 --- a/Tests/GRDBTests/InflectionsTests.swift +++ b/Tests/GRDBTests/InflectionsTests.swift @@ -14,14 +14,11 @@ class InflectionsTests: GRDBTestCase { Inflections.default = originalInflections! } - // Until SPM tests can load resources, disable this test for SPM. - #if !SWIFT_PACKAGE private var inflectionTestCases: InflectionTestCases { - let url = Bundle(for: type(of: self)).url(forResource: "InflectionsTests", withExtension: "json")! + let url = testBundle.url(forResource: "InflectionsTests", withExtension: "json")! let data = try! Data(contentsOf: url) return try! JSONDecoder().decode(InflectionTestCases.self, from: data) } - #endif func testStartIndexOfLastWord() { func lastWord(_ string: String) -> String { @@ -158,8 +155,6 @@ class InflectionsTests: GRDBTestCase { XCTAssertEqual(countableWord.pluralized.singularized, "sponsor") } - // Until SPM tests can load resources, disable this test for SPM. - #if !SWIFT_PACKAGE func testPluralizeSingularWord() { for (singular, plural) in inflectionTestCases.testCases["SingularToPlural"]! { XCTAssertEqual(singular.pluralized, plural) @@ -174,10 +169,7 @@ class InflectionsTests: GRDBTestCase { XCTAssertEqual(suffixedSingular.pluralized, suffixedPlural) } } - #endif - // Until SPM tests can load resources, disable this test for SPM. - #if !SWIFT_PACKAGE func testSingularizePluralWord() { for (singular, plural) in inflectionTestCases.testCases["SingularToPlural"]! { XCTAssertEqual(plural.singularized, singular) @@ -192,10 +184,7 @@ class InflectionsTests: GRDBTestCase { XCTAssertEqual(suffixedPlural.singularized, suffixedSingular) } } - #endif - // Until SPM tests can load resources, disable this test for SPM. - #if !SWIFT_PACKAGE func testPluralizePluralWord() { for (_, plural) in inflectionTestCases.testCases["SingularToPlural"]! { XCTAssertEqual(plural.pluralized, plural) @@ -208,10 +197,7 @@ class InflectionsTests: GRDBTestCase { XCTAssertEqual(suffixedPlural.pluralized, suffixedPlural) } } - #endif - // Until SPM tests can load resources, disable this test for SPM. - #if !SWIFT_PACKAGE func testSingularizeSingularWord() { for (singular, _) in inflectionTestCases.testCases["SingularToPlural"]! { XCTAssertEqual(singular.singularized, singular) @@ -224,10 +210,7 @@ class InflectionsTests: GRDBTestCase { XCTAssertEqual(suffixedSingular.singularized, suffixedSingular) } } - #endif - // Until SPM tests can load resources, disable this test for SPM. - #if !SWIFT_PACKAGE func testIrregularityBetweenSingularAndPlural() { for (singular, plural) in inflectionTestCases.testCases["Irregularities"]! { Inflections.default.irregularSuffix(singular, plural) @@ -251,11 +234,8 @@ class InflectionsTests: GRDBTestCase { XCTAssertEqual(suffixedPlural.pluralized, suffixedPlural) } } - #endif } -// Until SPM tests can load resources, disable this test for SPM. -#if !SWIFT_PACKAGE struct InflectionTestCases: Decodable { var testCases: [String: [(String, String)]] @@ -285,4 +265,3 @@ struct InflectionTestCases: Decodable { self.testCases = testCases } } -#endif diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index 28bd96f17..9de30a497 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -92,6 +92,11 @@ private struct FlatModel: FetchableRecord { self.t5count = row.scopes[Scopes.suffix]!["t5count"] } + @available(iOS 13.0, macOS 10.15.0, tvOS 13.0, watchOS 6.0, *) + static func modernAll() -> some FetchRequest { + all() + } + static func all() -> AdaptedFetchRequest> { SQLRequest(literal: testedLiteral).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ @@ -108,8 +113,8 @@ private struct FlatModel: FetchableRecord { } } - static func hierarchicalAll() -> AdaptedFetchRequest> { - SQLRequest(literal: testedLiteral).adapted { db in + static func hierarchicalAll() -> AdaptedFetchRequest> { + SQLRequest(literal: testedLiteral).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), @@ -133,6 +138,11 @@ private struct CodableFlatModel: FetchableRecord, Codable { var t3: T3? var t5count: Int + @available(iOS 13.0, macOS 10.15.0, tvOS 13.0, watchOS 6.0, *) + static func modernAll() -> some FetchRequest { + all() + } + static func all() -> AdaptedFetchRequest> { SQLRequest(literal: testedLiteral).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ @@ -176,6 +186,11 @@ private struct CodableNestedModel: FetchableRecord, Codable { var t3: T3? var t5count: Int + @available(iOS 13.0, macOS 10.15.0, tvOS 13.0, watchOS 6.0, *) + static func modernAll() -> some FetchRequest { + all() + } + static func all() -> AdaptedFetchRequest> { SQLRequest(literal: testedLiteral).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ @@ -198,7 +213,7 @@ private struct CodableNestedModel: FetchableRecord, Codable { class JoinSupportTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "t1") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index f7b504584..bc974114b 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -16,20 +16,19 @@ private struct Player: FetchableRecord, MutablePersistableRecord, Codable { self.creationDate = creationDate } - mutating func insert(_ db: Database) throws { + mutating func willInsert(_ db: Database) throws { if creationDate == nil { creationDate = Date() } - try performInsert(db) } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } class MutablePersistableRecordChangesTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "players") { t in t.column("id", .integer).primaryKey() @@ -48,7 +47,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } let record = DegenerateRecord() XCTAssertTrue(record.databaseEquals(record)) - XCTAssertTrue(record.databaseChanges(from: record).isEmpty) + try XCTAssertTrue(record.databaseChanges(from: record).isEmpty) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -66,7 +65,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { do { let player = Player(id: nil, name: nil, score: nil, creationDate: nil) XCTAssertTrue(player.databaseEquals(player)) - XCTAssertTrue(player.databaseChanges(from: player).isEmpty) + try XCTAssertTrue(player.databaseChanges(from: player).isEmpty) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -78,7 +77,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { do { let player = Player(id: 1, name: "foo", score: 42, creationDate: Date()) XCTAssertTrue(player.databaseEquals(player)) - XCTAssertTrue(player.databaseChanges(from: player).isEmpty) + try XCTAssertTrue(player.databaseChanges(from: player).isEmpty) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -102,7 +101,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { newPlayer.name = "Bobby" XCTAssertFalse(newPlayer.databaseEquals(player)) - let changes = newPlayer.databaseChanges(from: player) + let changes = try newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["name"]!, "Arthur".databaseValue) @@ -119,7 +118,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { newPlayer.name = nil XCTAssertFalse(newPlayer.databaseEquals(player)) - let changes = newPlayer.databaseChanges(from: player) + let changes = try newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["name"]!, "Arthur".databaseValue) @@ -136,7 +135,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { newPlayer.score = 41 XCTAssertFalse(newPlayer.databaseEquals(player)) - let changes = newPlayer.databaseChanges(from: player) + let changes = try newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["score"]!, .null) @@ -154,7 +153,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { newPlayer.score = 41 XCTAssertFalse(newPlayer.databaseEquals(player)) - let changes = newPlayer.databaseChanges(from: player) + let changes = try newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 2) XCTAssertEqual(changes["name"]!, "Arthur".databaseValue) XCTAssertEqual(changes["score"]!, .null) @@ -184,7 +183,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { var oldPlayer = NarrowPlayer(ID: 1, NAME: "Arthur") let newPlayer = Player(id: 1, name: "Arthur", score: 41, creationDate: nil) - let changes = newPlayer.databaseChanges(from: oldPlayer) + let changes = try newPlayer.databaseChanges(from: oldPlayer) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["score"]!, .null) @@ -202,7 +201,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { var oldPlayer = NarrowPlayer(ID: 1, NAME: "Bobby") let newPlayer = Player(id: 1, name: "Arthur", score: 42, creationDate: nil) - let changes = newPlayer.databaseChanges(from: oldPlayer) + let changes = try newPlayer.databaseChanges(from: oldPlayer) XCTAssertEqual(changes.count, 2) XCTAssertEqual(changes["name"]!, "Bobby".databaseValue) XCTAssertEqual(changes["score"]!, .null) @@ -223,7 +222,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { let oldPlayer = Player(id: 1, name: "Arthur", score: 42, creationDate: nil) let newPlayer = NarrowPlayer(ID: 1, NAME: "Arthur") - let changes = newPlayer.databaseChanges(from: oldPlayer) + let changes = try newPlayer.databaseChanges(from: oldPlayer) XCTAssertTrue(changes.isEmpty) try dbQueue.inTransaction { db in @@ -238,7 +237,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { let oldPlayer = Player(id: 1, name: "Arthur", score: nil, creationDate: nil) let newPlayer = NarrowPlayer(ID: 1, NAME: "Arthur") - let changes = newPlayer.databaseChanges(from: oldPlayer) + let changes = try newPlayer.databaseChanges(from: oldPlayer) XCTAssertTrue(changes.isEmpty) try dbQueue.inTransaction { db in @@ -253,7 +252,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { var oldPlayer = Player(id: 1, name: "Arthur", score: nil, creationDate: nil) let newPlayer = NarrowPlayer(ID: 1, NAME: "Bobby") - let changes = newPlayer.databaseChanges(from: oldPlayer) + let changes = try newPlayer.databaseChanges(from: oldPlayer) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["NAME"]!, "Arthur".databaseValue) @@ -289,21 +288,22 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { case id, firstName, lastName } - required init(row: Row) { + required init(row: Row) throws { id = row[Columns.id] firstName = row[Columns.firstName] lastName = row[Columns.lastName] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container[Columns.id] = id container[Columns.firstName] = firstName container[Columns.lastName] = lastName } - override func didInsert(with rowID: Int64, for column: String?) { - id = rowID + override func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + id = inserted.rowID } } @@ -315,8 +315,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { t.column("lastName", .text) } - // This `let` is part of the test - let record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") + var record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") try record.insert(db) do { @@ -375,8 +374,8 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { self.lastName = lastName } - func didInsert(with rowID: Int64, for column: String?) { - id = rowID + func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -388,8 +387,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { t.column("lastName", .text) } - // This `let` is part of the test - let record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") + var record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") try record.insert(db) do { @@ -442,8 +440,8 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { var firstName: String? var lastName: String? - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } diff --git a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift index b67c4c60e..b6aa66fa8 100644 --- a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift @@ -21,7 +21,7 @@ extension MutablePersistableRecordEncodableTests { } var value = Struct(value: "foo") - assert(value, isEncodedIn: ["value": "foo"]) + try assert(value, isEncodedIn: ["value": "foo"]) try value.insert(db) let string = try String.fetchOne(db, sql: "SELECT value FROM t1")! @@ -51,7 +51,7 @@ extension MutablePersistableRecordEncodableTests { } var value = Struct(value: "foo") - assert(value, isEncodedIn: ["someColumn": "foo (Encodable)"]) + try assert(value, isEncodedIn: ["someColumn": "foo (Encodable)"]) try value.insert(db) let string = try String.fetchOne(db, sql: "SELECT someColumn FROM t1")! @@ -76,7 +76,7 @@ extension MutablePersistableRecordEncodableTests { } var value = Struct(value: "foo") - assert(value, isEncodedIn: ["value": "foo (MutablePersistableRecord)"]) + try assert(value, isEncodedIn: ["value": "foo (MutablePersistableRecord)"]) try value.insert(db) let string = try String.fetchOne(db, sql: "SELECT value FROM t1")! @@ -106,7 +106,7 @@ extension MutablePersistableRecordEncodableTests { try dbQueue.inTransaction { db in var value = Struct(int64: 123, optionalInt64: 456) - assert(value, isEncodedIn: ["int64": 123, "optionalInt64": 456]) + try assert(value, isEncodedIn: ["int64": 123, "optionalInt64": 456]) try value.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM t1")! @@ -116,7 +116,7 @@ extension MutablePersistableRecordEncodableTests { try dbQueue.inTransaction { db in var value = Struct(int64: 123, optionalInt64: nil) - assert(value, isEncodedIn: ["int64": 123, "optionalInt64": nil]) + try assert(value, isEncodedIn: ["int64": 123, "optionalInt64": nil]) try value.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM t1")! @@ -151,7 +151,7 @@ extension MutablePersistableRecordEncodableTests { try dbQueue.inTransaction { db in var value = Struct(value: Value(string: "foo"), optionalValue: Value(string: "bar")) - assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"]) + try assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"]) try value.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM t1")! @@ -161,7 +161,7 @@ extension MutablePersistableRecordEncodableTests { try dbQueue.inTransaction { db in var value = Struct(value: Value(string: "foo"), optionalValue: nil) - assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil]) + try assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil]) try value.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM t1")! @@ -205,7 +205,7 @@ extension MutablePersistableRecordEncodableTests { try dbQueue.inTransaction { db in var value = Struct(value: Value(nestedValue: NestedValue(string: "foo")), optionalValue: Value(nestedValue: NestedValue(string: "bar"))) - assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"]) + try assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"]) try value.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM t1")! @@ -215,7 +215,7 @@ extension MutablePersistableRecordEncodableTests { try dbQueue.inTransaction { db in var value = Struct(value: Value(nestedValue: NestedValue(string: "foo")), optionalValue: nil) - assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil]) + try assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil]) try value.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM t1")! @@ -250,7 +250,7 @@ extension MutablePersistableRecordEncodableTests { try dbQueue.inTransaction { db in var value = Struct(value: .foo, optionalValue: .bar) - assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"]) + try assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"]) try value.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM t1")! @@ -260,7 +260,7 @@ extension MutablePersistableRecordEncodableTests { try dbQueue.inTransaction { db in var value = Struct(value: .foo, optionalValue: nil) - assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil]) + try assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil]) try value.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM t1")! @@ -313,7 +313,7 @@ extension MutablePersistableRecordEncodableTests { try dbQueue.inTransaction { db in var value = Struct(value: Value(string: "foo"), optionalValue: Value(string: "bar")) - assert(value, isEncodedIn: ["value": "foo (DatabaseValueConvertible)", "optionalValue": "bar (DatabaseValueConvertible)"]) + try assert(value, isEncodedIn: ["value": "foo (DatabaseValueConvertible)", "optionalValue": "bar (DatabaseValueConvertible)"]) try value.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM t1")! @@ -323,7 +323,7 @@ extension MutablePersistableRecordEncodableTests { try dbQueue.inTransaction { db in var value = Struct(value: Value(string: "foo"), optionalValue: nil) - assert(value, isEncodedIn: ["value": "foo (DatabaseValueConvertible)", "optionalValue": nil]) + try assert(value, isEncodedIn: ["value": "foo (DatabaseValueConvertible)", "optionalValue": nil]) try value.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM t1")! @@ -377,7 +377,7 @@ extension MutablePersistableRecordEncodableTests { } let value = StructWithURL(url: URL(string: "https://github.com")!) - assert(value, isEncodedIn: ["url": value.url]) + try assert(value, isEncodedIn: ["url": value.url]) try value.insert(db) let dbValue = try DatabaseValue.fetchOne(db, sql: "SELECT url FROM t1")! @@ -400,7 +400,7 @@ extension MutablePersistableRecordEncodableTests { } let value = StructWithUUID(uuid: UUID()) - assert(value, isEncodedIn: ["uuid": value.uuid]) + try assert(value, isEncodedIn: ["uuid": value.uuid]) try value.insert(db) let dbValue = try DatabaseValue.fetchOne(db, sql: "SELECT uuid FROM t1")! @@ -640,7 +640,6 @@ extension MutablePersistableRecordEncodableTests { } } - @available(OSX 10.13, iOS 11.0, tvOS 11.0, *) struct CustomizedRecord: Encodable, MutablePersistableRecord { var nestedKeyed: NestedKeyed var nestedSingle: NestedSingle @@ -681,10 +680,6 @@ extension MutablePersistableRecordEncodableTests { // Used as a reference func testFoundationBehavior() throws { - guard #available(OSX 10.13, iOS 11.0, tvOS 11.0, *) else { - throw XCTSkip("JSONEncoder.OutputFormatting.sortedKeys is not available") - } - do { let record = Record( nestedKeyed: NestedKeyed(name: "foo"), @@ -740,10 +735,6 @@ extension MutablePersistableRecordEncodableTests { } func testRecord() throws { - guard #available(OSX 10.13, iOS 11.0, tvOS 11.0, *) else { - throw XCTSkip("JSONEncoder.OutputFormatting.sortedKeys is not available") - } - let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "record") { t in @@ -771,10 +762,6 @@ extension MutablePersistableRecordEncodableTests { } func testCustomizedRecord() throws { - guard #available(OSX 10.13, iOS 11.0, tvOS 11.0, *) else { - throw XCTSkip("JSONEncoder.OutputFormatting.sortedKeys is not available") - } - let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "customizedRecord") { t in diff --git a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift index ddf471bb2..1caa68b1c 100644 --- a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift @@ -10,8 +10,8 @@ private struct DefaultPolicy: MutablePersistableRecord { container["id"] = id } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -25,8 +25,8 @@ private struct MixedPolicy: MutablePersistableRecord { container["id"] = id } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -42,8 +42,8 @@ private struct ReplacePolicy: MutablePersistableRecord { container["email"] = email } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -57,8 +57,8 @@ private struct IgnorePolicy: MutablePersistableRecord { container["id"] = id } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -72,8 +72,8 @@ private struct FailPolicy: MutablePersistableRecord { container["id"] = id } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -87,8 +87,8 @@ private struct AbortPolicy: MutablePersistableRecord { container["id"] = id } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -102,8 +102,8 @@ private struct RollbackPolicy: MutablePersistableRecord { container["id"] = id } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -134,6 +134,25 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { XCTAssertTrue(self.lastSQLQuery!.hasPrefix("UPDATE \"records\"")) } } + + func testPolicyOverride() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "records") { t in + t.column("id", .integer).primaryKey() + } + + // Insert + var record = DefaultPolicy(id: nil) + try record.insert(db, onConflict: .ignore) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("INSERT OR IGNORE INTO \"records\"")) + + // Update + record = DefaultPolicy(id: 1) + try record.update(db, onConflict: .ignore) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("UPDATE OR IGNORE \"records\"")) + } + } func testMixedPolicy() throws { let dbQueue = try makeDatabaseQueue() @@ -242,7 +261,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { var record = IgnorePolicy(id: nil) try record.insert(db) XCTAssertTrue(self.lastSQLQuery!.hasPrefix("INSERT OR IGNORE INTO \"records\"")) - XCTAssertTrue(record.id == nil) + XCTAssertEqual(record.id, 1) // Update record = IgnorePolicy(id: 1) diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index 11eefc9c9..93e415ba1 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -15,8 +15,19 @@ private struct MutablePersistableRecordPerson : MutablePersistableRecord { container["aGe"] = age } - mutating func didInsert(with rowID: Int64, for column: String?) { - self.id = rowID + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + let inserted = try insert() + XCTAssertNotNil(inserted.rowID) + XCTAssertEqual(inserted.rowIDColumn, "id") + XCTAssertEqual(inserted.persistenceContainer["iD"]?.databaseValue, inserted.rowID.databaseValue) + XCTAssertEqual(inserted.persistenceContainer["id"]?.databaseValue, inserted.rowID.databaseValue) + } + + mutating func didInsert(_ inserted: InsertionSuccess) { + XCTAssertEqual(inserted.rowIDColumn, "id") + XCTAssertEqual(inserted.persistenceContainer["iD"]?.databaseValue, inserted.rowID.databaseValue) + XCTAssertEqual(inserted.persistenceContainer["id"]?.databaseValue, inserted.rowID.databaseValue) + id = inserted.rowID } } @@ -32,20 +43,39 @@ private struct MutablePersistableRecordCountry : MutablePersistableRecord { container["name"] = name } - mutating func didInsert(with rowID: Int64, for column: String?) { - self.rowID = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + XCTAssertNil(inserted.rowIDColumn) + rowID = inserted.rowID } } +private class Callbacks { + var willInsertCount = 0 + var aroundInsertEnterCount = 0 + var aroundInsertExitCount = 0 + var didInsertCount = 0 + + var willUpdateCount = 0 + var aroundUpdateEnterCount = 0 + var aroundUpdateExitCount = 0 + var didUpdateCount = 0 + + var willSaveCount = 0 + var aroundSaveEnterCount = 0 + var aroundSaveExitCount = 0 + var didSaveCount = 0 + + var willDeleteCount = 0 + var aroundDeleteEnterCount = 0 + var aroundDeleteExitCount = 0 + var didDeleteCount = 0 +} + private struct MutablePersistableRecordCustomizedCountry : MutablePersistableRecord { var rowID: Int64? var isoCode: String var name: String - let willInsert: () -> Void - let willUpdate: () -> Void - let willSave: () -> Void - let willDelete: () -> Void - let willExists: () -> Void + let callbacks = Callbacks() static let databaseTableName = "countries" @@ -54,39 +84,225 @@ private struct MutablePersistableRecordCustomizedCountry : MutablePersistableRec container["name"] = name } - mutating func didInsert(with rowID: Int64, for column: String?) { - self.rowID = rowID + mutating func willInsert(_ db: Database) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willInsertCount += 1 } - mutating func insert(_ db: Database) throws { - willInsert() - try performInsert(db) + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundInsertEnterCount += 1 + _ = try insert() + callbacks.aroundInsertExitCount += 1 } - func update(_ db: Database, columns: Set) throws { - willUpdate() - try performUpdate(db, columns: columns) + mutating func didInsert(_ inserted: InsertionSuccess) { + callbacks.didInsertCount += 1 + rowID = inserted.rowID } - mutating func save(_ db: Database) throws { - willSave() - try performSave(db) + func willUpdate(_ db: Database, columns: Set) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willUpdateCount += 1 } - func delete(_ db: Database) throws -> Bool { - willDelete() - return try performDelete(db) + func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundUpdateEnterCount += 1 + _ = try update() + callbacks.aroundUpdateExitCount += 1 } - func exists(_ db: Database) throws -> Bool { - willExists() - return try performExists(db) + func didUpdate(_ updated: PersistenceSuccess) { + callbacks.didUpdateCount += 1 + } + + func willSave(_ db: Database) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willSaveCount += 1 + } + + func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundSaveEnterCount += 1 + _ = try save() + callbacks.aroundSaveExitCount += 1 + } + + func didSave(_ saved: PersistenceSuccess) { + callbacks.didSaveCount += 1 + } + + func willDelete(_ db: Database) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willDeleteCount += 1 + } + + func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundDeleteEnterCount += 1 + _ = try delete() + callbacks.aroundDeleteExitCount += 1 + } + + func didDelete(deleted: Bool) { + callbacks.didDeleteCount += 1 + } +} + +private struct PartialPlayer: Codable, MutablePersistableRecord, FetchableRecord { + static let databaseTableName = "player" + let callbacks = Callbacks() + var id: Int64? + var name: String + + enum CodingKeys: String, CodingKey { + case id, name + } + + mutating func willInsert(_ db: Database) throws { + callbacks.willInsertCount += 1 + } + + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + callbacks.aroundInsertEnterCount += 1 + _ = try insert() + callbacks.aroundInsertExitCount += 1 + } + + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID + callbacks.didInsertCount += 1 + } + + func willUpdate(_ db: Database, columns: Set) throws { + callbacks.willUpdateCount += 1 + } + + func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + callbacks.aroundUpdateEnterCount += 1 + _ = try update() + callbacks.aroundUpdateExitCount += 1 + } + + func didUpdate(_ updated: PersistenceSuccess) { + callbacks.didUpdateCount += 1 + } + + func willSave(_ db: Database) throws { + callbacks.willSaveCount += 1 + } + + func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + callbacks.aroundSaveEnterCount += 1 + _ = try save() + callbacks.aroundSaveExitCount += 1 + } + + func didSave(_ saved: PersistenceSuccess) { + callbacks.didSaveCount += 1 + } + + func willDelete(_ db: Database) throws { + callbacks.willDeleteCount += 1 + } + + func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + callbacks.aroundDeleteEnterCount += 1 + _ = try delete() + callbacks.aroundDeleteExitCount += 1 + } + + func didDelete(deleted: Bool) { + callbacks.didDeleteCount += 1 + } +} + +private struct FullPlayer: Codable, MutablePersistableRecord, FetchableRecord { + static let databaseTableName = "player" + var id: Int64? + var name: String + var score: Int + + enum CodingKeys: String, CodingKey { + case id, name, score + } + + let callbacks = Callbacks() + + mutating func willInsert(_ db: Database) throws { + callbacks.willInsertCount += 1 + } + + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + callbacks.aroundInsertEnterCount += 1 + _ = try insert() + callbacks.aroundInsertExitCount += 1 + } + + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID + callbacks.didInsertCount += 1 + } + + func willUpdate(_ db: Database, columns: Set) throws { + callbacks.willUpdateCount += 1 + } + + func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + callbacks.aroundUpdateEnterCount += 1 + _ = try update() + callbacks.aroundUpdateExitCount += 1 + } + + func didUpdate(_ updated: PersistenceSuccess) { + callbacks.didUpdateCount += 1 + } + + func willSave(_ db: Database) throws { + callbacks.willSaveCount += 1 + } + + func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + callbacks.aroundSaveEnterCount += 1 + _ = try save() + callbacks.aroundSaveExitCount += 1 + } + + func didSave(_ saved: PersistenceSuccess) { + callbacks.didSaveCount += 1 + } + + func willDelete(_ db: Database) throws { + callbacks.willDeleteCount += 1 + } + + func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + callbacks.aroundDeleteEnterCount += 1 + _ = try delete() + callbacks.aroundDeleteExitCount += 1 + } + + func didDelete(deleted: Bool) { + callbacks.didDeleteCount += 1 } } class MutablePersistableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("setUp") { db in try db.execute(sql: """ @@ -97,12 +313,15 @@ class MutablePersistableRecordTests: GRDBTestCase { CREATE TABLE countries ( isoCode TEXT NOT NULL PRIMARY KEY, name TEXT NOT NULL); + CREATE TABLE player( + id INTEGER PRIMARY KEY, + name NOT NULL UNIQUE, -- UNIQUE for upsert tests + score INTEGER NOT NULL DEFAULT 1000); """) } try migrator.migrate(dbWriter) } - // MARK: - MutablePersistableRecordPerson func testInsertMutablePersistableRecordPerson() throws { @@ -143,7 +362,7 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertTrue([ "UPDATE \"persons\" SET \"age\"=24, \"name\"='Craig' WHERE \"id\"=1", "UPDATE \"persons\" SET \"name\"='Craig', \"age\"=24 WHERE \"id\"=1" - ].contains(self.lastSQLQuery)) + ].contains(self.lastSQLQuery)) let rows = try Row.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) @@ -153,7 +372,7 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "Barbara") } } - + func testPartialUpdateMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -209,7 +428,7 @@ class MutablePersistableRecordTests: GRDBTestCase { } } } - + func testSaveMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -301,7 +520,7 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "Barbara") } } - + func testExistsMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -314,12 +533,12 @@ class MutablePersistableRecordTests: GRDBTestCase { } } - func testMutablePersistableRecordPersonDatabaseDictionary() { + func testMutablePersistableRecordPersonDatabaseDictionary() throws { let person = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) - let dict = person.databaseDictionary + let dict = try person.databaseDictionary XCTAssertEqual(dict, ["iD": DatabaseValue.null, "NAme": "Arthur".databaseValue, "aGe": 24.databaseValue]) } - + // MARK: - MutablePersistableRecordCountry func testInsertMutablePersistableRecordCountry() throws { @@ -367,7 +586,7 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + func testSaveMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -458,7 +677,7 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "United States") } } - + func testExistsMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -470,34 +689,37 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertFalse(try country.exists(db)) } } - - + // MARK: - MutablePersistableRecordCustomizedCountry func testInsertMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country.insert(db) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country.callbacks.willInsertCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country.callbacks.didInsertCount, 1) + + XCTAssertEqual(country.callbacks.willUpdateCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country.callbacks.didSaveCount, 1) + + XCTAssertEqual(country.callbacks.willDeleteCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country.callbacks.didDeleteCount, 0) let rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries") XCTAssertEqual(rows.count, 1) @@ -505,45 +727,44 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "France") } } - + func testUpdateMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country1 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.insert(db) var country2 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" try country1.update(db) XCTAssertEqual(self.lastSQLQuery, "UPDATE \"countries\" SET \"name\"='France Métropolitaine' WHERE \"isoCode\"='FR'") - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 1) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) + + XCTAssertEqual(country1.callbacks.willSaveCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(country1.callbacks.didSaveCount, 2) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) let rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries ORDER BY rowID") XCTAssertEqual(rows.count, 2) @@ -553,31 +774,70 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + + func testPersistenceErrorMutablePersistableRecordCustomizedCountry() throws { + let country = MutablePersistableRecordCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France") + + let dbQueue = try makeDatabaseQueue() + do { + try dbQueue.inDatabase { db in + try country.update(db) + } + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "countries", key: ["isoCode": "FR".databaseValue]) { } + + XCTAssertEqual(country.callbacks.willInsertCount, 0) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(country.callbacks.didInsertCount, 0) + + XCTAssertEqual(country.callbacks.willUpdateCount, 1) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) // last update has failed + XCTAssertEqual(country.callbacks.didUpdateCount, 0) // last update has failed + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 0) // last update has failed + XCTAssertEqual(country.callbacks.didSaveCount, 0) // last update has failed + + XCTAssertEqual(country.callbacks.willDeleteCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country.callbacks.didDeleteCount, 0) + } + func testSaveMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country1 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.save(db) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 1) - XCTAssertEqual(saveCount, 1) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 0) // last update has failed + XCTAssertEqual(country1.callbacks.didUpdateCount, 0) // last update has failed + + XCTAssertEqual(country1.callbacks.willSaveCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country1.callbacks.didSaveCount, 1) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) var rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries") XCTAssertEqual(rows.count, 1) @@ -587,22 +847,31 @@ class MutablePersistableRecordTests: GRDBTestCase { var country2 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.save(db) country1.name = "France Métropolitaine" try country1.save(db) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 2) - XCTAssertEqual(saveCount, 2) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 2) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) + + XCTAssertEqual(country1.callbacks.willSaveCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(country1.callbacks.didSaveCount, 2) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries ORDER BY rowID") XCTAssertEqual(rows.count, 2) @@ -614,11 +883,25 @@ class MutablePersistableRecordTests: GRDBTestCase { _ = try country1.delete(db) try country1.save(db) - XCTAssertEqual(insertCount, 2) - XCTAssertEqual(updateCount, 3) - XCTAssertEqual(saveCount, 3) - XCTAssertEqual(deleteCount, 1) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 2) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 2) + XCTAssertEqual(country1.callbacks.didInsertCount, 2) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 3) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 3) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) // last update has failed + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) // last update has failed + + XCTAssertEqual(country1.callbacks.willSaveCount, 3) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 3) + XCTAssertEqual(country1.callbacks.didSaveCount, 3) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 1) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(country1.callbacks.didDeleteCount, 1) rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries ORDER BY rowID") XCTAssertEqual(rows.count, 2) @@ -628,34 +911,19 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "France Métropolitaine") } } - + func testDeleteMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country1 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.insert(db) var country2 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.insert(db) var deleted = try country1.delete(db) @@ -663,11 +931,25 @@ class MutablePersistableRecordTests: GRDBTestCase { deleted = try country1.delete(db) XCTAssertFalse(deleted) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 2) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 0) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country1.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country1.callbacks.willSaveCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country1.callbacks.didSaveCount, 1) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 2) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 2) + XCTAssertEqual(country1.callbacks.didDeleteCount, 2) let rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries ORDER BY rowID") XCTAssertEqual(rows.count, 1) @@ -675,41 +957,61 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "United States") } } - + func testExistsMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country.insert(db) XCTAssertTrue(try country.exists(db)) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 1) + + XCTAssertEqual(country.callbacks.willInsertCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country.callbacks.didInsertCount, 1) + + XCTAssertEqual(country.callbacks.willUpdateCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country.callbacks.didSaveCount, 1) + + XCTAssertEqual(country.callbacks.willDeleteCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country.callbacks.didDeleteCount, 0) _ = try country.delete(db) XCTAssertFalse(try country.exists(db)) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 1) - XCTAssertEqual(existsCount, 2) + + XCTAssertEqual(country.callbacks.willInsertCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country.callbacks.didInsertCount, 1) + + XCTAssertEqual(country.callbacks.willUpdateCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country.callbacks.didSaveCount, 1) + + XCTAssertEqual(country.callbacks.willDeleteCount, 1) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(country.callbacks.didDeleteCount, 1) } } @@ -727,8 +1029,8 @@ class MutablePersistableRecordTests: GRDBTestCase { container["a"] = a } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -806,9 +1108,9 @@ class MutablePersistableRecordTests: GRDBTestCase { } func testGeneratedColumnsInsertIsAnError() throws { - #if !GRDBCUSTOMSQLITE +#if !GRDBCUSTOMSQLITE throw XCTSkip("Generated columns are not available") - #else +#else struct T: MutablePersistableRecord { func encode(to container: inout PersistenceContainer) { container["a"] = 1 @@ -828,13 +1130,13 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(error.sql!, "INSERT INTO \"t\" (\"a\", \"b\") VALUES (?,?)") } } - #endif +#endif } func testGeneratedColumnsUpdateIsAnError() throws { - #if !GRDBCUSTOMSQLITE +#if !GRDBCUSTOMSQLITE throw XCTSkip("Generated columns are not available") - #else +#else struct T: MutablePersistableRecord { func encode(to container: inout PersistenceContainer) { container["id"] = 1 @@ -853,6 +1155,1010 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(error.sql!, "UPDATE \"t\" SET \"a\"=? WHERE \"id\"=?") } } - #endif +#endif + } +} + +// MARK: - Insert and Fetch + +extension MutablePersistableRecordTests { + func test_insertAndFetch() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let player = FullPlayer(id: nil, name: "Arthur", score: 1000) + let insertedPlayer = try XCTUnwrap(player.insertAndFetch(db)) + XCTAssertEqual(insertedPlayer.id, 1) + XCTAssertEqual(insertedPlayer.name, "Arthur") + XCTAssertEqual(insertedPlayer.score, 1000) + } + } + + func test_insertAndFetch_as() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + sqlQueries.removeAll() + var partialPlayer = PartialPlayer(name: "Arthur") + let fullPlayer = try XCTUnwrap(partialPlayer.insertAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } + + func test_insertAndFetch_selection_fetch() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + sqlQueries.removeAll() + var partialPlayer = PartialPlayer(name: "Arthur") + let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement)! + } + + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } +} + +// MARK: - Save and Fetch + +extension MutablePersistableRecordTests { + func test_saveAndFetch() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let player = FullPlayer(id: nil, name: "Arthur", score: 1000) + let savedPlayer = try XCTUnwrap(player.saveAndFetch(db)) + XCTAssertEqual(savedPlayer.id, 1) + XCTAssertEqual(savedPlayer.name, "Arthur") + XCTAssertEqual(savedPlayer.score, 1000) + } + } + + func test_saveAndFetch_as() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + sqlQueries.removeAll() + var partialPlayer = PartialPlayer(name: "Arthur") + let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") }) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + + do { + var partialPlayer = PartialPlayer(id: 1, name: "Arthur") + try partialPlayer.delete(db) + sqlQueries.removeAll() + let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING * + """), sqlQueries.joined(separator: "\n")) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1) + } + + do { + sqlQueries.removeAll() + var partialPlayer = PartialPlayer(id: 1, name: "Arthur") + let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") }) + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } + + func test_saveAndFetch_selection_fetch() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + sqlQueries.removeAll() + var partialPlayer = PartialPlayer(name: "Arthur") + let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement) + } + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") }) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + + do { + var partialPlayer = PartialPlayer(id: 1, name: "Arthur") + try partialPlayer.delete(db) + sqlQueries.removeAll() + let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement) + } + + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1) + } + + do { + sqlQueries.removeAll() + var partialPlayer = PartialPlayer(id: 1, name: "Arthur") + let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement) + } + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") }) + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } +} + +// MARK: - Update and Fetch + +extension MutablePersistableRecordTests { + func test_updateAndFetch() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateAndFetch(db) + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + player.name = "Barbara" + + do { + let updatedPlayer = try XCTUnwrap(player.updateAndFetch(db)) + XCTAssertEqual(updatedPlayer.id, 1) + XCTAssertEqual(updatedPlayer.name, "Barbara") + XCTAssertEqual(updatedPlayer.score, 1000) + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + + func test_updateAndFetch_as() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateAndFetch(db, as: PartialPlayer.self) + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + player.name = "Barbara" + + do { + let updatedPlayer = try XCTUnwrap(player.updateAndFetch(db, as: PartialPlayer.self)) + XCTAssertEqual(updatedPlayer.id, 1) + XCTAssertEqual(updatedPlayer.name, "Barbara") + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + + func test_updateAndFetch_selection_fetch() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateAndFetch(db, selection: [AllColumns()]) { statement in + try Row.fetchOne(statement) + } + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + player.name = "Barbara" + player.score = 0 + + do { + let row = try player.updateAndFetch(db, selection: [AllColumns()]) { statement in + try Row.fetchOne(statement) + } + XCTAssertEqual(row, ["id": 1, "name": "Barbara", "score": 0]) + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + + func test_updateAndFetch_columns_selection_fetch() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateAndFetch(db, columns: [Column("score")], selection: [AllColumns()]) { statement in + try Row.fetchOne(statement) + } + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + player.name = "Barbara" + player.score = 0 + + do { + let row = try player.updateAndFetch(db, columns: [Column("score")], selection: [AllColumns()]) { statement in + try Row.fetchOne(statement) + } + XCTAssertEqual(row, ["id": 1, "name": "Arthur", "score": 0]) + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + + func test_updateChangesAndFetch_modify() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateChangesAndFetch(db) { + $0.name = "Barbara" + } + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + + do { + let updatedPlayer = try player.updateChangesAndFetch(db) { + $0.name = "Barbara" + } + XCTAssertNil(updatedPlayer) + } + + do { + let updatedPlayer = try XCTUnwrap(player.updateChangesAndFetch(db) { + $0.name = "Craig" + }) + XCTAssertEqual(updatedPlayer.id, 1) + XCTAssertEqual(updatedPlayer.name, "Craig") + XCTAssertEqual(updatedPlayer.score, 1000) + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + + func test_updateChangesAndFetch_as_modify() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateChangesAndFetch(db, as: PartialPlayer.self) { + $0.name = "Barbara" + } + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + + do { + let updatedPlayer = try player.updateChangesAndFetch(db, as: PartialPlayer.self) { + $0.name = "Barbara" + } + XCTAssertNil(updatedPlayer) + } + + do { + let updatedPlayer = try XCTUnwrap(player.updateChangesAndFetch(db, as: PartialPlayer.self) { + $0.name = "Craig" + }) + XCTAssertEqual(updatedPlayer.id, 1) + XCTAssertEqual(updatedPlayer.name, "Craig") + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + + func test_updateChangesAndFetch_selection_fetch_modify() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateChangesAndFetch( + db, selection: [AllColumns()], + fetch: { statement in try Row.fetchOne(statement) }, + modify: { $0.name = "Barbara" }) + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + + do { + let updatedRow = try player.updateChangesAndFetch( + db, selection: [AllColumns()], + fetch: { statement in try Row.fetchOne(statement) }, + modify: { $0.name = "Barbara" }) + XCTAssertNil(updatedRow) + } + + do { + let updatedRow = try player.updateChangesAndFetch( + db, selection: [AllColumns()], + fetch: { statement in try Row.fetchOne(statement) }, + modify: { $0.name = "Craig" }) + XCTAssertEqual(updatedRow, ["id": 1, "name": "Craig", "score": 1000]) + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } +} + +// MARK: - Upsert + +extension MutablePersistableRecordTests { + func test_upsert() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("UPSERT is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("UPSERT is not available") + } +#endif + + try makeDatabaseQueue().write { db in + do { + var player = FullPlayer(name: "Arthur", score: 1000) + try player.upsert(db) + + // Test SQL + XCTAssertEqual(lastSQLQuery, """ + INSERT INTO "player" ("id", "name", "score") \ + VALUES (NULL,'Arthur',1000) \ + ON CONFLICT DO UPDATE SET "name"='Arthur', "score"=1000 \ + RETURNING "rowid" + """) + + // Test database state + let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) + XCTAssertEqual(rows, [ + ["id": 1, "name": "Arthur", "score":1000], + ]) + + // Test didSave callback + XCTAssertEqual(player.id, 1) + + // Test other callbacks + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 0) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(player.callbacks.didUpdateCount, 0) + + XCTAssertEqual(player.callbacks.willSaveCount, 1) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(player.callbacks.didSaveCount, 1) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + + // Test conflict on name + do { + // Set the last inserted row id to some arbitrary value + _ = try FullPlayer(id: 42, name: "Barbara", score: 0).inserted(db) + XCTAssertNotEqual(db.lastInsertedRowID, 1) + + var player = FullPlayer(name: "Arthur", score: 100) + try player.upsert(db) + + // Test database state + let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) + XCTAssertEqual(rows, [ + ["id": 1, "name": "Arthur", "score":100], + ["id": 42, "name": "Barbara", "score":0], + ]) + + // Test didSave callback + XCTAssertEqual(player.id, 1) + } + + // Test conflict on id + do { + var player = FullPlayer(id: 1, name: "Craig", score: 500) + try player.upsert(db) + + // Test database state + let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) + XCTAssertEqual(rows, [ + ["id": 1, "name": "Craig", "score":500], + ["id": 42, "name": "Barbara", "score":0], + ]) + + // Test didSave callback + XCTAssertEqual(player.id, 1) + } + + // Test conflict on both id and name (same row) + do { + var player = FullPlayer(id: 1, name: "Craig", score: 200) + try player.upsert(db) + + // Test database state + let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) + XCTAssertEqual(rows, [ + ["id": 1, "name": "Craig", "score":200], + ["id": 42, "name": "Barbara", "score":0], + ]) + + // Test didSave callback + XCTAssertEqual(player.id, 1) + } + + // Test conflict on both id and name (different rows) + do { + var player = FullPlayer(id: 1, name: "Barbara", score: 300) + + do { + try player.upsert(db) + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) + XCTAssertEqual(error.message, "UNIQUE constraint failed: player.name") + XCTAssertEqual(error.sql!, """ + INSERT INTO "player" ("id", "name", "score") \ + VALUES (?,?,?) \ + ON CONFLICT DO UPDATE SET "name"=?, "score"=? \ + RETURNING "rowid" + """) + } + + // Test callbacks + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(player.callbacks.didInsertCount, 0) + + XCTAssertEqual(player.callbacks.willUpdateCount, 0) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(player.callbacks.didUpdateCount, 0) + + XCTAssertEqual(player.callbacks.willSaveCount, 1) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 0) + XCTAssertEqual(player.callbacks.didSaveCount, 0) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + } + + func test_upsertAndFetch_as() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("UPSERT is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("UPSERT is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + sqlQueries.removeAll() + var partialPlayer = PartialPlayer(name: "Arthur") + let fullPlayer = try partialPlayer.upsertAndFetch(db, as: FullPlayer.self) + + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") \ + VALUES (NULL,'Arthur') \ + ON CONFLICT DO UPDATE SET "name"='Arthur' \ + RETURNING *, "rowid" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } } } diff --git a/Tests/GRDBTests/PersistableRecordTests.swift b/Tests/GRDBTests/PersistableRecordTests.swift index ff7f15316..65536d49e 100644 --- a/Tests/GRDBTests/PersistableRecordTests.swift +++ b/Tests/GRDBTests/PersistableRecordTests.swift @@ -33,8 +33,8 @@ private class PersistableRecordPersonClass : PersistableRecord { container["Age"] = age } - func didInsert(with rowID: Int64, for column: String?) { - self.id = rowID + func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -50,14 +50,32 @@ private struct PersistableRecordCountry : PersistableRecord { } } +private class Callbacks { + var willInsertCount = 0 + var aroundInsertEnterCount = 0 + var aroundInsertExitCount = 0 + var didInsertCount = 0 + + var willUpdateCount = 0 + var aroundUpdateEnterCount = 0 + var aroundUpdateExitCount = 0 + var didUpdateCount = 0 + + var willSaveCount = 0 + var aroundSaveEnterCount = 0 + var aroundSaveExitCount = 0 + var didSaveCount = 0 + + var willDeleteCount = 0 + var aroundDeleteEnterCount = 0 + var aroundDeleteExitCount = 0 + var didDeleteCount = 0 +} + private struct PersistableRecordCustomizedCountry : PersistableRecord { var isoCode: String var name: String - let willInsert: () -> Void - let willUpdate: () -> Void - let willSave: () -> Void - let willDelete: () -> Void - let willExists: () -> Void + let callbacks = Callbacks() static let databaseTableName = "countries" @@ -66,29 +84,80 @@ private struct PersistableRecordCustomizedCountry : PersistableRecord { container["name"] = name } - func insert(_ db: Database) throws { - willInsert() - try performInsert(db) + func willInsert(_ db: Database) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willInsertCount += 1 } - func update(_ db: Database, columns: Set) throws { - willUpdate() - try performUpdate(db, columns: columns) + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundInsertEnterCount += 1 + _ = try insert() + callbacks.aroundInsertExitCount += 1 } - func save(_ db: Database) throws { - willSave() - try performSave(db) + func didInsert(_ inserted: InsertionSuccess) { + callbacks.didInsertCount += 1 } - func delete(_ db: Database) throws -> Bool { - willDelete() - return try performDelete(db) + func willUpdate(_ db: Database, columns: Set) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willUpdateCount += 1 } - func exists(_ db: Database) throws -> Bool { - willExists() - return try performExists(db) + func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundUpdateEnterCount += 1 + _ = try update() + callbacks.aroundUpdateExitCount += 1 + } + + func didUpdate(_ updated: PersistenceSuccess) { + callbacks.didUpdateCount += 1 + } + + func willSave(_ db: Database) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willSaveCount += 1 + } + + func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundSaveEnterCount += 1 + _ = try save() + callbacks.aroundSaveExitCount += 1 + } + + func didSave(_ saved: PersistenceSuccess) { + callbacks.didSaveCount += 1 + } + + func willDelete(_ db: Database) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willDeleteCount += 1 + } + + func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundDeleteEnterCount += 1 + _ = try delete() + callbacks.aroundDeleteExitCount += 1 + } + + func didDelete(deleted: Bool) { + callbacks.didDeleteCount += 1 } } @@ -104,9 +173,145 @@ private struct Citizenship : PersistableRecord { } } +private struct PartialPlayer: Codable, PersistableRecord, FetchableRecord { + static let databaseTableName = "player" + let callbacks = Callbacks() + var id: Int64? + var name: String + + enum CodingKeys: String, CodingKey { + case id, name + } + + func willInsert(_ db: Database) throws { + callbacks.willInsertCount += 1 + } + + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + callbacks.aroundInsertEnterCount += 1 + _ = try insert() + callbacks.aroundInsertExitCount += 1 + } + + func didInsert(_ inserted: InsertionSuccess) { + callbacks.didInsertCount += 1 + } + + func willUpdate(_ db: Database, columns: Set) throws { + callbacks.willUpdateCount += 1 + } + + func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + callbacks.aroundUpdateEnterCount += 1 + _ = try update() + callbacks.aroundUpdateExitCount += 1 + } + + func didUpdate(_ updated: PersistenceSuccess) { + callbacks.didUpdateCount += 1 + } + + func willSave(_ db: Database) throws { + callbacks.willSaveCount += 1 + } + + func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + callbacks.aroundSaveEnterCount += 1 + _ = try save() + callbacks.aroundSaveExitCount += 1 + } + + func didSave(_ saved: PersistenceSuccess) { + callbacks.didSaveCount += 1 + } + + func willDelete(_ db: Database) throws { + callbacks.willDeleteCount += 1 + } + + func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + callbacks.aroundDeleteEnterCount += 1 + _ = try delete() + callbacks.aroundDeleteExitCount += 1 + } + + func didDelete(deleted: Bool) { + callbacks.didDeleteCount += 1 + } +} + +private struct FullPlayer: Codable, PersistableRecord, FetchableRecord { + static let databaseTableName = "player" + var id: Int64? + var name: String + var score: Int + + enum CodingKeys: String, CodingKey { + case id, name, score + } + + let callbacks = Callbacks() + + func willInsert(_ db: Database) throws { + callbacks.willInsertCount += 1 + } + + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + callbacks.aroundInsertEnterCount += 1 + _ = try insert() + callbacks.aroundInsertExitCount += 1 + } + + func didInsert(_ inserted: InsertionSuccess) { + callbacks.didInsertCount += 1 + } + + func willUpdate(_ db: Database, columns: Set) throws { + callbacks.willUpdateCount += 1 + } + + func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + callbacks.aroundUpdateEnterCount += 1 + _ = try update() + callbacks.aroundUpdateExitCount += 1 + } + + func didUpdate(_ updated: PersistenceSuccess) { + callbacks.didUpdateCount += 1 + } + + func willSave(_ db: Database) throws { + callbacks.willSaveCount += 1 + } + + func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + callbacks.aroundSaveEnterCount += 1 + _ = try save() + callbacks.aroundSaveExitCount += 1 + } + + func didSave(_ saved: PersistenceSuccess) { + callbacks.didSaveCount += 1 + } + + func willDelete(_ db: Database) throws { + callbacks.willDeleteCount += 1 + } + + func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + callbacks.aroundDeleteEnterCount += 1 + _ = try delete() + callbacks.aroundDeleteExitCount += 1 + } + + func didDelete(deleted: Bool) { + callbacks.didDeleteCount += 1 + } +} + class PersistableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("setUp") { db in try db.execute(sql: """ @@ -120,12 +325,15 @@ class PersistableRecordTests: GRDBTestCase { CREATE TABLE citizenships ( countryIsoCode TEXT NOT NULL REFERENCES countries(isoCode), personID INTEGER NOT NULL REFERENCES persons(id)); + CREATE TABLE player( + id INTEGER PRIMARY KEY, + name NOT NULL UNIQUE, -- UNIQUE for upsert tests + score INTEGER NOT NULL DEFAULT 1000); """) } try migrator.migrate(dbWriter) } - // MARK: - PersistableRecordPerson func testInsertPersistableRecordPerson() throws { @@ -139,7 +347,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "Arthur") } } - + func testSavePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -151,8 +359,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "Arthur") } } - - + // MARK: - PersistableRecordPersonClass func testInsertPersistableRecordPersonClass() throws { @@ -167,7 +374,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "Arthur") } } - + func testUpdatePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -181,7 +388,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertTrue([ "UPDATE \"persons\" SET \"age\"=42, \"name\"='Craig' WHERE \"id\"=1", "UPDATE \"persons\" SET \"name\"='Craig', \"age\"=42 WHERE \"id\"=1" - ].contains(self.lastSQLQuery)) + ].contains(self.lastSQLQuery)) let rows = try Row.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) @@ -191,7 +398,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "Barbara") } } - + func testPartialUpdatePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -247,7 +454,7 @@ class PersistableRecordTests: GRDBTestCase { } } } - + func testSavePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -283,7 +490,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "Barbara") } } - + func testDeletePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -303,7 +510,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "Barbara") } } - + func testExistsPersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -315,8 +522,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertFalse(try person.exists(db)) } } - - + // MARK: - PersistableRecordCountry func testInsertPersistableRecordCountry() throws { @@ -331,7 +537,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "France") } } - + func testUpdatePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -352,7 +558,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + func testPartialUpdatePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -388,7 +594,7 @@ class PersistableRecordTests: GRDBTestCase { } } } - + func testSavePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -424,7 +630,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + func testDeletePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -444,7 +650,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "United States") } } - + func testExistsPersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -456,33 +662,36 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertFalse(try country.exists(db)) } } - - + // MARK: - PersistableRecordCustomizedCountry func testInsertPersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 let country = PersistableRecordCustomizedCountry( isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country.insert(db) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country.callbacks.willInsertCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country.callbacks.didInsertCount, 1) + + XCTAssertEqual(country.callbacks.willUpdateCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country.callbacks.didSaveCount, 1) + + XCTAssertEqual(country.callbacks.willDeleteCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country.callbacks.didDeleteCount, 0) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries") XCTAssertEqual(rows.count, 1) @@ -490,43 +699,42 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "France") } } - + func testUpdatePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.insert(db) let country2 = PersistableRecordCustomizedCountry( isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" try country1.update(db) XCTAssertEqual(self.lastSQLQuery, "UPDATE \"countries\" SET \"name\"='France Métropolitaine' WHERE \"isoCode\"='FR'") - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 1) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) + + XCTAssertEqual(country1.callbacks.willSaveCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(country1.callbacks.didSaveCount, 2) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) @@ -536,43 +744,76 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + + func testPersistenceErrorPersistableRecordCustomizedCountry() throws { + let country = PersistableRecordCustomizedCountry( + isoCode: "FR", + name: "France") + + let dbQueue = try makeDatabaseQueue() + do { + try dbQueue.inDatabase { db in + try country.update(db) + } + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "countries", key: ["isoCode": "FR".databaseValue]) { } + + XCTAssertEqual(country.callbacks.willInsertCount, 0) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(country.callbacks.didInsertCount, 0) + + XCTAssertEqual(country.callbacks.willUpdateCount, 1) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) // last update has failed + XCTAssertEqual(country.callbacks.didUpdateCount, 0) // last update has failed + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 0) // last update has failed + XCTAssertEqual(country.callbacks.didSaveCount, 0) // last update has failed + + XCTAssertEqual(country.callbacks.willDeleteCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country.callbacks.didDeleteCount, 0) + } + func testPartialUpdatePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.insert(db) let country2 = PersistableRecordCustomizedCountry( isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" try country1.update(db, columns: ["name"]) XCTAssertEqual(self.lastSQLQuery, "UPDATE \"countries\" SET \"name\"='France Métropolitaine' WHERE \"isoCode\"='FR'") - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 1) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) + + XCTAssertEqual(country1.callbacks.willSaveCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(country1.callbacks.didSaveCount, 2) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) @@ -582,30 +823,34 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + func testSavePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.save(db) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 1) - XCTAssertEqual(saveCount, 1) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 0) // last update has failed + XCTAssertEqual(country1.callbacks.didUpdateCount, 0) // last update has failed + + XCTAssertEqual(country1.callbacks.willSaveCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country1.callbacks.didSaveCount, 1) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) var rows = try Row.fetchAll(db, sql: "SELECT * FROM countries") XCTAssertEqual(rows.count, 1) @@ -614,22 +859,31 @@ class PersistableRecordTests: GRDBTestCase { let country2 = PersistableRecordCustomizedCountry( isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.save(db) country1.name = "France Métropolitaine" try country1.save(db) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 2) - XCTAssertEqual(saveCount, 2) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 2) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) + + XCTAssertEqual(country1.callbacks.willSaveCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(country1.callbacks.didSaveCount, 2) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) @@ -641,11 +895,25 @@ class PersistableRecordTests: GRDBTestCase { _ = try country1.delete(db) try country1.save(db) - XCTAssertEqual(insertCount, 2) - XCTAssertEqual(updateCount, 3) - XCTAssertEqual(saveCount, 3) - XCTAssertEqual(deleteCount, 1) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 2) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 2) + XCTAssertEqual(country1.callbacks.didInsertCount, 2) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 3) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 3) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) // last update has failed + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) // last update has failed + + XCTAssertEqual(country1.callbacks.willSaveCount, 3) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 3) + XCTAssertEqual(country1.callbacks.didSaveCount, 3) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 1) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(country1.callbacks.didDeleteCount, 1) rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) @@ -655,32 +923,17 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + func testDeletePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 let country1 = PersistableRecordCustomizedCountry( isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.insert(db) let country2 = PersistableRecordCustomizedCountry( isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.insert(db) var deleted = try country1.delete(db) @@ -688,11 +941,25 @@ class PersistableRecordTests: GRDBTestCase { deleted = try country1.delete(db) XCTAssertFalse(deleted) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 2) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 0) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country1.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country1.callbacks.willSaveCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country1.callbacks.didSaveCount, 1) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 2) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 2) + XCTAssertEqual(country1.callbacks.didDeleteCount, 2) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 1) @@ -700,46 +967,65 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "United States") } } - + func testExistsPersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 let country = PersistableRecordCustomizedCountry( isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country.insert(db) XCTAssertTrue(try country.exists(db)) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 1) + + XCTAssertEqual(country.callbacks.willInsertCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country.callbacks.didInsertCount, 1) + + XCTAssertEqual(country.callbacks.willUpdateCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country.callbacks.didSaveCount, 1) + + XCTAssertEqual(country.callbacks.willDeleteCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country.callbacks.didDeleteCount, 0) _ = try country.delete(db) XCTAssertFalse(try country.exists(db)) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 1) - XCTAssertEqual(existsCount, 2) + + XCTAssertEqual(country.callbacks.willInsertCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country.callbacks.didInsertCount, 1) + + XCTAssertEqual(country.callbacks.willUpdateCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country.callbacks.didSaveCount, 1) + + XCTAssertEqual(country.callbacks.willDeleteCount, 1) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(country.callbacks.didDeleteCount, 1) } } - - + // MARK: - Errors - + func testInsertErrorDoesNotPreventSubsequentInserts() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -776,7 +1062,7 @@ extension PersistableRecordTests { try db.create(table: "t1") { t in t.column("nested", .text) } - + let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") let value = StructWithNestedType(nested: nested) try value.insert(db) @@ -844,7 +1130,7 @@ extension PersistableRecordTests { try db.create(table: "t1") { t in t.column("nested", .text) } - + let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") let value = StructWithNestedType(nested: [nested, nested]) try value.insert(db) @@ -915,13 +1201,13 @@ extension PersistableRecordTests { try db.create(table: "t1") { t in t.column("nested", .text) } - + let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") let value = StructWithNestedType(nested: nested) try value.insert(db) let dbValue = try DatabaseValue.fetchOne(db, sql: "SELECT nested FROM t1")! - + // Encodable has a default implementation which encodes a model to JSON as String. // We expect here JSON in the form of a String XCTAssert(dbValue.storage.value is String) @@ -935,7 +1221,7 @@ extension PersistableRecordTests { XCTFail(error.localizedDescription) } } else { - XCTFail("Failed to convert " + string) + XCTFail("Failed to convert " + string) } } } @@ -1036,3 +1322,548 @@ extension PersistableRecordTests { } } + +// MARK: - Insert and Fetch + +extension PersistableRecordTests { + func test_insertAndFetch_as() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + sqlQueries.removeAll() + let partialPlayer = PartialPlayer(name: "Arthur") + let fullPlayer = try XCTUnwrap(partialPlayer.insertAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } + + func test_insertAndFetch_selection_fetch() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + sqlQueries.removeAll() + let partialPlayer = PartialPlayer(name: "Arthur") + let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement)! + } + + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } +} + +// MARK: - Save and Fetch + +extension PersistableRecordTests { + func test_saveAndFetch_as() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + sqlQueries.removeAll() + let partialPlayer = PartialPlayer(name: "Arthur") + let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") }) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + + do { + let partialPlayer = PartialPlayer(id: 1, name: "Arthur") + try partialPlayer.delete(db) + sqlQueries.removeAll() + let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING * + """), sqlQueries.joined(separator: "\n")) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1) + } + + do { + sqlQueries.removeAll() + let partialPlayer = PartialPlayer(id: 1, name: "Arthur") + let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") }) + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } + + func test_saveAndFetch_selection_fetch() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + sqlQueries.removeAll() + let partialPlayer = PartialPlayer(name: "Arthur") + let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement) + } + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") }) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + + do { + let partialPlayer = PartialPlayer(id: 1, name: "Arthur") + try partialPlayer.delete(db) + sqlQueries.removeAll() + let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement) + } + + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1) + } + + do { + sqlQueries.removeAll() + let partialPlayer = PartialPlayer(id: 1, name: "Arthur") + let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement) + } + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") }) + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } +} + +// MARK: - Upsert + +extension PersistableRecordTests { + func test_upsert() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("UPSERT is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("UPSERT is not available") + } +#endif + + try makeDatabaseQueue().write { db in + do { + let player = FullPlayer(name: "Arthur", score: 1000) + try player.upsert(db) + + // Test SQL + XCTAssertEqual(lastSQLQuery, """ + INSERT INTO "player" ("id", "name", "score") \ + VALUES (NULL,'Arthur',1000) \ + ON CONFLICT DO UPDATE SET "name"='Arthur', "score"=1000 \ + RETURNING "rowid" + """) + + // Test database state + let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) + XCTAssertEqual(rows, [ + ["id": 1, "name": "Arthur", "score":1000], + ]) + + // Test callbacks + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 0) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(player.callbacks.didUpdateCount, 0) + + XCTAssertEqual(player.callbacks.willSaveCount, 1) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(player.callbacks.didSaveCount, 1) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + + // Test conflict on name + do { + // Set the last inserted row id to some arbitrary value + _ = try FullPlayer(id: 42, name: "Barbara", score: 0).inserted(db) + XCTAssertNotEqual(db.lastInsertedRowID, 1) + + let player = FullPlayer(name: "Arthur", score: 100) + try player.upsert(db) + + // Test database state + let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) + XCTAssertEqual(rows, [ + ["id": 1, "name": "Arthur", "score":100], + ["id": 42, "name": "Barbara", "score":0], + ]) + } + + // Test conflict on id + do { + let player = FullPlayer(id: 1, name: "Craig", score: 500) + try player.upsert(db) + + // Test database state + let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) + XCTAssertEqual(rows, [ + ["id": 1, "name": "Craig", "score":500], + ["id": 42, "name": "Barbara", "score":0], + ]) + } + + // Test conflict on both id and name (same row) + do { + let player = FullPlayer(id: 1, name: "Craig", score: 200) + try player.upsert(db) + + // Test database state + let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) + XCTAssertEqual(rows, [ + ["id": 1, "name": "Craig", "score":200], + ["id": 42, "name": "Barbara", "score":0], + ]) + } + + // Test conflict on both id and name (different rows) + do { + let player = FullPlayer(id: 1, name: "Barbara", score: 300) + + do { + try player.upsert(db) + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) + XCTAssertEqual(error.message, "UNIQUE constraint failed: player.name") + XCTAssertEqual(error.sql!, """ + INSERT INTO "player" ("id", "name", "score") \ + VALUES (?,?,?) \ + ON CONFLICT DO UPDATE SET "name"=?, "score"=? \ + RETURNING "rowid" + """) + } + + // Test callbacks + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(player.callbacks.didInsertCount, 0) + + XCTAssertEqual(player.callbacks.willUpdateCount, 0) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(player.callbacks.didUpdateCount, 0) + + XCTAssertEqual(player.callbacks.willSaveCount, 1) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 0) + XCTAssertEqual(player.callbacks.didSaveCount, 0) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + } + + func test_upsertAndFetch_as() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("UPSERT is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("UPSERT is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + sqlQueries.removeAll() + let partialPlayer = PartialPlayer(name: "Arthur") + let fullPlayer = try partialPlayer.upsertAndFetch(db, as: FullPlayer.self) + + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") \ + VALUES (NULL,'Arthur') \ + ON CONFLICT DO UPDATE SET "name"='Arthur' \ + RETURNING *, "rowid" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } +} diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 7617a1958..7097c6fe1 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -32,7 +32,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { } } - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute(sql: """ @@ -1129,17 +1129,15 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { sql(dbQueue, tableRequest.select(Col.name.uppercased)), "SELECT swiftUppercaseString(\"name\") FROM \"readers\"") - if #available(OSX 10.11, *) { - XCTAssertEqual( - sql(dbQueue, tableRequest.select(Col.name.localizedCapitalized)), - "SELECT swiftLocalizedCapitalizedString(\"name\") FROM \"readers\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.select(Col.name.localizedLowercased)), - "SELECT swiftLocalizedLowercaseString(\"name\") FROM \"readers\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.select(Col.name.localizedUppercased)), - "SELECT swiftLocalizedUppercaseString(\"name\") FROM \"readers\"") - } + XCTAssertEqual( + sql(dbQueue, tableRequest.select(Col.name.localizedCapitalized)), + "SELECT swiftLocalizedCapitalizedString(\"name\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(Col.name.localizedLowercased)), + "SELECT swiftLocalizedLowercaseString(\"name\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(Col.name.localizedUppercased)), + "SELECT swiftLocalizedUppercaseString(\"name\") FROM \"readers\"") } diff --git a/Tests/GRDBTests/QueryInterfacePromiseTests.swift b/Tests/GRDBTests/QueryInterfacePromiseTests.swift index 389dfde09..1cd1c14de 100644 --- a/Tests/GRDBTests/QueryInterfacePromiseTests.swift +++ b/Tests/GRDBTests/QueryInterfacePromiseTests.swift @@ -10,7 +10,7 @@ private struct NotARecord { } // Here we test that filter(key:), orderByPrimaryKey(), and groupByPrimaryKey() // don't forget their table when the request type is changed. class QueryInterfacePromiseTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "node") { t in t.autoIncrementedPrimaryKey("id") diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index 1be985ede..fa3c35f1c 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -26,7 +26,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { } } - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift b/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift index 6d2931bf9..7dfdfb171 100644 --- a/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift @@ -25,28 +25,42 @@ private enum Grape : String { case riesling } +private enum FastGrape : String { + case chardonnay + case merlot + case riesling + } + private struct Wrapper: RawRepresentable { var rawValue: RawValue } -extension Color32 : SQLExpressible { } -extension Color64 : SQLExpressible { } -extension Color : SQLExpressible { } -extension Grape : SQLExpressible { } -extension Wrapper: SQLOrderingTerm where RawValue: SQLOrderingTerm { } -extension Wrapper: SQLSelectable where RawValue: SQLSelectable { } -extension Wrapper: SQLExpressible where RawValue: SQLExpressible { } -extension Wrapper: StatementBinding where RawValue: StatementBinding { } +private struct FastWrapper: RawRepresentable { + var rawValue: RawValue +} + extension Color32 : DatabaseValueConvertible { } extension Color64 : DatabaseValueConvertible { } extension Color : DatabaseValueConvertible { } extension Grape : DatabaseValueConvertible { } +extension FastGrape : DatabaseValueConvertible, StatementColumnConvertible { } + +extension Wrapper: SQLExpressible where RawValue: SQLExpressible { } +extension Wrapper: StatementBinding where RawValue: StatementBinding { } extension Wrapper: DatabaseValueConvertible where RawValue: DatabaseValueConvertible { } +extension FastWrapper: SQLSelectable where RawValue: SQLSelectable { } +extension FastWrapper: SQLOrderingTerm where RawValue: SQLOrderingTerm { } +extension FastWrapper: SQLSpecificExpressible where RawValue: SQLSpecificExpressible { } +extension FastWrapper: SQLExpressible where RawValue: SQLExpressible { } +extension FastWrapper: StatementBinding where RawValue: StatementBinding { } +extension FastWrapper: DatabaseValueConvertible where RawValue: DatabaseValueConvertible { } +extension FastWrapper: StatementColumnConvertible where RawValue: StatementColumnConvertible { } + class RawRepresentableDatabaseValueConvertibleTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: "CREATE TABLE wines (grape TEXT, color INTEGER)") @@ -85,7 +99,7 @@ class RawRepresentableDatabaseValueConvertibleTests: GRDBTestCase { return .rollback } } - + func testColor64() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in @@ -117,7 +131,7 @@ class RawRepresentableDatabaseValueConvertibleTests: GRDBTestCase { return .rollback } } - + func testColor() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in @@ -149,7 +163,7 @@ class RawRepresentableDatabaseValueConvertibleTests: GRDBTestCase { return .rollback } } - + func testGrape() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in @@ -181,4 +195,100 @@ class RawRepresentableDatabaseValueConvertibleTests: GRDBTestCase { return .rollback } } + + func testFastGrape() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inTransaction { db in + + do { + for grape in [FastGrape.chardonnay, FastGrape.merlot, FastGrape.riesling] { + try db.execute(sql: "INSERT INTO wines (grape) VALUES (?)", arguments: [grape]) + } + try db.execute(sql: "INSERT INTO wines (grape) VALUES (NULL)") + } + + do { + let rows = try Row.fetchAll(db, sql: "SELECT grape FROM wines ORDER BY grape") + let grapes = rows.map { $0[0] as FastGrape? } + XCTAssertTrue(grapes[0] == nil) + XCTAssertEqual(grapes[1]!, FastGrape.chardonnay) + XCTAssertEqual(grapes[2]!, FastGrape.merlot) + XCTAssertEqual(grapes[3]!, FastGrape.riesling) + } + + do { + let grapes = try Optional.fetchAll(db, sql: "SELECT grape FROM wines ORDER BY grape") + XCTAssertTrue(grapes[0] == nil) + XCTAssertEqual(grapes[1]!, FastGrape.chardonnay) + XCTAssertEqual(grapes[2]!, FastGrape.merlot) + XCTAssertEqual(grapes[3]!, FastGrape.riesling) + } + + return .rollback + } + } + + func testWrapper() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inTransaction { db in + + do { + for color in [Wrapper(rawValue: 0), Wrapper(rawValue: 1), Wrapper(rawValue: 2)] { + try db.execute(sql: "INSERT INTO wines (color) VALUES (?)", arguments: [color]) + } + try db.execute(sql: "INSERT INTO wines (color) VALUES (NULL)") + } + + do { + let rows = try Row.fetchAll(db, sql: "SELECT color FROM wines ORDER BY color") + let values = rows.map { $0[0] as Wrapper? } + XCTAssertTrue(values[0] == nil) + XCTAssertEqual(values[1]!.rawValue, 0) + XCTAssertEqual(values[2]!.rawValue, 1) + XCTAssertEqual(values[3]!.rawValue, 2) + } + + do { + let values = try Optional>.fetchAll(db, sql: "SELECT color FROM wines ORDER BY color") + XCTAssertTrue(values[0] == nil) + XCTAssertEqual(values[1]!.rawValue, 0) + XCTAssertEqual(values[2]!.rawValue, 1) + XCTAssertEqual(values[3]!.rawValue, 2) + } + + return .rollback + } + } + + func testFastWrapper() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inTransaction { db in + + do { + for color in [FastWrapper(rawValue: 0), FastWrapper(rawValue: 1), FastWrapper(rawValue: 2)] { + try db.execute(sql: "INSERT INTO wines (color) VALUES (?)", arguments: [color]) + } + try db.execute(sql: "INSERT INTO wines (color) VALUES (NULL)") + } + + do { + let rows = try Row.fetchAll(db, sql: "SELECT color FROM wines ORDER BY color") + let values = rows.map { $0[0] as FastWrapper? } + XCTAssertTrue(values[0] == nil) + XCTAssertEqual(values[1]!.rawValue, 0) + XCTAssertEqual(values[2]!.rawValue, 1) + XCTAssertEqual(values[3]!.rawValue, 2) + } + + do { + let values = try Optional>.fetchAll(db, sql: "SELECT color FROM wines ORDER BY color") + XCTAssertTrue(values[0] == nil) + XCTAssertEqual(values[1]!.rawValue, 0) + XCTAssertEqual(values[2]!.rawValue, 1) + XCTAssertEqual(values[3]!.rawValue, 2) + } + + return .rollback + } + } } diff --git a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift index f3ca0b73b..86a610e17 100644 --- a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift @@ -13,32 +13,33 @@ private class Reader : Record { super.init() } - required init(row: Row){ + required init(row: Row) throws { self.id = row["id"] self.name = row["name"] self.age = row["age"] - super.init(row: row) + try super.init(row: row) } override class var databaseTableName: String { "readers" } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["id"] = id container["name"] = name container["age"] = age } - override func didInsert(with rowID: Int64, for column: String?) { - id = rowID + override func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + id = inserted.rowID } } class RecordQueryInterfaceRequestTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/RecordCopyTests.swift b/Tests/GRDBTests/RecordCopyTests.swift deleted file mode 100644 index 77a1957c4..000000000 --- a/Tests/GRDBTests/RecordCopyTests.swift +++ /dev/null @@ -1,46 +0,0 @@ -import XCTest -import GRDB - -private class Person : Record { - var id: Int64! - var name: String! - var age: Int? - var creationDate: Date - - init(id: Int64?, name: String?, age: Int?, creationDate: Date) { - self.id = id - self.name = name - self.age = age - self.creationDate = creationDate - super.init() - } - - // Record - - required init(row: Row) { - id = row["id"] - age = row["age"] - name = row["name"] - creationDate = row["creationDate"] - super.init(row: row) - } - - override func encode(to container: inout PersistenceContainer) { - container["id"] = id - container["name"] = name - container["age"] = age - container["creationDate"] = creationDate - } -} - -class RecordCopyTests: GRDBTestCase { - - func testRecordCopy() { - let person1 = Person(id: 123, name: "Arthur", age: 41, creationDate: Date()) - let person2 = person1.copy() - XCTAssertTrue(person2.id == person1.id) - XCTAssertTrue(person2.name == person1.name) - XCTAssertTrue(person2.age == person1.age) - XCTAssertTrue(abs(person2.creationDate.timeIntervalSince(person1.creationDate)) < 1e-3) - } -} diff --git a/Tests/GRDBTests/RecordEditedTests.swift b/Tests/GRDBTests/RecordEditedTests.swift index 535e4bafc..d74431534 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -31,32 +31,31 @@ private class Person : Record { "persons" } - required init(row: Row) { + required init(row: Row) throws { id = row["id"] age = row["age"] name = row["name"] creationDate = row["creationDate"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["id"] = id container["name"] = name container["age"] = age container["creationDate"] = creationDate } - override func insert(_ db: Database) throws { - // This is implicitly tested with the NOT NULL constraint on creationDate + override func willInsert(_ db: Database) throws { if creationDate == nil { creationDate = Date() } - - try super.insert(db) + try super.willInsert(db) } - override func didInsert(with rowID: Int64, for column: String?) { - self.id = rowID + override func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + id = inserted.rowID } } @@ -70,12 +69,12 @@ private class IntegerPropertyOnRealAffinityColumn : Record { // Record - required init(row: Row) { + required init(row: Row) throws { value = row["value"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["value"] = value } } @@ -100,38 +99,37 @@ private class PersonWithModifiedCaseColumns: Record { "persons" } - required init(row: Row) { + required init(row: Row) throws { id = row["ID"] age = row["AGE"] name = row["NAME"] creationDate = row["CREATIONDATE"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["ID"] = id container["NAME"] = name container["AGE"] = age container["CREATIONDATE"] = creationDate } - override func insert(_ db: Database) throws { - // This is implicitly tested with the NOT NULL constraint on creationDate + override func willInsert(_ db: Database) throws { if creationDate == nil { creationDate = Date() } - - try super.insert(db) + try super.willInsert(db) } - override func didInsert(with rowID: Int64, for column: String?) { - self.id = rowID + override func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + id = inserted.rowID } } class RecordEditedTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPerson", migrate: Person.setup) try migrator.migrate(dbWriter) @@ -144,11 +142,11 @@ class RecordEditedTests: GRDBTestCase { XCTAssertTrue(person.hasDatabaseChanges) } - func testRecordIsEditedAfterInitFromRow() { + func testRecordIsEditedAfterInitFromRow() throws { // Create a Record from a row. The row may not come from the database. // So it is edited. let row = Row(["name": "Arthur", "age": 41]) - let person = Person(row: row) + let person = try Person(row: row) XCTAssertTrue(person.hasDatabaseChanges) } @@ -377,52 +375,10 @@ class RecordEditedTests: GRDBTestCase { XCTAssertTrue(person.hasDatabaseChanges) } } - - func testCopyTransfersEditedFlag() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let person = Person(name: "Arthur", age: 41) - - try person.insert(db) - XCTAssertFalse(person.hasDatabaseChanges) - XCTAssertFalse(person.copy().hasDatabaseChanges) - - person.name = "Barbara" - XCTAssertTrue(person.hasDatabaseChanges) - XCTAssertTrue(person.copy().hasDatabaseChanges) - - person.hasDatabaseChanges = false - XCTAssertFalse(person.hasDatabaseChanges) - XCTAssertFalse(person.copy().hasDatabaseChanges) - - person.hasDatabaseChanges = true - XCTAssertTrue(person.hasDatabaseChanges) - XCTAssertTrue(person.copy().hasDatabaseChanges) - } - try dbQueue.inDatabase { db in - let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) - - try person.insert(db) - XCTAssertFalse(person.hasDatabaseChanges) - XCTAssertFalse(person.copy().hasDatabaseChanges) - - person.name = "Barbara" - XCTAssertTrue(person.hasDatabaseChanges) - XCTAssertTrue(person.copy().hasDatabaseChanges) - - person.hasDatabaseChanges = false - XCTAssertFalse(person.hasDatabaseChanges) - XCTAssertFalse(person.copy().hasDatabaseChanges) - - person.hasDatabaseChanges = true - XCTAssertTrue(person.hasDatabaseChanges) - XCTAssertTrue(person.copy().hasDatabaseChanges) - } - } - - func testChangesAfterInit() { + + func testChangesAfterInit() throws { let person = Person(name: "Arthur", age: 41) - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 4) for (column, old) in changes { switch column { @@ -440,9 +396,9 @@ class RecordEditedTests: GRDBTestCase { } } - func testChangesAfterInitFromRow() { - let person = Person(row: Row(["name": "Arthur", "age": 41])) - let changes = person.databaseChanges + func testChangesAfterInitFromRow() throws { + let person = try Person(row: Row(["name": "Arthur", "age": 41])) + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 4) for (column, old) in changes { switch column { @@ -470,12 +426,12 @@ class RecordEditedTests: GRDBTestCase { try Person(name: "Arthur", age: 41).insert(db) do { let person = try Person.fetchOne(db, sql: "SELECT * FROM persons")! - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 0) } do { let persons = try Person.fetchAll(db, sql: "SELECT * FROM persons") - let changes = persons[0].databaseChanges + let changes = try persons[0].databaseChanges XCTAssertEqual(changes.count, 0) } do { @@ -485,14 +441,14 @@ class RecordEditedTests: GRDBTestCase { } do { let person = try Person.fetchOne(db, sql: "SELECT * FROM persons", adapter: SuffixRowAdapter(fromIndex: 0))! - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 0) } } try dbQueue.inDatabase { db in try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db) let person = try PersonWithModifiedCaseColumns.fetchOne(db, sql: "SELECT * FROM persons")! - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 0) } } @@ -506,7 +462,7 @@ class RecordEditedTests: GRDBTestCase { try dbQueue.inDatabase { db in try Person(name: "Arthur", age: 41).insert(db) let person = try Person.fetchOne(db, sql: "SELECT name FROM persons")! - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 3) for (column, old) in changes { switch column { @@ -524,7 +480,7 @@ class RecordEditedTests: GRDBTestCase { try dbQueue.inDatabase { db in try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db) let person = try PersonWithModifiedCaseColumns.fetchOne(db, sql: "SELECT name FROM persons")! - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 3) for (column, old) in changes { switch column { @@ -547,13 +503,13 @@ class RecordEditedTests: GRDBTestCase { try dbQueue.inDatabase { db in let person = Person(name: "Arthur", age: 41) try person.insert(db) - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 0) } try dbQueue.inDatabase { db in let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) try person.insert(db) - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 0) } } @@ -569,7 +525,7 @@ class RecordEditedTests: GRDBTestCase { person.name = "Bobby" // non-nil -> non-nil person.age = 41 // nil -> non-nil person.creationDate = nil // non-nil -> nil - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 3) for (column, old) in changes { switch column { @@ -591,7 +547,7 @@ class RecordEditedTests: GRDBTestCase { person.name = "Bobby" // non-nil -> non-nil person.age = 41 // nil -> non-nil person.creationDate = nil // non-nil -> nil - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 3) for (column, old) in changes { switch column { @@ -616,14 +572,16 @@ class RecordEditedTests: GRDBTestCase { try person.insert(db) person.name = "Bobby" try person.update(db) - XCTAssertEqual(person.databaseChanges.count, 0) + XCTAssertFalse(person.hasDatabaseChanges) + try XCTAssert(person.databaseChanges.isEmpty) } try dbQueue.inDatabase { db in let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) try person.insert(db) person.name = "Bobby" try person.update(db) - XCTAssertEqual(person.databaseChanges.count, 0) + XCTAssertFalse(person.hasDatabaseChanges) + try XCTAssert(person.databaseChanges.isEmpty) } } @@ -633,10 +591,11 @@ class RecordEditedTests: GRDBTestCase { try dbQueue.inDatabase { db in let person = Person(name: "Arthur", age: 41) try person.save(db) - XCTAssertEqual(person.databaseChanges.count, 0) - + XCTAssertFalse(person.hasDatabaseChanges) + try XCTAssert(person.databaseChanges.isEmpty) + person.name = "Bobby" - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 1) for (column, old) in changes { switch column { @@ -647,15 +606,17 @@ class RecordEditedTests: GRDBTestCase { } } try person.save(db) - XCTAssertEqual(person.databaseChanges.count, 0) + XCTAssertFalse(person.hasDatabaseChanges) + try XCTAssert(person.databaseChanges.isEmpty) } try dbQueue.inDatabase { db in let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) try person.save(db) - XCTAssertEqual(person.databaseChanges.count, 0) - + XCTAssertFalse(person.hasDatabaseChanges) + try XCTAssert(person.databaseChanges.isEmpty) + person.name = "Bobby" - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 1) for (column, old) in changes { switch column { @@ -666,7 +627,8 @@ class RecordEditedTests: GRDBTestCase { } } try person.save(db) - XCTAssertEqual(person.databaseChanges.count, 0) + XCTAssertFalse(person.hasDatabaseChanges) + try XCTAssert(person.databaseChanges.isEmpty) } } @@ -677,7 +639,7 @@ class RecordEditedTests: GRDBTestCase { let person = Person(name: "Arthur", age: 41) try person.insert(db) person.id = person.id + 1 - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 1) for (column, old) in changes { switch column { @@ -692,7 +654,7 @@ class RecordEditedTests: GRDBTestCase { let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) try person.insert(db) person.id = person.id + 1 - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 1) for (column, old) in changes { switch column { @@ -704,48 +666,6 @@ class RecordEditedTests: GRDBTestCase { } } } - - func testCopyTransfersChanges() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let person = Person(name: "Arthur", age: 41) - - try person.insert(db) - XCTAssertEqual(person.databaseChanges.count, 0) - XCTAssertEqual(person.copy().databaseChanges.count, 0) - - person.name = "Barbara" - XCTAssertTrue(person.databaseChanges.count > 0) // TODO: compare actual changes - XCTAssertEqual(person.databaseChanges.count, person.copy().databaseChanges.count) - - person.hasDatabaseChanges = false - XCTAssertEqual(person.databaseChanges.count, 0) - XCTAssertEqual(person.copy().databaseChanges.count, 0) - - person.hasDatabaseChanges = true - XCTAssertTrue(person.databaseChanges.count > 0) // TODO: compare actual changes - XCTAssertEqual(person.databaseChanges.count, person.copy().databaseChanges.count) - } - try dbQueue.inDatabase { db in - let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41) - - try person.insert(db) - XCTAssertEqual(person.databaseChanges.count, 0) - XCTAssertEqual(person.copy().databaseChanges.count, 0) - - person.name = "Barbara" - XCTAssertTrue(person.databaseChanges.count > 0) // TODO: compare actual changes - XCTAssertEqual(person.databaseChanges.count, person.copy().databaseChanges.count) - - person.hasDatabaseChanges = false - XCTAssertEqual(person.databaseChanges.count, 0) - XCTAssertEqual(person.copy().databaseChanges.count, 0) - - person.hasDatabaseChanges = true - XCTAssertTrue(person.databaseChanges.count > 0) // TODO: compare actual changes - XCTAssertEqual(person.databaseChanges.count, person.copy().databaseChanges.count) - } - } func testUpdateChanges() throws { let dbQueue = try makeDatabaseQueue() @@ -756,7 +676,7 @@ class RecordEditedTests: GRDBTestCase { XCTAssertTrue(person.hasDatabaseChanges) try person.updateChanges(db) XCTFail("Expected PersistenceError") - } catch is PersistenceError { } + } catch PersistenceError.recordNotFound(databaseTableName: "persons", key: ["id": .null]) { } try person.insert(db) @@ -774,7 +694,7 @@ class RecordEditedTests: GRDBTestCase { // Update single column person.age = 42 - XCTAssertEqual(Set(person.databaseChanges.keys), ["age"]) + try XCTAssertEqual(Set(person.databaseChanges.keys), ["age"]) try XCTAssertTrue(person.updateChanges(db)) XCTAssertEqual(db.totalChangesCount, initialChangesCount + 1) XCTAssertEqual(lastSQLQuery, "UPDATE \"persons\" SET \"age\"=42 WHERE \"id\"=1") @@ -782,7 +702,7 @@ class RecordEditedTests: GRDBTestCase { // Update two columns person.name = "Barbara" person.age = 43 - XCTAssertEqual(Set(person.databaseChanges.keys), ["age", "name"]) + try XCTAssertEqual(Set(person.databaseChanges.keys), ["age", "name"]) try XCTAssertTrue(person.updateChanges(db)) XCTAssertEqual(db.totalChangesCount, initialChangesCount + 2) let fetchedPerson = try Person.fetchOne(db, key: person.id) diff --git a/Tests/GRDBTests/RecordInitializersTests.swift b/Tests/GRDBTests/RecordInitializersTests.swift index c29f027cc..73128fa88 100644 --- a/Tests/GRDBTests/RecordInitializersTests.swift +++ b/Tests/GRDBTests/RecordInitializersTests.swift @@ -19,8 +19,8 @@ class EmptyRecordWithoutInitializer : Record { class RecordWithMutablePropertyAndRowInitializer : Record { var name: String? - required init(row: Row) { - super.init(row: row) // super.init(row: row) is required + required init(row: Row) throws { + try super.init(row: row) // super.init(row: row) is required self.name = "toto" // property can be set before or after super.init } } @@ -34,8 +34,8 @@ class RecordWithMutablePropertyAndEmptyInitializer : Record { self.name = "toto" // property can be set before or after super.init } - required init(row: Row) { // init(row) is required - super.init(row: row) // super.init(row: row) is required + required init(row: Row) throws { // init(row) is required + try super.init(row: row) // super.init(row: row) is required } } @@ -48,8 +48,8 @@ class RecordWithMutablePropertyAndCustomInitializer : Record { super.init() // super.init() is required } - required init(row: Row) { // init(row) is required - super.init(row: row) // super.init(row: row) is required + required init(row: Row) throws { // init(row) is required + try super.init(row: row) // super.init(row: row) is required } } @@ -57,9 +57,9 @@ class RecordWithMutablePropertyAndCustomInitializer : Record { class RecordWithImmutableProperty : Record { let initializedFromRow: Bool - required init(row: Row) { // An initializer is required, and the minimum is init(row) - initializedFromRow = true // property must be set before super.init(row: row) - super.init(row: row) // super.init(row: row) is required + required init(row: Row) throws { // An initializer is required, and the minimum is init(row) + initializedFromRow = true // property must be set before super.init(row: row) + try super.init(row: row) // super.init(row: row) is required } } @@ -72,9 +72,9 @@ class RecordWithPedigree : Record { super.init() // super.init() is required } - required init(row: Row) { // An initializer is required, and the minimum is init(row) - initializedFromRow = true // property must be set before super.init(row: row) - super.init(row: row) // super.init(row: row) is required + required init(row: Row) throws { // An initializer is required, and the minimum is init(row) + initializedFromRow = true // property must be set before super.init(row: row) + try super.init(row: row) // super.init(row: row) is required } } @@ -87,9 +87,9 @@ class RecordWithImmutablePropertyAndCustomInitializer : Record { super.init() // super.init() is required } - required init(row: Row) { // An initializer is required, and the minimum is init(row) - initializedFromRow = true // property must be set before super.init(row: row) - super.init(row: row) // super.init(row: row) is required + required init(row: Row) throws { // An initializer is required, and the minimum is init(row) + initializedFromRow = true // property must be set before super.init(row: row) + try super.init(row: row) // super.init(row: row) is required } } diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 51df91e5d..305f53d4b 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -23,12 +23,12 @@ private class MinimalNonOptionalPrimaryKeySingle: Record, Hashable { "minimalSingles" } - required init(row: Row) { + required init(row: Row) throws { id = row["id"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["id"] = id } @@ -46,7 +46,7 @@ extension MinimalNonOptionalPrimaryKeySingle: Identifiable { } class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createMinimalNonOptionalPrimaryKeySingle", migrate: MinimalNonOptionalPrimaryKeySingle.setup) try migrator.migrate(dbWriter) @@ -62,7 +62,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalSingles WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -89,7 +89,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalSingles WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -119,7 +119,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { try record.update(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalSingles WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -150,7 +150,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalSingles WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -162,7 +162,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalSingles WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -175,7 +175,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalSingles WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -747,33 +747,29 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { } } - // MARK: Select ID + // MARK: Select PrimaryKey - func test_static_selectID() throws { - guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - + func test_static_selectPrimaryKey() throws { 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) + let ids: [String] = try MinimalSingle.selectPrimaryKey().fetchAll(db) XCTAssertEqual(ids, ["theUUID"]) + let rows = try MinimalSingle.selectPrimaryKey(as: Row.self).fetchAll(db) + XCTAssertEqual(rows, [["id": "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") - } - + func test_request_selectPrimaryKey() throws { 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) + let ids: [String] = try MinimalSingle.all().selectPrimaryKey().fetchAll(db) XCTAssertEqual(ids, ["theUUID"]) + let rows = try MinimalSingle.all().selectPrimaryKey(as: Row.self).fetchAll(db) + XCTAssertEqual(rows, [["id": "theUUID"]]) } } } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 270c71ca3..6534179bc 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -22,17 +22,18 @@ class MinimalRowID : Record, Hashable { "minimalRowIDs" } - required init(row: Row) { + required init(row: Row) throws { id = row["id"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["id"] = id } - override func didInsert(with rowID: Int64, for column: String?) { - self.id = rowID + override func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + id = inserted.rowID } static func == (lhs: MinimalRowID, rhs: MinimalRowID) -> Bool { @@ -49,7 +50,7 @@ extension MinimalRowID: Identifiable { } class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createMinimalRowID", migrate: MinimalRowID.setup) try migrator.migrate(dbWriter) @@ -67,7 +68,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertTrue(record.id != nil) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalRowIDs WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -79,7 +80,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalRowIDs WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -106,7 +107,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalRowIDs WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -137,7 +138,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { try record.update(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalRowIDs WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -170,7 +171,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertTrue(record.id != nil) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalRowIDs WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -182,7 +183,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalRowIDs WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -194,7 +195,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalRowIDs WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -207,7 +208,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalRowIDs WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -599,6 +600,9 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertTrue(fetchedRecord.id == record.id) XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") } + do { + try XCTAssertNil(MinimalRowID.fetchOne(db, id: nil)) + } } } } @@ -746,6 +750,9 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertTrue(fetchedRecord.id == record.id) XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") } + do { + try XCTAssertNil(MinimalRowID.filter(id: nil).fetchOne(db)) + } } } } @@ -781,33 +788,29 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } - // MARK: Select ID + // MARK: Select PrimaryKey - func test_static_selectID() throws { - guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - + func test_static_selectPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let record = MinimalRowID() try record.insert(db) - let ids = try MinimalRowID.selectID().fetchAll(db) + let ids: [Int64] = try MinimalRowID.selectPrimaryKey().fetchAll(db) XCTAssertEqual(ids, [1]) + let rows = try MinimalRowID.selectPrimaryKey(as: Row.self).fetchAll(db) + XCTAssertEqual(rows, [["id": 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") - } - + func test_request_selectPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let record = MinimalRowID() try record.insert(db) - let ids = try MinimalRowID.all().selectID().fetchAll(db) + let ids: [Int64] = try MinimalRowID.all().selectPrimaryKey().fetchAll(db) XCTAssertEqual(ids, [1]) + let rows = try MinimalRowID.all().selectPrimaryKey(as: Row.self).fetchAll(db) + XCTAssertEqual(rows, [["id": 1]]) } } } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index cae1f356c..04247d476 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -21,12 +21,12 @@ class MinimalSingle: Record, Hashable { "minimalSingles" } - required init(row: Row) { + required init(row: Row) throws { UUID = row["UUID"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["UUID"] = UUID } @@ -47,7 +47,7 @@ extension MinimalSingle: Identifiable { class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createMinimalSingle", migrate: MinimalSingle.setup) try migrator.migrate(dbWriter) @@ -78,7 +78,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -107,7 +107,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -139,7 +139,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { try record.update(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -186,7 +186,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -199,7 +199,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -213,7 +213,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -819,35 +819,31 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } - // 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") - } - + // MARK: Select PrimaryKey + + func test_static_selectPrimaryKey() throws { 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) + let ids: [String] = try MinimalSingle.selectPrimaryKey().fetchAll(db) XCTAssertEqual(ids, ["theUUID"]) + let rows = try MinimalSingle.selectPrimaryKey(as: Row.self).fetchAll(db) + XCTAssertEqual(rows, [["UUID": "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") - } - + func test_request_selectPrimaryKey() throws { 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) + let ids: [String] = try MinimalSingle.all().selectPrimaryKey().fetchAll(db) XCTAssertEqual(ids, ["theUUID"]) + let rows = try MinimalSingle.all().selectPrimaryKey(as: Row.self).fetchAll(db) + XCTAssertEqual(rows, [["UUID": "theUUID"]]) } } } diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index e0dfba00d..a15436b09 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -35,40 +35,31 @@ private class Person : Record, Hashable { "persons" } - required init(row: Row) { - #if compiler(>=5.5) + required init(row: Row) throws { id = row[.rowID] - #else - id = row[Column.rowID] - #endif age = row["age"] name = row["name"] creationDate = row["creationDate"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { - #if compiler(>=5.5) + override func encode(to container: inout PersistenceContainer) throws { container[.rowID] = id - #else - container[Column.rowID] = id - #endif container["name"] = name container["age"] = age container["creationDate"] = creationDate } - override func insert(_ db: Database) throws { - // This is implicitly tested with the NOT NULL constraint on creationDate + override func willInsert(_ db: Database) throws { if creationDate == nil { creationDate = Date() } - - try super.insert(db) + try super.willInsert(db) } - override func didInsert(with rowID: Int64, for column: String?) { - self.id = rowID + override func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + id = inserted.rowID } static func == (lhs: Person, rhs: Person) -> Bool { @@ -91,7 +82,7 @@ extension Person: Identifiable { } class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPerson", migrate: Person.setup) try migrator.migrate(dbWriter) @@ -109,7 +100,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(record.id != nil) let row = try Row.fetchOne(db, sql: "SELECT *, rowid FROM persons WHERE rowid = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -122,7 +113,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(record.id != nil) let row = try Row.fetchOne(db, sql: "SELECT *, rowid FROM persons WHERE rowid = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) return .rollback } // This is debatable, actually. @@ -136,7 +127,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT *, rowid FROM persons WHERE rowid = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -174,7 +165,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT *, rowid FROM persons WHERE rowid = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -220,7 +211,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { try record.update(db) let row = try Row.fetchOne(db, sql: "SELECT *, rowid FROM persons WHERE rowid = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -253,7 +244,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(record.id != nil) let row = try Row.fetchOne(db, sql: "SELECT *, rowid FROM persons WHERE rowid = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -264,7 +255,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT *, rowid FROM persons WHERE rowid = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -279,7 +270,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { try record.save(db) // Actual update let row = try Row.fetchOne(db, sql: "SELECT *, rowid FROM persons WHERE rowid = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -292,7 +283,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT *, rowid FROM persons WHERE rowid = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -704,6 +695,9 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") } + do { + try XCTAssertNil(Person.fetchOne(db, id: nil)) + } } } } @@ -857,6 +851,9 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") } + do { + try XCTAssertNil(Person.filter(id: nil).fetchOne(db)) + } } } } diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index 79835ab01..cd42ee4e3 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -30,14 +30,14 @@ private class Citizenship : Record, Hashable { "citizenships" } - required init(row: Row) { + required init(row: Row) throws { personName = row["personName"] countryName = row["countryName"] native = row["native"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["personName"] = personName container["countryName"] = countryName container["native"] = native @@ -59,7 +59,7 @@ private class Citizenship : Record, Hashable { class RecordPrimaryKeyMultipleTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createCitizenship", migrate: Citizenship.setup) try migrator.migrate(dbWriter) @@ -89,7 +89,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM citizenships WHERE personName = ? AND countryName = ?", arguments: [record.personName, record.countryName])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -116,7 +116,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM citizenships WHERE personName = ? AND countryName = ?", arguments: [record.personName, record.countryName])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -162,7 +162,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { try record.update(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM citizenships WHERE personName = ? AND countryName = ?", arguments: [record.personName, record.countryName])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -207,7 +207,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM citizenships WHERE personName = ? AND countryName = ?", arguments: [record.personName, record.countryName])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -221,7 +221,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { try record.save(db) // Actual update let row = try Row.fetchOne(db, sql: "SELECT * FROM citizenships WHERE personName = ? AND countryName = ?", arguments: [record.personName, record.countryName])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -234,7 +234,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM citizenships WHERE personName = ? AND countryName = ?", arguments: [record.personName, record.countryName])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index c114bfe30..cfe0b7dfe 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -28,19 +28,20 @@ private class Item : Record, Hashable { "items" } - required init(row: Row) { + required init(row: Row) throws { name = row["name"] email = row["email"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["name"] = name container["email"] = email } - override func didInsert(with rowID: Int64, for column: String?) { - insertedRowIDColumn = column + override func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + insertedRowIDColumn = inserted.rowIDColumn } static func == (lhs: Item, rhs: Item) -> Bool { @@ -55,7 +56,7 @@ private class Item : Record, Hashable { class RecordPrimaryKeyNoneTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createItem", migrate: Item.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index d3639adca..90b2be317 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -32,32 +32,31 @@ private class Person : Record, Hashable { "persons" } - required init(row: Row) { + required init(row: Row) throws { id = row["id"] age = row["age"] name = row["name"] creationDate = row["creationDate"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["id"] = id container["name"] = name container["age"] = age container["creationDate"] = creationDate } - override func insert(_ db: Database) throws { - // This is implicitly tested with the NOT NULL constraint on creationDate + override func willInsert(_ db: Database) throws { if creationDate == nil { creationDate = Date() } - - try super.insert(db) + try super.willInsert(db) } - override func didInsert(with rowID: Int64, for column: String?) { - self.id = rowID + override func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + id = inserted.rowID } static func == (lhs: Person, rhs: Person) -> Bool { @@ -77,7 +76,7 @@ private class Person : Record, Hashable { class RecordPrimaryKeyRowIDTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPerson", migrate: Person.setup) try migrator.migrate(dbWriter) @@ -95,7 +94,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { XCTAssertTrue(record.id != nil) let row = try Row.fetchOne(db, sql: "SELECT * FROM persons WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -108,7 +107,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { XCTAssertTrue(record.id != nil) let row = try Row.fetchOne(db, sql: "SELECT * FROM persons WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) return .rollback } // This is debatable, actually. @@ -122,7 +121,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM persons WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -160,7 +159,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM persons WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -206,7 +205,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { try record.update(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM persons WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -239,7 +238,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { XCTAssertTrue(record.id != nil) let row = try Row.fetchOne(db, sql: "SELECT * FROM persons WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -250,7 +249,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM persons WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -264,7 +263,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { try record.save(db) // Actual update let row = try Row.fetchOne(db, sql: "SELECT * FROM persons WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -277,7 +276,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM persons WHERE id = ?", arguments: [record.id])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index 53686dd82..70eaf248d 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -26,13 +26,13 @@ class Pet : Record, Hashable { "pets" } - required init(row: Row) { + required init(row: Row) throws { UUID = row["UUID"] name = row["name"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["UUID"] = UUID container["name"] = name } @@ -49,7 +49,7 @@ class Pet : Record, Hashable { class RecordPrimaryKeySingleTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPet", migrate: Pet.setup) try migrator.migrate(dbWriter) @@ -79,7 +79,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM pets WHERE UUID = ?", arguments: [record.UUID])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -106,7 +106,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM pets WHERE UUID = ?", arguments: [record.UUID])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -152,7 +152,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { try record.update(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM pets WHERE UUID = ?", arguments: [record.UUID])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -197,7 +197,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM pets WHERE UUID = ?", arguments: [record.UUID])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -211,7 +211,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { try record.save(db) // Actual update let row = try Row.fetchOne(db, sql: "SELECT * FROM pets WHERE UUID = ?", arguments: [record.UUID])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -224,7 +224,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM pets WHERE UUID = ?", arguments: [record.UUID])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index 110cde402..90c70b105 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -25,13 +25,13 @@ class Email : Record, Hashable { "emails" } - required init(row: Row) { + required init(row: Row) throws { email = row["email"] label = row["label"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["email"] = email container["label"] = label } @@ -48,7 +48,7 @@ class Email : Record, Hashable { class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createEmail", migrate: Email.setup) try migrator.migrate(dbWriter) @@ -80,7 +80,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM emails WHERE email = ?", arguments: [record.email])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -95,7 +95,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM emails WHERE email = ?", arguments: [record.email])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -109,7 +109,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { try record.insert(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM emails WHERE email = ?", arguments: [record.email])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -141,7 +141,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { try record.update(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM emails WHERE email = ?", arguments: [record.email])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -188,7 +188,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM emails WHERE email = ?", arguments: [record.email])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -201,7 +201,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM emails WHERE email = ?", arguments: [record.email])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } @@ -215,7 +215,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { try record.save(db) let row = try Row.fetchOne(db, sql: "SELECT * FROM emails WHERE email = ?", arguments: [record.email])! - assert(record, isEncodedIn: row) + try assert(record, isEncodedIn: row) } } diff --git a/Tests/GRDBTests/RecordSubClassTests.swift b/Tests/GRDBTests/RecordSubClassTests.swift index ff707813f..fc3d8dc3f 100644 --- a/Tests/GRDBTests/RecordSubClassTests.swift +++ b/Tests/GRDBTests/RecordSubClassTests.swift @@ -31,32 +31,31 @@ private class Person : Record { "persons" } - required init(row: Row) { + required init(row: Row) throws { id = row["id"] age = row["age"] name = row["name"] creationDate = row["creationDate"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["id"] = id container["name"] = name container["age"] = age container["creationDate"] = creationDate } - override func insert(_ db: Database) throws { - // This is implicitly tested with the NOT NULL constraint on creationDate + override func willInsert(_ db: Database) throws { if creationDate == nil { creationDate = Date() } - - try super.insert(db) + try super.willInsert(db) } - override func didInsert(with rowID: Int64, for column: String?) { - self.id = rowID + override func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + id = inserted.rowID } } @@ -65,9 +64,9 @@ private class MinimalPersonWithOverrides : Person { // Record - required init(row: Row) { + required init(row: Row) throws { extra = row["extra"] - super.init(row: row) + try super.init(row: row) } } @@ -86,25 +85,25 @@ private class PersonWithOverrides : Person { // Record - required init(row: Row) { + required init(row: Row) throws { extra = row["extra"] - super.init(row: row) + try super.init(row: row) } - override func insert(_ db: Database) throws { + override func willInsert(_ db: Database) throws { lastSavingMethod = .insert - try super.insert(db) + try super.willInsert(db) } - override func update(_ db: Database, columns: Set) throws { + override func willUpdate(_ db: Database, columns: Set) throws { lastSavingMethod = .update - try super.update(db, columns: columns) + try super.willUpdate(db, columns: columns) } } class RecordSubClassTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPerson", migrate: Person.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift index decaff676..0ce7021e0 100644 --- a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift +++ b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift @@ -23,29 +23,30 @@ class BadlyMangledStuff : Record { "stuffs" } - required init(row: Row) { + required init(row: Row) throws { // Here user may peek fancy column names that match his SQL queries. // However this is not the way to do it (see testBadlyMangledStuff()). id = row["mangled_id"] name = row["mangled_name"] - super.init(row: row) + try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { // User won't peek fancy column names because he will notice that the // generated INSERT query needs actual column names. container["id"] = id container["name"] = name } - override func didInsert(with rowID: Int64, for column: String?) { - self.id = rowID + override func didInsert(_ inserted: InsertionSuccess) { + super.didInsert(inserted) + id = inserted.rowID } } class RecordWithColumnNameManglingTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createBadlyMangledStuff", migrate: BadlyMangledStuff.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RowFetchTests.swift b/Tests/GRDBTests/RowFetchTests.swift index c419f5f3a..9a65c2ace 100644 --- a/Tests/GRDBTests/RowFetchTests.swift +++ b/Tests/GRDBTests/RowFetchTests.swift @@ -3,13 +3,24 @@ import GRDB class RowFetchTests: GRDBTestCase { + func testStatementInformationFromCursor() throws { + // Test that cursor provides statement information + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request: SQLRequest = "SELECT \("Arthur") AS firstName, \("Martin") AS lastName" + let cursor = try request.fetchCursor(db) + XCTAssertEqual(cursor.sql, "SELECT ? AS firstName, ? AS lastName") + XCTAssertEqual(cursor.arguments, ["Arthur", "Martin"]) + XCTAssertEqual(cursor.columnCount, 2) + XCTAssertEqual(cursor.columnNames, ["firstName", "lastName"]) + XCTAssertEqual(cursor.databaseRegion.description, "empty") + } + } + func testFetchCursor() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in func test(_ cursor: RowCursor) throws { - // Check that RowCursor gives access to the raw SQLite API - XCTAssertEqual(String(cString: sqlite3_column_name(cursor.statement.sqliteStatement, 0)), "firstName") - var row = try cursor.next()! XCTAssertEqual(row["firstName"] as String, "Arthur") XCTAssertEqual(row["lastName"] as String, "Martin") diff --git a/Tests/GRDBTests/SQLRequestTests.swift b/Tests/GRDBTests/SQLRequestTests.swift index 58bcaa11c..104cadc28 100644 --- a/Tests/GRDBTests/SQLRequestTests.swift +++ b/Tests/GRDBTests/SQLRequestTests.swift @@ -125,7 +125,7 @@ class SQLRequestTests: GRDBTestCase { """ } - static func filter(excludedIds: S) -> SQLRequest where S: Sequence, S.Element == Int64 { + static func filter(excludedIds: some Sequence) -> SQLRequest { """ SELECT * FROM \(self) diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index b03d8560e..f68746e10 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -3,7 +3,7 @@ import XCTest class SelectStatementTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ @@ -28,8 +28,12 @@ class SelectStatementTests : GRDBTestCase { let statement = try db.makeStatement(sql: sql) let cursor = try statement.makeCursor() - // Check that StatementCursor gives access to the raw SQLite API - XCTAssertEqual(String(cString: sqlite3_column_name(cursor.statement.sqliteStatement, 0)), "firstName") + // Test that cursor provides statement information + XCTAssertEqual(cursor.sql, sql) + XCTAssertEqual(cursor.arguments, []) + XCTAssertEqual(cursor.columnCount, 2) + XCTAssertEqual(cursor.columnNames, ["firstName", "lastName"]) + XCTAssertEqual(cursor.databaseRegion.description, "empty") XCTAssertFalse(try cursor.next() == nil) XCTAssertFalse(try cursor.next() == nil) @@ -44,7 +48,7 @@ class SelectStatementTests : GRDBTestCase { let customError = NSError(domain: "Custom", code: 0xDEAD) db.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError }) func test(_ cursor: StatementCursor) throws { - let sql = cursor.statement.sql + let sql = cursor.sql do { _ = try cursor.next() XCTFail() @@ -334,23 +338,11 @@ class SelectStatementTests : GRDBTestCase { 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.makeStatement(sql: "SELECT COUNT(*) FROM table1"), ] - let doubtfulCountFunction = (sqlite3_libversion_number() < 3019000) - let observers = statements.map { Observer(region: $0.databaseRegion) } - if doubtfulCountFunction { - XCTAssertEqual(observers.map { $0.region.description }, ["table1(a,b,id,id3,id4)","table1(a,id,id3)", "table1(a,id),table2(a,id)", "full database"]) - } else { - XCTAssertEqual(observers.map { $0.region.description }, ["table1(a,b,id,id3,id4)","table1(a,id,id3)", "table1(a,id),table2(a,id)", "table1(*)"]) - } + XCTAssertEqual(observers.map { $0.region.description }, ["table1(a,b,id,id3,id4)","table1(a,id,id3)", "table1(a,id),table2(a,id)", "table1(*)"]) for observer in observers { db.add(transactionObserver: observer) @@ -362,7 +354,7 @@ class SelectStatementTests : GRDBTestCase { XCTAssertEqual(observers.map(\.triggered), [true, true, true, true]) try db.execute(sql: "INSERT INTO table2 (id, a, b) VALUES (NULL, 0, 0)") - XCTAssertEqual(observers.map(\.triggered), [false, false, true, doubtfulCountFunction]) + XCTAssertEqual(observers.map(\.triggered), [false, false, true, false]) try db.execute(sql: "UPDATE table1 SET a = 1") XCTAssertEqual(observers.map(\.triggered), [true, true, true, true]) @@ -371,10 +363,10 @@ class SelectStatementTests : GRDBTestCase { XCTAssertEqual(observers.map(\.triggered), [true, false, false, true]) try db.execute(sql: "UPDATE table2 SET a = 1") - XCTAssertEqual(observers.map(\.triggered), [false, false, true, doubtfulCountFunction]) + XCTAssertEqual(observers.map(\.triggered), [false, false, true, false]) try db.execute(sql: "UPDATE table2 SET b = 1") - XCTAssertEqual(observers.map(\.triggered), [false, false, false, doubtfulCountFunction]) + XCTAssertEqual(observers.map(\.triggered), [false, false, false, false]) try db.execute(sql: "UPDATE table3 SET id = 2 WHERE id = 1") XCTAssertEqual(observers.map(\.triggered), [true, true, false, true]) @@ -387,7 +379,7 @@ class SelectStatementTests : GRDBTestCase { try db.execute(sql: "INSERT INTO table4 (id) VALUES (1)") try db.execute(sql: "DELETE FROM table4") - XCTAssertEqual(observers.map(\.triggered), [false, false, false, doubtfulCountFunction]) + XCTAssertEqual(observers.map(\.triggered), [false, false, false, false]) try db.execute(sql: "DELETE FROM table3") XCTAssertEqual(observers.map(\.triggered), [true, true, true, true]) diff --git a/Tests/GRDBTests/SharedValueObservationTests.swift b/Tests/GRDBTests/SharedValueObservationTests.swift index 45610e39e..e510fc73e 100644 --- a/Tests/GRDBTests/SharedValueObservationTests.swift +++ b/Tests/GRDBTests/SharedValueObservationTests.swift @@ -621,7 +621,6 @@ class SharedValueObservationTests: GRDBTestCase { } #endif -#if compiler(>=5.6) && canImport(_Concurrency) @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait() async throws { let dbQueue = try makeDatabaseQueue() @@ -641,7 +640,6 @@ class SharedValueObservationTests: GRDBTestCase { break } } -#endif } private class Log: TextOutputStream { diff --git a/Tests/GRDBTests/StatementArguments+FoundationTests.swift b/Tests/GRDBTests/StatementArguments+FoundationTests.swift index 812f625c8..61ec4b075 100644 --- a/Tests/GRDBTests/StatementArguments+FoundationTests.swift +++ b/Tests/GRDBTests/StatementArguments+FoundationTests.swift @@ -6,7 +6,7 @@ private class NonDatabaseConvertibleObject: NSObject class StatementArgumentsFoundationTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/StatementArgumentsTests.swift b/Tests/GRDBTests/StatementArgumentsTests.swift index aa00fcf47..de0ab55ae 100644 --- a/Tests/GRDBTests/StatementArgumentsTests.swift +++ b/Tests/GRDBTests/StatementArgumentsTests.swift @@ -3,7 +3,7 @@ import GRDB class StatementArgumentsTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift index f0dbc1a75..ed94e9e69 100644 --- a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift +++ b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift @@ -11,7 +11,7 @@ private struct Fetched: DatabaseValueConvertible, StatementColumnConvertible, Ha self.fast = fast } - init(sqliteStatement: SQLiteStatement, index: Int32) { + init(sqliteStatement: SQLiteStatement, index: CInt) { self.init(int: Int(sqlite3_column_int64(sqliteStatement, index)), fast: true) } @@ -479,6 +479,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { do { func test(_ value: Fetched?) { XCTAssertEqual(value!.int, 1) + XCTAssertTrue(value!.fast) } do { let sql = "SELECT 1" @@ -582,7 +583,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { func testOptionalFetchCursor() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - func test(_ cursor: FastNullableDatabaseValueCursor) throws { + func test(_ cursor: FastDatabaseValueCursor) throws { let i = try cursor.next()! XCTAssertEqual(i!.int, 1) XCTAssertTrue(i!.fast) @@ -624,7 +625,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { func testOptionalFetchCursorCompilationFailure() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - func test(_ cursor: @autoclosure () throws -> FastNullableDatabaseValueCursor, sql: String) throws { + func test(_ cursor: @autoclosure () throws -> FastDatabaseValueCursor, sql: String) throws { do { _ = try cursor() XCTFail() @@ -860,4 +861,159 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } } } + + func testOptionalFetchOne() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + func test(_ nilBecauseMissingRow: Fetched??) { + switch nilBecauseMissingRow { + case .none: break + default: XCTFail("Expected nil because missing row") + } + } + do { + let sql = "SELECT 1 WHERE 0" + let statement = try db.makeStatement(sql: sql) + try test(Optional.fetchOne(db, sql: sql)) + try test(Optional.fetchOne(statement)) + try test(Optional.fetchOne(db, SQLRequest(sql: sql))) + try test(SQLRequest(sql: sql).fetchOne(db)) + } + do { + let sql = "SELECT 0, 1 WHERE 0" + let statement = try db.makeStatement(sql: sql) + let adapter = SuffixRowAdapter(fromIndex: 1) + try test(Optional.fetchOne(db, sql: sql, adapter: adapter)) + try test(Optional.fetchOne(statement, adapter: adapter)) + try test(Optional.fetchOne(db, SQLRequest(sql: sql, adapter: adapter))) + try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db)) + } + } + do { + func test(_ nilBecauseNull: Fetched??) { + switch nilBecauseNull { + case .some(.none): break + default: XCTFail("Expected .some(nil) because NULL") + } + } + do { + let sql = "SELECT NULL" + let statement = try db.makeStatement(sql: sql) + try test(Optional.fetchOne(db, sql: sql)) + try test(Optional.fetchOne(statement)) + try test(Optional.fetchOne(db, SQLRequest(sql: sql))) + try test(SQLRequest(sql: sql).fetchOne(db)) + } + do { + let sql = "SELECT 0, NULL" + let statement = try db.makeStatement(sql: sql) + let adapter = SuffixRowAdapter(fromIndex: 1) + try test(Optional.fetchOne(db, sql: sql, adapter: adapter)) + try test(Optional.fetchOne(statement, adapter: adapter)) + try test(Optional.fetchOne(db, SQLRequest(sql: sql, adapter: adapter))) + try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db)) + } + } + do { + func test(_ value: Fetched??) { + XCTAssertEqual(value!!.int, 1) + XCTAssertTrue(value!!.fast) + } + do { + let sql = "SELECT 1" + let statement = try db.makeStatement(sql: sql) + try test(Optional.fetchOne(db, sql: sql)) + try test(Optional.fetchOne(statement)) + try test(Optional.fetchOne(db, SQLRequest(sql: sql))) + try test(SQLRequest(sql: sql).fetchOne(db)) + } + do { + let sql = "SELECT 0, 1" + let statement = try db.makeStatement(sql: sql) + let adapter = SuffixRowAdapter(fromIndex: 1) + try test(Optional.fetchOne(db, sql: sql, adapter: adapter)) + try test(Optional.fetchOne(statement, adapter: adapter)) + try test(Optional.fetchOne(db, SQLRequest(sql: sql, adapter: adapter))) + try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db)) + } + } + } + } + + func testOptionalFetchOneWithInterpolation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request: SQLRequest = "SELECT \(42)" + let fetched = try request.fetchOne(db) + XCTAssertEqual(fetched!!.int, 42) + XCTAssertTrue(fetched!!.fast) + } + } + + func testOptionalFetchOneStepFailure() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let customError = NSError(domain: "Custom", code: 0xDEAD) + db.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError }) + func test(_ value: @autoclosure () throws -> Fetched??, sql: String) throws { + do { + _ = try value() + XCTFail() + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "\(customError)") + XCTAssertEqual(error.sql!, sql) + XCTAssertEqual(error.description, "SQLite error 1: \(customError) - while executing `\(sql)`") + } + } + do { + let sql = "SELECT throw()" + try test(Optional.fetchOne(db, sql: sql), sql: sql) + try test(Optional.fetchOne(db.makeStatement(sql: sql)), sql: sql) + try test(Optional.fetchOne(db, SQLRequest(sql: sql)), sql: sql) + try test(SQLRequest(sql: sql).fetchOne(db), sql: sql) + } + do { + let sql = "SELECT 0, throw()" + let adapter = SuffixRowAdapter(fromIndex: 1) + try test(Optional.fetchOne(db, sql: sql, adapter: adapter), sql: sql) + try test(Optional.fetchOne(db.makeStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.fetchOne(db, SQLRequest(sql: sql, adapter: adapter)), sql: sql) + try test(SQLRequest(sql: sql, adapter: adapter).fetchOne(db), sql: sql) + } + } + } + + func testOptionalFetchOneCompilationFailure() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + func test(_ value: @autoclosure () throws -> Fetched??, sql: String) throws { + do { + _ = try value() + XCTFail() + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "no such table: nonExistingTable") + XCTAssertEqual(error.sql!, sql) + XCTAssertEqual(error.description, "SQLite error 1: no such table: nonExistingTable - while executing `\(sql)`") + } + } + do { + let sql = "SELECT * FROM nonExistingTable" + try test(Optional.fetchOne(db, sql: sql), sql: sql) + try test(Optional.fetchOne(db.makeStatement(sql: sql)), sql: sql) + try test(Optional.fetchOne(db, SQLRequest(sql: sql)), sql: sql) + try test(SQLRequest(sql: sql).fetchOne(db), sql: sql) + } + do { + let sql = "SELECT * FROM nonExistingTable" + let adapter = SuffixRowAdapter(fromIndex: 1) + try test(Optional.fetchOne(db, sql: sql, adapter: adapter), sql: sql) + try test(Optional.fetchOne(db.makeStatement(sql: sql), adapter: adapter), sql: sql) + try test(Optional.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/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index 9277b99ce..3553cec4c 100644 --- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -14,7 +14,7 @@ private struct Reader : TableRecord { class TableRecordQueryInterfaceRequestTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute(sql: """ @@ -386,6 +386,10 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { try XCTAssertFalse(Player.exists(db, id: 1)) XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"player\" WHERE \"id\" = 1)") + sqlQueries.removeAll() + try XCTAssertFalse(Player.exists(db, id: nil)) + XCTAssertNil(lastSQLQuery) // Database not hit + return .rollback } try dbQueue.inTransaction { db in diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index 07e60e613..ee8f21011 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -9,9 +9,11 @@ private struct Hacker : TableRecord { @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) extension Hacker: Identifiable { } -private struct Person : TableRecord { +private struct Person : Codable, PersistableRecord, FetchableRecord, Hashable { static let databaseTableName = "persons" var id: Int64 // Non-optional + var name: String + var email: String } @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) @@ -24,7 +26,7 @@ private struct Citizenship : TableRecord { class TableRecordDeleteTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE hackers (name TEXT)") try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)") @@ -46,6 +48,7 @@ class TableRecordDeleteTests: GRDBTestCase { if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { try db.execute(sql: "INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [1, "Arthur"]) + try XCTAssertFalse(Hacker.deleteOne(db, id: nil)) deleted = try Hacker.deleteOne(db, id: 1) XCTAssertTrue(deleted) XCTAssertEqual(try Hacker.fetchCount(db), 0) @@ -171,7 +174,7 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testRequestDelete() throws { + func testRequestDeleteAll() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -226,7 +229,134 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testJoinedRequestDelete() throws { + func testRequestDeleteAndFetchStatement() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Person.all() + let statement = try request.deleteAndFetchStatement(db, selection: [AllColumns()]) + XCTAssertEqual(statement.sql, "DELETE FROM \"persons\" RETURNING *") + XCTAssertEqual(statement.columnNames, ["id", "name", "email"]) + } + } + + func testRequestDeleteAndFetchCursor() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + + try dbQueue.inDatabase { db in + _ = try Person.all().deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" RETURNING *") + + _ = try Person.all().deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" RETURNING *") + + _ = try Person.filter(Column("name") == "Arthur").deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"name\" = 'Arthur' RETURNING *") + + _ = try Person.filter(key: 1).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *") + + _ = try Person.filter(keys: [1, 2]).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *") + + if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + _ = try Person.filter(id: 1).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *") + + _ = try Person.filter(ids: [1, 2]).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *") + } + + _ = try Person.filter(sql: "id = 1").deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE id = 1 RETURNING *") + + _ = try Person.filter(sql: "id = 1").filter(Column("name") == "Arthur").deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (id = 1) AND (\"name\" = 'Arthur') RETURNING *") + + _ = try Person.select(Column("name")).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" RETURNING *") + + _ = try Person.order(Column("name")).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" RETURNING *") + + // No test for LIMIT ... RETURNING ... since this is not supported by SQLite + } + } + + func testRequestDeleteAndFetchArray() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try Person(id: 1, name: "Arthur", email: "arthur@example.com").insert(db) + try Person(id: 2, name: "Barbara", email: "barbara@example.com").insert(db) + try Person(id: 3, name: "Craig", email: "craig@example.com").insert(db) + + let request = Person.filter(Column("id") != 2) + let deletePersons = try request + .deleteAndFetchAll(db) + .sorted(by: { $0.id < $1.id }) + XCTAssertEqual(deletePersons, [ + Person(id: 1, name: "Arthur", email: "arthur@example.com"), + Person(id: 3, name: "Craig", email: "craig@example.com"), + ]) + } + } + + func testRequestDeleteAndFetchSet() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try Person(id: 1, name: "Arthur", email: "arthur@example.com").insert(db) + try Person(id: 2, name: "Barbara", email: "barbara@example.com").insert(db) + try Person(id: 3, name: "Craig", email: "craig@example.com").insert(db) + + let request = Person.filter(Column("id") != 2) + let deletePersons = try request.deleteAndFetchSet(db) + XCTAssertEqual(deletePersons, [ + Person(id: 1, name: "Arthur", email: "arthur@example.com"), + Person(id: 3, name: "Craig", email: "craig@example.com"), + ]) + } + } + + func testJoinedRequestDeleteAll() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { static let team = belongsTo(Team.self) @@ -286,7 +416,109 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testGroupedRequestDelete() throws { + func testJoinedRequestDeleteAndFetch() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + struct Player: MutablePersistableRecord, FetchableRecord { + static let team = belongsTo(Team.self) + func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } + init(row: Row) { preconditionFailure("should not be called") } + } + + struct Team: MutablePersistableRecord, FetchableRecord { + // Test RETURNING + static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")] + static let players = hasMany(Player.self) + func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } + init(row: Row) { preconditionFailure("should not be called") } + } + + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamId", .integer).references("team") + } + + do { + let request = Player.including(required: Player.team) + let statement = try request.deleteAndFetchStatement(db, selection: [AllColumns()]) + XCTAssertEqual(statement.sql, """ + DELETE FROM "player" WHERE "id" IN (\ + SELECT "player"."id" \ + FROM "player" \ + JOIN "team" ON "team"."id" = "player"."teamId") \ + RETURNING * + """) + XCTAssertEqual(statement.columnNames, ["id", "teamId"]) + + _ = try request.deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, """ + DELETE FROM "player" WHERE "id" IN (\ + SELECT "player"."id" \ + FROM "player" \ + JOIN "team" ON "team"."id" = "player"."teamId") \ + RETURNING * + """) + } + do { + let alias = TableAlias(name: "p") + _ = try Player.aliased(alias).including(required: Player.team).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, """ + DELETE FROM "player" WHERE "id" IN (\ + SELECT "p"."id" \ + FROM "player" "p" \ + JOIN "team" ON "team"."id" = "p"."teamId") \ + RETURNING * + """) + } + do { + let request = Team.having(Team.players.isEmpty) + let statement = try request.deleteAndFetchStatement(db, selection: [AllColumns()]) + XCTAssertEqual(statement.sql, """ + DELETE FROM "team" WHERE "id" IN (\ + SELECT "team"."id" \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ + GROUP BY "team"."id" \ + HAVING COUNT(DISTINCT "player"."id") = 0) \ + RETURNING * + """) + XCTAssertEqual(statement.columnNames, ["id", "name"]) + + _ = try request.deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, """ + DELETE FROM "team" WHERE "id" IN (\ + SELECT "team"."id" \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ + GROUP BY "team"."id" \ + HAVING COUNT(DISTINCT "player"."id") = 0) \ + RETURNING "id", "name" + """) + } + do { + _ = try Team.including(all: Team.players).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, """ + DELETE FROM "team" RETURNING "id", "name" + """) + } + } + } + + func testGroupedRequestDeleteAll() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } @@ -350,4 +582,86 @@ class TableRecordDeleteTests: GRDBTestCase { } } } + + func testGroupedRequestDeleteAndFetchCursor() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + struct Player: MutablePersistableRecord, FetchableRecord { + func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } + init(row: Row) { preconditionFailure("should not be called") } + } + struct Passport: MutablePersistableRecord, FetchableRecord { + func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } + init(row: Row) { preconditionFailure("should not be called") } + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("score", .integer) + } + try db.create(table: "passport") { t in + t.column("countryCode", .text).notNull() + t.column("citizenId", .integer).notNull() + t.primaryKey(["countryCode", "citizenId"]) + } + do { + _ = try Player.all().groupByPrimaryKey().deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, """ + DELETE FROM "player" WHERE "id" IN (\ + SELECT "id" \ + FROM "player" \ + GROUP BY "id") \ + RETURNING * + """) + } + do { + _ = try Player.all().group(-Column("id")).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, """ + DELETE FROM "player" WHERE "id" IN (\ + SELECT "id" \ + FROM "player" \ + GROUP BY -"id") \ + RETURNING * + """) + } + do { + _ = try Player.all().group(Column.rowID).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, """ + DELETE FROM "player" WHERE "id" IN (\ + SELECT "id" \ + FROM "player" \ + GROUP BY "rowid") \ + RETURNING * + """) + } + do { + _ = try Passport.all().groupByPrimaryKey().deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, """ + DELETE FROM "passport" WHERE "rowid" IN (\ + SELECT "rowid" \ + FROM "passport" \ + GROUP BY "rowid") \ + RETURNING * + """) + } + do { + _ = try Passport.all().group(Column.rowID).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, """ + DELETE FROM "passport" WHERE "rowid" IN (\ + SELECT "rowid" \ + FROM "passport" \ + GROUP BY "rowid") \ + RETURNING * + """) + } + } + } } diff --git a/Tests/GRDBTests/TableRecordUpdateTests.swift b/Tests/GRDBTests/TableRecordUpdateTests.swift index 4154bdf30..eeabd3bfc 100644 --- a/Tests/GRDBTests/TableRecordUpdateTests.swift +++ b/Tests/GRDBTests/TableRecordUpdateTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -private struct Player: Codable, TableRecord, FetchableRecord { +private struct Player: Codable, PersistableRecord, FetchableRecord, Hashable { var id: Int64 var name: String var score: Int @@ -24,7 +24,7 @@ private enum Columns: String, ColumnExpression { case id, name, score, bonus } -private extension QueryInterfaceRequest where RowDecoder == Player { +private extension QueryInterfaceRequest { func incrementScore(_ db: Database) throws { try updateAll(db, Columns.score += 1) } @@ -117,6 +117,110 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testRequestUpdateAndFetchStatement() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + let assignment = Columns.score.set(to: 0) + + let request = Player.all() + let statement = try request.updateAndFetchStatement(db, [assignment], selection: [AllColumns()]) + XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING *") + XCTAssertEqual(statement.arguments, [0]) + XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"]) + } + } + + func testRequestUpdateAndFetchCursor() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try Player(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db) + try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db) + try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db) + + let request = Player.filter(Columns.id != 2) + let cursor = try request.updateAndFetchCursor(db, [Columns.score += 100]) + let updatedPlayers = try Array(cursor).sorted(by: { $0.id < $1.id }) + XCTAssertEqual(updatedPlayers, [ + Player(id: 1, name: "Arthur", score: 110, bonus: 0), + Player(id: 3, name: "Craig", score: 130, bonus: 20), + ]) + } + } + + func testRequestUpdateAndFetchAll() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try Player(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db) + try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db) + try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db) + + let request = Player.filter(Columns.id != 2) + let updatedPlayers = try request + .updateAndFetchAll(db, [Columns.score += 100]) + .sorted(by: { $0.id < $1.id }) + XCTAssertEqual(updatedPlayers, [ + Player(id: 1, name: "Arthur", score: 110, bonus: 0), + Player(id: 3, name: "Craig", score: 130, bonus: 20), + ]) + } + } + + func testRequestUpdateAndFetchSet() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try Player(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db) + try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db) + try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db) + + let request = Player.filter(Columns.id != 2) + let updatedPlayers = try request.updateAndFetchSet(db, [Columns.score += 100]) + XCTAssertEqual(updatedPlayers, [ + Player(id: 1, name: "Arthur", score: 110, bonus: 0), + Player(id: 3, name: "Craig", score: 130, bonus: 20), + ]) + } + } + func testNilAssignment() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) diff --git a/Tests/GRDBTests/TableTests.swift b/Tests/GRDBTests/TableTests.swift index a82d6b723..375649d4d 100644 --- a/Tests/GRDBTests/TableTests.swift +++ b/Tests/GRDBTests/TableTests.swift @@ -52,6 +52,9 @@ class TableTests: GRDBTestCase { """) try XCTAssertEqual(t.select(Column("id"), as: Int64.self).fetchOne(db), 1) try XCTAssertEqual(t.select(Column("id")).fetchOne(db), 1) + try XCTAssertEqual(t.selectPrimaryKey().fetchOne(db), 1) + try XCTAssertEqual(t.selectPrimaryKey(as: Int64.self).fetchOne(db), 1) + try XCTAssertEqual(t.selectPrimaryKey(as: Row.self).fetchOne(db), ["id": 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) @@ -124,7 +127,6 @@ class TableTests: GRDBTestCase { 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, *) { @@ -134,10 +136,12 @@ class TableTests: GRDBTestCase { try assertEqualSQL(db, t.filter(id: 1), """ SELECT * FROM "player" WHERE "id" = 1 """) + try assertEqualSQL(db, t.filter(id: nil), """ + SELECT * FROM "player" WHERE 0 + """) 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) } } } @@ -250,6 +254,7 @@ class TableTests: GRDBTestCase { do { try db.execute(sql: "DELETE FROM player") try XCTAssertEqual(t.fetchOne(db), nil) + try XCTAssertEqual(t.fetchOne(db), .none) } do { @@ -261,7 +266,8 @@ class TableTests: GRDBTestCase { do { try db.execute(sql: "DELETE FROM player") try db.execute(sql: "INSERT INTO player VALUES (NULL)") - try XCTAssertEqual(t.fetchOne(db), nil) + try XCTAssertNotEqual(t.fetchOne(db), nil) + try XCTAssertEqual(t.fetchOne(db), .some(nil)) } } } @@ -308,6 +314,7 @@ class TableTests: GRDBTestCase { do { try db.execute(sql: "DELETE FROM player") try XCTAssertEqual(t.fetchOne(db), nil) + try XCTAssertEqual(t.fetchOne(db), .none) } do { @@ -319,7 +326,8 @@ class TableTests: GRDBTestCase { do { try db.execute(sql: "DELETE FROM player") try db.execute(sql: "INSERT INTO player VALUES (NULL)") - try XCTAssertEqual(t.fetchOne(db), nil) + try XCTAssertNotEqual(t.fetchOne(db), nil) + try XCTAssertEqual(t.fetchOne(db), .some(.none)) } } } @@ -822,6 +830,10 @@ class TableTests: GRDBTestCase { DELETE FROM "country" WHERE "code" = 'FR' """) + sqlQueries.removeAll() + try Table("country").deleteOne(db, id: nil) + XCTAssertNil(lastSQLQuery) // Database not hit + try Table("country").deleteAll(db, ids: ["FR", "DE"]) XCTAssertEqual(lastSQLQuery, """ DELETE FROM "country" WHERE "code" IN ('FR', 'DE') @@ -926,6 +938,10 @@ class TableTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, """ SELECT EXISTS (SELECT * FROM "country" WHERE "code" = 'FR') """) + + sqlQueries.removeAll() + try XCTAssertFalse(Table("country").exists(db, id: nil)) + XCTAssertNil(lastSQLQuery) // Database not hit } } } diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index 2c38fa4b8..446927342 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -96,8 +96,8 @@ private final class Artist: Codable { extension Artist : FetchableRecord, PersistableRecord { static let databaseTableName = "artists" - func didInsert(with rowID: Int64, for column: String?) { - self.id = rowID + func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -115,8 +115,8 @@ private final class Artwork : Codable { extension Artwork : FetchableRecord, PersistableRecord { static let databaseTableName = "artworks" - func didInsert(with rowID: Int64, for column: String?) { - self.id = rowID + func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } diff --git a/Tests/GRDBTests/UpdateStatementTests.swift b/Tests/GRDBTests/UpdateStatementTests.swift index 401977207..0db27cf65 100644 --- a/Tests/GRDBTests/UpdateStatementTests.swift +++ b/Tests/GRDBTests/UpdateStatementTests.swift @@ -3,7 +3,7 @@ import GRDB class UpdateStatementTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ @@ -24,11 +24,13 @@ class UpdateStatementTests : GRDBTestCase { 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() + try db.makeStatement(sql: "INSERT INTO persons (name) VALUES ('Eugene')\r\n").execute() + try db.makeStatement(sql: "INSERT INTO persons (name) VALUES ('Fiona')\u{000C}" /* \f */).execute() return .commit } try dbQueue.inDatabase { db in let names = try String.fetchAll(db, sql: "SELECT name FROM persons ORDER BY name") - XCTAssertEqual(names, ["Arthur", "Barbara", "Craig", "Daniel"]) + XCTAssertEqual(names, ["Arthur", "Barbara", "Craig", "Daniel", "Eugene", "Fiona"]) } } @@ -37,9 +39,13 @@ class UpdateStatementTests : GRDBTestCase { try dbQueue.inDatabase { db in 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', ?)") + try XCTAssertEqual(db.makeStatement(sql: " INSERT INTO persons (name, age) VALUES ('Arthur', ?)\r\n").sql, "INSERT INTO persons (name, age) VALUES ('Arthur', ?)") + try XCTAssertEqual(db.makeStatement(sql: " INSERT INTO persons (name, age) VALUES ('Arthur', ?)\t").sql, "INSERT INTO persons (name, age) VALUES ('Arthur', ?)") + try XCTAssertEqual(db.makeStatement(sql: " INSERT INTO persons (name, age) VALUES ('Arthur', ?)\n").sql, "INSERT INTO persons (name, age) VALUES ('Arthur', ?)") + try XCTAssertEqual(db.makeStatement(sql: " INSERT INTO persons (name, age) VALUES ('Arthur', ?)\u{000C}" /* \f */).sql, "INSERT INTO persons (name, age) VALUES ('Arthur', ?)") } } - + func testArrayStatementArguments() throws { let dbQueue = try makeDatabaseQueue() @@ -184,6 +190,8 @@ class UpdateStatementTests : GRDBTestCase { try db.execute(sql: ";") try db.execute(sql: ";;") try db.execute(sql: " \n;\t; ") + try db.execute(sql: "\r\n") + try db.execute(sql: "\u{000C}") // \f try db.execute(sql: "-- comment") try db.execute(sql: "-- comment\\n; -----ignored") } @@ -210,7 +218,7 @@ class UpdateStatementTests : GRDBTestCase { func testExecuteMultipleStatementWithTrailingSemicolonAndWhiteSpace() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - try db.execute(sql: "CREATE TABLE wines (name TEXT, color INT); CREATE TABLE books (name TEXT, age INT);\n \t") + try db.execute(sql: "CREATE TABLE wines (name TEXT, color INT); CREATE TABLE books (name TEXT, age INT);\r\n \t") XCTAssertTrue(try db.tableExists("wines")) XCTAssertTrue(try db.tableExists("books")) } diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index 79e0a4236..737c548fd 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -180,7 +180,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { } try db.execute(sql: "DELETE FROM t WHERE id = 1") }) -} + } func testOneOptional() throws { let request = SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC") @@ -188,15 +188,16 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { try assertValueObservation( ValueObservation.trackingConstantRegion(request.fetchOne), records: [ - nil, + .none, Name(rawValue: "foo"), Name(rawValue: "foo"), Name(rawValue: "bar"), - nil, + .none, Name(rawValue: "baz"), + .some(nil), nil, - nil, - nil, + .some(nil), + .some(nil), Name(rawValue: "qux")], setup: { db in try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") @@ -215,18 +216,21 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { try db.execute(sql: "UPDATE t SET name = NULL") try db.execute(sql: "DELETE FROM t") try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, NULL)") + try db.execute(sql: "UPDATE t SET name = NULL") try db.execute(sql: "UPDATE t SET name = 'qux'") }) try assertValueObservation( ValueObservation.trackingConstantRegion(request.fetchOne).removeDuplicates(), records: [ - nil, + .none, Name(rawValue: "foo"), Name(rawValue: "bar"), - nil, + .none, Name(rawValue: "baz"), + .some(nil), nil, + .some(nil), Name(rawValue: "qux")], setup: { db in try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") @@ -245,6 +249,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { try db.execute(sql: "UPDATE t SET name = NULL") try db.execute(sql: "DELETE FROM t") try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, NULL)") + try db.execute(sql: "UPDATE t SET name = NULL") try db.execute(sql: "UPDATE t SET name = 'qux'") }) } diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index 8108fa296..35f6da8cd 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -28,7 +28,7 @@ class ValueObservationPrintTests: GRDBTestCase { try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") } - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { let logger = TestStream() let observation = ValueObservation .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } @@ -62,7 +62,7 @@ class ValueObservationPrintTests: GRDBTestCase { try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") } - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { let logger = TestStream() let observation = ValueObservation .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } @@ -91,10 +91,10 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_readonly_failure_asynchronousScheduling() throws { + struct TestError: Error { } _ = try makeDatabasePool(filename: "test") - func test(_ dbReader: DatabaseReader) throws { - struct TestError: Error { } + func test(_ dbReader: some DatabaseReader) throws { let logger = TestStream() let observation = ValueObservation .trackingConstantRegion { _ in throw TestError() } @@ -123,10 +123,10 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_readonly_failure_immediateScheduling() throws { + struct TestError: Error { } _ = try makeDatabasePool(filename: "test") - func test(_ dbReader: DatabaseReader) throws { - struct TestError: Error { } + func test(_ dbReader: some DatabaseReader) throws { let logger = TestStream() let observation = ValueObservation .trackingConstantRegion { _ in throw TestError() } @@ -157,7 +157,7 @@ class ValueObservationPrintTests: GRDBTestCase { // MARK: - Writeonly func test_writeonly_success_asynchronousScheduling() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") } @@ -199,7 +199,7 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_writeonly_success_immediateScheduling() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") } @@ -241,7 +241,7 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_writeonly_immediateFailure_asynchronousScheduling() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let logger = TestStream() var observation = ValueObservation .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } @@ -268,7 +268,7 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_writeonly_immediateFailure_immediateScheduling() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let logger = TestStream() var observation = ValueObservation .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } @@ -295,7 +295,7 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_writeonly_lateFailure_asynchronousScheduling() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") } @@ -338,7 +338,7 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_writeonly_lateFailure_immediateScheduling() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") } diff --git a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift index bc9d03836..30317ed65 100644 --- a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift @@ -207,7 +207,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { ValueObservation .trackingConstantRegion { db in try Row.fetchOne(db, request) } .removeDuplicates() - .map { row in row.map(ParentInfo.init(row:)) }, + .map { row in try row.map(ParentInfo.init(row:)) }, records: [ nil, ParentInfo( @@ -312,7 +312,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { ValueObservation .trackingConstantRegion { db in try Row.fetchAll(db, request) } .removeDuplicates() - .map { rows in rows.map(ParentInfo.init(row:)) }, + .map { rows in try rows.map(ParentInfo.init(row:)) }, records: [ [], [ diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 4db189940..0d4a677be 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -174,12 +174,12 @@ public class ValueObservationRecorder { } } - fileprivate func receive(_ cancellable: DatabaseCancellable) { + fileprivate func receive(_ cancellable: AnyDatabaseCancellable) { synchronized { if state.cancellable != nil { XCTFail("ValueObservationRecorder is already observing") } - state.cancellable = AnyDatabaseCancellable(cancellable) + state.cancellable = cancellable } } } @@ -218,7 +218,7 @@ extension ValueObservationRecorder { extension ValueObservation { public func record( - in reader: DatabaseReader, + in reader: some DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), onError: ((Error) -> Void)? = nil, onChange: ((Reducer.Value) -> Void)? = nil) @@ -283,8 +283,6 @@ extension XCTestCase { return try valueObservationExpectation.get() } - // #file vs. #filePath dance - #if compiler(>=5.3) /// This test checks the fundamental promise of ValueObservation by /// comparing recorded values with expected values. /// @@ -310,71 +308,13 @@ extension XCTestCase { /// - `[]` (missing last value) /// - `[0, 1, 2]` (unexpected value) /// - `[1, 0, 1]` (unexpected value) - public func assertValueObservationRecordingMatch( - recorded recordedValues: [Value], - expected expectedValues: [Value], - _ message: @autoclosure () -> String = "", - file: StaticString = #filePath, - line: UInt = #line) - where Value: Equatable - { - _assertValueObservationRecordingMatch( - recorded: recordedValues, - expected: expectedValues, - // Last value can't be missed - allowMissingLastValue: false, - message(), file: file, line: line) - } - #else - /// This test checks the fundamental promise of ValueObservation by - /// comparing recorded values with expected values. - /// - /// Recorded values match the expected values if and only if: - /// - /// - The last recorded value is the last expected value - /// - Recorded values are in the same order as expected values - /// - /// However, both missing and repeated values are allowed - with the only - /// exception of the last expected value which can not be missed. - /// - /// For example, if the expected values are [0, 1], then the following - /// recorded values match: - /// - /// - `[0, 1]` (identical values) - /// - `[1]` (missing value but the last one) - /// - `[0, 0, 1, 1]` (repeated value) - /// - /// However the following recorded values don't match, and fail the test: - /// - /// - `[1, 0]` (wrong order) - /// - `[0]` (missing last value) - /// - `[]` (missing last value) - /// - `[0, 1, 2]` (unexpected value) - /// - `[1, 0, 1]` (unexpected value) - public func assertValueObservationRecordingMatch( - recorded recordedValues: [Value], - expected expectedValues: [Value], + func assertValueObservationRecordingMatch( + recorded recordedValues: R, + expected expectedValues: E, + allowMissingLastValue: Bool = false, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) - where Value: Equatable - { - _assertValueObservationRecordingMatch( - recorded: recordedValues, - expected: expectedValues, - // Last value can't be missed - allowMissingLastValue: false, - message(), file: file, line: line) - } - #endif - - private func _assertValueObservationRecordingMatch( - recorded recordedValues: R, - expected expectedValues: E, - allowMissingLastValue: Bool, - _ message: @autoclosure () -> String = "", - file: StaticString, - line: UInt) where R: BidirectionalCollection, E: BidirectionalCollection, @@ -400,7 +340,7 @@ extension XCTestCase { let remainingRecordedValues = recordedValues.prefix(recordedValues.count - recordedSuffix.count) let remainingExpectedValues = expectedValues.prefix(expectedValues.count - expectedSuffix.count) - _assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: remainingRecordedValues, expected: remainingExpectedValues, // Other values can be missed @@ -412,13 +352,13 @@ extension XCTestCase { // MARK: - GRDBTestCase + ValueObservationExpectation extension GRDBTestCase { - func _assertValueObservation( + func assertValueObservation( _ observation: ValueObservation, records expectedValues: [Reducer.Value], setup: (Database) throws -> Void, recordedUpdates: @escaping (Database) throws -> Void, - file: StaticString, - line: UInt) + file: StaticString = #file, + line: UInt = #line) throws where Reducer.Value: Equatable { @@ -427,7 +367,7 @@ extension GRDBTestCase { scheduling scheduler: ValueObservationScheduler, testValueDispatching: @escaping () -> Void) throws { - func testRecordingEqualWhenWriteAfterStart(writer: DatabaseWriter) throws { + func testRecordingEqualWhenWriteAfterStart(writer: some DatabaseWriter) throws { try writer.write(setup) var value: Reducer.Value? @@ -454,7 +394,7 @@ extension GRDBTestCase { "\(#function), \(writer), \(scheduler)", file: file, line: line) } - func testRecordingEqualWhenWriteAfterFirstValue(writer: DatabaseWriter) throws { + func testRecordingEqualWhenWriteAfterFirstValue(writer: some DatabaseWriter) throws { try writer.write(setup) var valueCount = 0 @@ -484,7 +424,7 @@ extension GRDBTestCase { "\(#function), \(writer), \(scheduler)", file: file, line: line) } - func testRecordingMatchWhenWriteAfterStart(writer: DatabaseWriter) throws { + func testRecordingMatchWhenWriteAfterStart(writer: some DatabaseWriter) throws { try writer.write(setup) var value: Reducer.Value? @@ -529,7 +469,7 @@ extension GRDBTestCase { "\(#function), \(writer), \(scheduler)", file: file, line: line) } - func testRecordingMatchWhenWriteAfterFirstValue(writer: DatabaseWriter) throws { + func testRecordingMatchWhenWriteAfterFirstValue(writer: some DatabaseWriter) throws { try writer.write(setup) var valueCount = 0 @@ -624,12 +564,12 @@ extension GRDBTestCase { } } - func _assertValueObservation( + func assertValueObservation( _ observation: ValueObservation, fails testFailure: (Failure, DatabaseWriter) throws -> Void, setup: (Database) throws -> Void, - file: StaticString, - line: UInt) + file: StaticString = #file, + line: UInt = #line) throws { func test( @@ -637,7 +577,7 @@ extension GRDBTestCase { scheduling scheduler: ValueObservationScheduler, testErrorDispatching: @escaping () -> Void) throws { - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { try writer.write(setup) let recorder = observation.record( @@ -689,67 +629,6 @@ extension GRDBTestCase { testErrorDispatching: { XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) }) } } - - // #file vs. #filePath dance - #if compiler(>=5.3) - func assertValueObservation( - _ observation: ValueObservation, - records expectedValues: [Reducer.Value], - setup: (Database) throws -> Void, - recordedUpdates: @escaping (Database) throws -> Void, - file: StaticString = #filePath, - line: UInt = #line) - throws - where Reducer.Value: Equatable - { - try _assertValueObservation( - observation, - records: expectedValues, - setup: setup, - recordedUpdates: recordedUpdates, - file: file, line: line) - } - - func assertValueObservation( - _ observation: ValueObservation, - fails testFailure: (Failure, DatabaseWriter) throws -> Void, - setup: (Database) throws -> Void, - file: StaticString = #filePath, - line: UInt = #line) - throws - { - try _assertValueObservation(observation, fails: testFailure, setup: setup, file: file, line: line) - } - #else - func assertValueObservation( - _ observation: ValueObservation, - records expectedValues: [Reducer.Value], - setup: (Database) throws -> Void, - recordedUpdates: @escaping (Database) throws -> Void, - file: StaticString = #file, - line: UInt = #line) - throws - where Reducer.Value: Equatable - { - try _assertValueObservation( - observation, - records: expectedValues, - setup: setup, - recordedUpdates: recordedUpdates, - file: file, line: line) - } - - func assertValueObservation( - _ observation: ValueObservation, - fails testFailure: (Failure, DatabaseWriter) throws -> Void, - setup: (Database) throws -> Void, - file: StaticString = #file, - line: UInt = #line) - throws - { - try _assertValueObservation(observation, fails: testFailure, setup: setup, file: file, line: line) - } - #endif } // MARK: - ValueObservationExpectations diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index 30a10f22b..90bd8beb8 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -23,7 +23,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { } do { - var region = DatabaseRegion.fullTable("player") + var region = DatabaseRegion(table: "player") db.recordingSelection(®ion) { } XCTAssertEqual(region.description, "player(*)") } @@ -45,7 +45,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { } do { - var region = DatabaseRegion.fullTable("player") + var region = DatabaseRegion(table: "player") _ = try db.recordingSelection(®ion) { _ = try Row.fetchAll(db, sql: "SELECT * FROM team") } diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index b7252bb2a..b29b5d8b7 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -4,9 +4,10 @@ import Dispatch class ValueObservationTests: GRDBTestCase { func testImmediateError() throws { - func test(_ dbWriter: DatabaseWriter) throws { + struct TestError: Error { } + + func test(_ dbWriter: some DatabaseWriter) throws { // Create an observation - struct TestError: Error { } let observation = ValueObservation.trackingConstantRegion { _ in throw TestError() } // Start observation @@ -24,7 +25,9 @@ class ValueObservationTests: GRDBTestCase { } func testErrorCompletesTheObservation() throws { - func test(_ dbWriter: DatabaseWriter) throws { + struct TestError: Error { } + + func test(_ dbWriter: some DatabaseWriter) throws { // We need something to change try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -34,7 +37,6 @@ class ValueObservationTests: GRDBTestCase { notificationExpectation.expectedFulfillmentCount = 4 notificationExpectation.isInverted = true - struct TestError: Error { } var nextError: Error? = nil // If not null, observation throws an error let observation = ValueObservation.trackingConstantRegion { _ = try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t") @@ -419,20 +421,12 @@ class ValueObservationTests: GRDBTestCase { } let expectedCounts: [Int] - #if GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7) + #if GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) // Optimization not available expectedCounts = [0, 0, 1] - #elseif GRDBCUSTOMSQLITE + #else // Optimization available expectedCounts = [0, 1] - #else - if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { - // Optimization available - expectedCounts = [0, 1] - } else { - // Optimization not available - expectedCounts = [0, 0, 1] - } #endif let expectation = self.expectation(description: "") @@ -477,20 +471,12 @@ class ValueObservationTests: GRDBTestCase { } let expectedCounts: [Int] - #if GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7) + #if GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) // Optimization not available expectedCounts = [0, 0, 1] - #elseif GRDBCUSTOMSQLITE + #else // Optimization available expectedCounts = [0, 1] - #else - if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { - // Optimization available - expectedCounts = [0, 1] - } else { - // Optimization not available - expectedCounts = [0, 0, 1] - } #endif let expectation = self.expectation(description: "") @@ -605,7 +591,7 @@ class ValueObservationTests: GRDBTestCase { func testCancellableInvalidation1() throws { // Test that observation stops when cancellable is deallocated - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } let notificationExpectation = expectation(description: "notification") @@ -649,7 +635,7 @@ class ValueObservationTests: GRDBTestCase { func testCancellableInvalidation2() throws { // Test that observation stops when cancellable is deallocated - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } let notificationExpectation = expectation(description: "notification") @@ -693,7 +679,7 @@ class ValueObservationTests: GRDBTestCase { } func testIssue1209() throws { - func test(_ dbWriter: Writer) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -741,12 +727,11 @@ class ValueObservationTests: GRDBTestCase { try test(makeDatabasePool()) } -#if compiler(>=5.6) && canImport(_Concurrency) // MARK: - Async Await @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_values_prefix() async throws { - func test(writer: DatabaseWriter) async throws { + func test(_ writer: some DatabaseWriter) async throws { // We need something to change try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -773,15 +758,14 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try await AsyncTest(test).run { try DatabaseQueue() } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_values_prefix_immediate_scheduling() async throws { - func test(writer: DatabaseWriter) async throws { + func test(_ writer: some DatabaseWriter) async throws { // We need something to change try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -808,15 +792,14 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try await AsyncTest(test).run { try DatabaseQueue() } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_values_break() async throws { - func test(writer: DatabaseWriter) async throws { + func test(_ writer: some DatabaseWriter) async throws { // We need something to change try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -847,15 +830,14 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try await AsyncTest(test).run { try DatabaseQueue() } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_values_immediate_break() async throws { - func test(writer: DatabaseWriter) async throws { + func test(_ writer: some DatabaseWriter) async throws { // We need something to change try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -883,15 +865,14 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try await AsyncTest(test).run { try DatabaseQueue() } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_values_cancelled() async throws { - func test(writer: DatabaseWriter) async throws { + func test(_ writer: some DatabaseWriter) async throws { // We need something to change try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -931,10 +912,8 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try await AsyncTest(test).run { try DatabaseQueue() } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } -#endif } diff --git a/Tests/GRDBTests/VirtualTableModuleTests.swift b/Tests/GRDBTests/VirtualTableModuleTests.swift index 6cd05f26a..b13848acd 100644 --- a/Tests/GRDBTests/VirtualTableModuleTests.swift +++ b/Tests/GRDBTests/VirtualTableModuleTests.swift @@ -4,7 +4,7 @@ import GRDB private struct FTS3TokenizeModule : VirtualTableModule { let moduleName = "fts3tokenize" - func makeTableDefinition() -> FTS3TokenizeTableDefinition { + func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS3TokenizeTableDefinition { FTS3TokenizeTableDefinition() } @@ -22,7 +22,7 @@ private struct FTS3TokenizeModule : VirtualTableModule { private struct ThrowingFTS3TokenizeModule : VirtualTableModule { let moduleName = "fts3tokenize" - func makeTableDefinition() -> FTS3TokenizeTableDefinition { + func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS3TokenizeTableDefinition { FTS3TokenizeTableDefinition() } diff --git a/Tests/Performance/GRDBPerformance/FetchRecordClassTests.swift b/Tests/Performance/GRDBPerformance/FetchRecordClassTests.swift index b2a13dbdb..d62267715 100644 --- a/Tests/Performance/GRDBPerformance/FetchRecordClassTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchRecordClassTests.swift @@ -30,7 +30,7 @@ class FetchRecordClassTests: XCTestCase { "item" } - required init(row: GRDB.Row) { + required init(row: GRDB.Row) throws { i0 = row["i0"] i1 = row["i1"] i2 = row["i2"] @@ -41,7 +41,7 @@ class FetchRecordClassTests: XCTestCase { i7 = row["i7"] i8 = row["i8"] i9 = row["i9"] - super.init(row: row) + try super.init(row: row) } } diff --git a/Tests/Performance/GRDBPerformance/InsertRecordClassTests.swift b/Tests/Performance/GRDBPerformance/InsertRecordClassTests.swift index 1bd3349c6..f58755727 100644 --- a/Tests/Performance/GRDBPerformance/InsertRecordClassTests.swift +++ b/Tests/Performance/GRDBPerformance/InsertRecordClassTests.swift @@ -45,7 +45,7 @@ class InsertRecordClassTests: XCTestCase { fatalError("init(row:) has not been implemented") } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["i0"] = i0 container["i1"] = i1 container["i2"] = i2 diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj index e8a1f3b3a..2851c7774 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj @@ -186,7 +186,7 @@ 56537C6A1BA8871A00E87787 /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 1200; + LastUpgradeCheck = 1400; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { 56537C711BA8871A00E87787 = { @@ -346,6 +346,7 @@ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; @@ -363,7 +364,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.13; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; @@ -403,6 +404,7 @@ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; @@ -414,7 +416,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.13; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_VERSION = 5.0; @@ -428,6 +430,7 @@ CLANG_ENABLE_OBJC_WEAK = YES; CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; INFOPLIST_FILE = GRDBProfiling/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", @@ -445,6 +448,7 @@ CLANG_ENABLE_OBJC_WEAK = YES; CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; INFOPLIST_FILE = GRDBProfiling/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/xcshareddata/xcschemes/GRDBProfiling.xcscheme b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/xcshareddata/xcschemes/GRDBProfiling.xcscheme index 2c3be795f..143cc0289 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/xcshareddata/xcschemes/GRDBProfiling.xcscheme +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/xcshareddata/xcschemes/GRDBProfiling.xcscheme @@ -1,6 +1,6 @@ Bool { - _ = DatabaseQueue() + _ = try! DatabaseQueue() .readPublisher(value: { _ in }) .assertNoFailure() return true diff --git a/Tests/SPM/macos/macos/AppDelegate.swift b/Tests/SPM/macos/macos/AppDelegate.swift index 11cb5cdcc..e056c1961 100644 --- a/Tests/SPM/macos/macos/AppDelegate.swift +++ b/Tests/SPM/macos/macos/AppDelegate.swift @@ -4,7 +4,7 @@ import GRDB @main class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { - _ = DatabaseQueue() + _ = try! DatabaseQueue() } func applicationWillTerminate(_ aNotification: Notification) {