From 8dc0168841dba8e26d41b723b918b2ce636450db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Mar 2022 16:05:54 +0100 Subject: [PATCH 01/73] Database.sqliteConnection setter is private --- GRDB/Core/Database.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index f935f7f17..c6658dece 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -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 From df7ba20ff2e6570bfc6904df099b814435d2d6e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Mar 2022 13:26:28 +0100 Subject: [PATCH 02/73] Test columnInfos(in:) for views --- Tests/GRDBTests/ColumnInfoTests.swift | 92 +++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/Tests/GRDBTests/ColumnInfoTests.swift b/Tests/GRDBTests/ColumnInfoTests.swift index 31de2168c..267404087 100644 --- a/Tests/GRDBTests/ColumnInfoTests.swift +++ b/Tests/GRDBTests/ColumnInfoTests.swift @@ -176,6 +176,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 { From 9d7e27ced15bda72e0b6f815947cc57f0e5ad0be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Mar 2022 14:13:01 +0100 Subject: [PATCH 03/73] Add support for index origin --- GRDB/Core/Database+Schema.swift | 30 ++++++++++++++++++++++------ Tests/GRDBTests/IndexInfoTests.swift | 4 ++++ 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index ac584849f..a3d242c3e 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -341,6 +341,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 +363,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 { @@ -779,6 +780,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 +809,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 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) } From e150ca6864fd0d40100b46367b2e89c4a255d47b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Aug 2022 10:50:12 +0200 Subject: [PATCH 04/73] Migration guide to GRDB 6 --- Documentation/GRDB6MigrationGuide.md | 13 +++++++++++++ README.md | 4 ++-- 2 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 Documentation/GRDB6MigrationGuide.md diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md new file mode 100644 index 000000000..836cdaa74 --- /dev/null +++ b/Documentation/GRDB6MigrationGuide.md @@ -0,0 +1,13 @@ +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) + + +## 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. diff --git a/README.md b/README.md index d9a5e8b45..7c3cc6c1c 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ --- -**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**: July 9, 2022 • [version 5.26.0](https://github.com/groue/GRDB.swift/tree/v5.26.0) • [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+ @@ -360,7 +360,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) From d1a32d19506ebfabef2a52421a01447e3b4df529 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Jul 2022 12:59:59 +0200 Subject: [PATCH 05/73] Swift 5.7 required: Makefile --- Makefile | 92 +------------------------------------------------------- 1 file changed, 1 insertion(+), 91 deletions(-) diff --git a/Makefile b/Makefile index 4e788121a..f68c38d54 100644 --- a/Makefile +++ b/Makefile @@ -52,103 +52,13 @@ TEST_ACTIONS = clean build build-for-testing test-without-building # `xcrun xctrace list devices` (or the deprecated `instruments -s devices`). ifeq ($(XCODEVERSION),14.0) MAX_SWIFT_VERSION = 5.7 - MIN_SWIFT_VERSION = 5.3 + MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=16.0" MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=12.4" MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=16.0" #MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks' GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' -else ifeq ($(XCODEVERSION),13.4) - MAX_SWIFT_VERSION = 5.6 - MIN_SWIFT_VERSION = 5.3 - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=15.5" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=13.7" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.4" - #MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore - OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks' - GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' -else ifeq ($(XCODEVERSION),13.3) - MAX_SWIFT_VERSION = 5.6 - MIN_SWIFT_VERSION = 5.3 - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=15.4" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=13.7" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.4" - #MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore - OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks' - GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' -else ifeq ($(XCODEVERSION),13.2) - MAX_SWIFT_VERSION = 5.5 - MIN_SWIFT_VERSION = 5.3 - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=15.2" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=13.7" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.2" - #MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore - OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks' - GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' -else ifeq ($(XCODEVERSION),13.1) - MAX_SWIFT_VERSION = 5.5 - MIN_SWIFT_VERSION = 5.3 - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=15.0" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=13.7" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.0" - #MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore - OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' - GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' -else ifeq ($(XCODEVERSION),13.0) - MAX_SWIFT_VERSION = 5.5 - MIN_SWIFT_VERSION = 5.3 - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=15.0" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=11.4" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.0" - MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" - OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' - GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' -else ifeq ($(XCODEVERSION),12.5) - MAX_SWIFT_VERSION = 5.4 - MIN_SWIFT_VERSION = 5.3 - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.5" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=11.4" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=14.5" - MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" - OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' - GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' -else ifeq ($(XCODEVERSION),12.4) - MAX_SWIFT_VERSION = 5.3 - MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.4" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=11.4" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=14.3" - MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" - OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' - GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' -else ifeq ($(XCODEVERSION),12.3) - MAX_SWIFT_VERSION = 5.3 - MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.3" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=14.3" - MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" - OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' - GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' -else ifeq ($(XCODEVERSION),12.2) - MAX_SWIFT_VERSION = 5.3 - MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.2" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=14.2" - MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" - OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' - GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' -else ifeq ($(XCODEVERSION),12.0) - MAX_SWIFT_VERSION = 5.3 - MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=14.0" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=14.0" - MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" - OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' - GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' else # Swift 5.3 required: Xcode < 12.0 is not supported endif From a22113faa594cf56280c7643d361163d11fc1a5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Jul 2022 13:00:10 +0200 Subject: [PATCH 06/73] Swift 5.7 required: podspec --- GRDB.swift.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 0000990cb..e5112371e 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -9,7 +9,7 @@ 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' From fc59b454932045b72a40fad3a743a1c87563d8a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Jul 2022 13:00:55 +0200 Subject: [PATCH 07/73] Swift 5.7 required: Package.swift --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index c93a39597..505b0f698 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.2 +// swift-tools-version:5.7 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription From df0ae43c5f8fbb7561ac0c4175e505f98ef53afa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Jul 2022 13:05:10 +0200 Subject: [PATCH 08/73] Swift 5.7 required: Sendable --- GRDB/Core/DatabaseError.swift | 2 +- GRDB/Core/DatabaseReader.swift | 2 +- GRDB/Core/DatabaseValue.swift | 2 +- GRDB/Core/DatabaseWriter.swift | 3 --- GRDB/Core/RowDecodingError.swift | 4 ++-- GRDB/Core/Statement.swift | 2 +- GRDB/Utils/Utils.swift | 6 ------ Tests/GRDBTests/BackupTestCase.swift | 2 +- 8 files changed, 7 insertions(+), 16 deletions(-) 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/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index d5ff1f34f..f2719ab1f 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 } diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 41e02913f..86172505b 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -157,7 +157,7 @@ extension DatabaseValue: StatementBinding { } } -extension DatabaseValue: GRDBSendable { } +extension DatabaseValue: Sendable { } #if swift(>=5.6) && canImport(_Concurrency) // @unchecked due to Foundation.Data not conforming to Sendable diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 3ab24d3ea..df7376e20 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -384,7 +384,6 @@ extension DatabaseWriter { 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 +407,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 +430,6 @@ extension DatabaseWriter { } } - // TODO: remove @escaping as soon as it is possible /// Asynchronously executes database updates, outside of any transaction, /// and returns the result. /// diff --git a/GRDB/Core/RowDecodingError.swift b/GRDB/Core/RowDecodingError.swift index 54cf0d6f8..657c110d6 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 diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 2017130d5..a994296a1 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -940,4 +940,4 @@ extension StatementArguments { } } -extension StatementArguments: GRDBSendable { } +extension StatementArguments: Sendable { } diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index f42e0f2ce..62b20dd37 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -32,12 +32,6 @@ public protocol _OptionalProtocol { /// :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/Tests/GRDBTests/BackupTestCase.swift b/Tests/GRDBTests/BackupTestCase.swift index f4474f9b9..bc6dba2e1 100644 --- a/Tests/GRDBTests/BackupTestCase.swift +++ b/Tests/GRDBTests/BackupTestCase.swift @@ -4,7 +4,7 @@ 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 { try writer.write { db in From fcb037bdf0b27833980ac8836df1e65138e7bd26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Aug 2022 19:21:57 +0200 Subject: [PATCH 09/73] Swift 5.7 required: Bump deployment targets --- CHANGELOG.md | 5 +++++ Documentation/GRDB6MigrationGuide.md | 12 ++++++++++++ GRDB.swift.podspec | 6 +++--- GRDB/Record/EncodableRecord.swift | 2 +- Package.swift | 6 +++--- README.md | 9 +++++---- SQLiteCustom/GRDBDeploymentTarget.xcconfig | 6 +++--- Support/GRDBDeploymentTarget.xcconfig | 6 +++--- .../SQLCipher3/GRDBTests.xcodeproj/project.pbxproj | 4 ++-- Tests/CocoaPods/SQLCipher3/Podfile | 2 +- .../SQLCipher4/GRDBTests.xcodeproj/project.pbxproj | 4 ++-- Tests/CocoaPods/SQLCipher4/Podfile | 2 +- .../CustomSQLite.xcodeproj/project.pbxproj | 4 ++-- .../GRDBProfiling.xcodeproj/project.pbxproj | 4 ++-- .../SPM/PlainProject/Plain.xcodeproj/project.pbxproj | 4 ++-- 15 files changed, 47 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 783f6a3ce..bef30f951 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -93,6 +93,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## 6.0.0 + +- **Breaking**: Swift 5.7+ and Xcode 14+ are required. +- **Breaking**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ are required. + ## 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/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index 836cdaa74..7df94ebe8 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -4,6 +4,7 @@ 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) ## Preparing the Migration to GRDB 6 @@ -11,3 +12,14 @@ Migrating From GRDB 5 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+) diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index e5112371e..6e664a7d3 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -11,9 +11,9 @@ Pod::Spec.new do |s| 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| diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 1a02fe384..9a2c6a21b 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -67,7 +67,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: /// diff --git a/Package.swift b/Package.swift index 505b0f698..e003cb869 100644 --- a/Package.swift +++ b/Package.swift @@ -7,9 +7,9 @@ let package = Package( name: "GRDB", platforms: [ .iOS(.v11), - .macOS(.v10_10), - .tvOS(.v9), - .watchOS(.v2), + .macOS(.v10_13), + .tvOS(.v11), + .watchOS(.v4), ], products: [ .library(name: "GRDB", targets: ["GRDB"]), diff --git a/README.md b/README.md index 7c3cc6c1c..35be12298 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@

A toolkit for SQLite databases, with a focus on application development

- Swift 5.3 + Swift 5.7 Platforms License CI Status @@ -13,11 +13,12 @@ **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 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.8.5+ • Swift 5.7+ / Xcode 14+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.3+** | **v5.26.0** | +| **Swift 5.7+** | **v5.26.0** | +| 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) | @@ -3126,7 +3127,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 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/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/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 239d10277..a731f80e8 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -1672,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; }; @@ -1706,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/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..e5db016ea 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -1678,7 +1678,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 +1712,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/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/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj index e8a1f3b3a..185eaeb97 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj @@ -363,7 +363,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; @@ -414,7 +414,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; diff --git a/Tests/SPM/PlainProject/Plain.xcodeproj/project.pbxproj b/Tests/SPM/PlainProject/Plain.xcodeproj/project.pbxproj index 74ef4a166..00bcf692e 100644 --- a/Tests/SPM/PlainProject/Plain.xcodeproj/project.pbxproj +++ b/Tests/SPM/PlainProject/Plain.xcodeproj/project.pbxproj @@ -187,7 +187,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; @@ -241,7 +241,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.13; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; SDKROOT = macosx; From 6da7d473947c1188efa40f9ce2f5eb249546c2f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Jul 2022 13:34:45 +0200 Subject: [PATCH 10/73] Swift 5.7 required: Remove compiler checks --- GRDB/Core/DatabasePool.swift | 2 - GRDB/Core/DatabaseReader.swift | 2 - GRDB/Core/DatabaseRegion.swift | 2 - GRDB/Core/DatabaseValue.swift | 2 - GRDB/Core/DatabaseWriter.swift | 3 - GRDB/Core/Row.swift | 3 - GRDB/Core/SerializedDatabase.swift | 2 - .../Request/RequestProtocols.swift | 4 - GRDB/QueryInterface/SQL/Column.swift | 2 - GRDB/QueryInterface/SQL/SQLExpression.swift | 2 - .../SharedValueObservation.swift | 2 - GRDB/ValueObservation/ValueObservation.swift | 2 - Tests/GRDBCombineTests/Support.swift | 29 ---- ...sociationPrefetchingObservationTests.swift | 27 +--- Tests/GRDBTests/DatabaseReaderTests.swift | 7 +- .../DatabaseValueConversionTests.swift | 67 +------- Tests/GRDBTests/DatabaseWriterTests.swift | 12 -- Tests/GRDBTests/DerivableRequestTests.swift | 8 - Tests/GRDBTests/FTS3RecordTests.swift | 8 - Tests/GRDBTests/FTS4RecordTests.swift | 8 - Tests/GRDBTests/FTS5RecordTests.swift | 8 - Tests/GRDBTests/FailureTestCase.swift | 72 --------- Tests/GRDBTests/ForeignKeyInfoTests.swift | 13 +- .../FoundationDateComponentsTests.swift | 13 +- Tests/GRDBTests/FoundationDateTests.swift | 58 +------ Tests/GRDBTests/GRDBTestCase.swift | 71 +-------- .../RecordPrimaryKeyHiddenRowIDTests.swift | 8 - .../SharedValueObservationTests.swift | 2 - .../GRDBTests/ValueObservationRecorder.swift | 143 ++---------------- Tests/GRDBTests/ValueObservationTests.swift | 2 - 30 files changed, 35 insertions(+), 549 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 7b652e791..db11fd85a 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 { diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index f2719ab1f..b7abe63a1 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -371,7 +371,6 @@ extension DatabaseReader { } } -#if compiler(>=5.6) && canImport(_Concurrency) extension DatabaseReader { // MARK: - Asynchronous Database Access @@ -465,7 +464,6 @@ extension DatabaseReader { } } } -#endif #if canImport(Combine) extension DatabaseReader { diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 0b2109089..0f134c4ce 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -356,13 +356,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: diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 86172505b..022a9106d 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -159,11 +159,9 @@ extension DatabaseValue: StatementBinding { 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/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index df7376e20..6b4a8a0ab 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -380,7 +380,6 @@ extension DatabaseWriter { } } -#if compiler(>=5.6) && canImport(_Concurrency) extension DatabaseWriter { // MARK: - Asynchronous Database Access @@ -491,8 +490,6 @@ extension DatabaseWriter { } } } -#endif - #if canImport(Combine) extension DatabaseWriter { diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 5355a6f78..21c756b21 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -2182,12 +2182,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:) 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/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 44df8aa24..90ef03457 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -459,11 +459,7 @@ extension TableRequest where Self: AggregatingRequest { return [Column(rowIDColumn)] } else if primaryKey.tableHasRowID { // Prefer the rowid - #if compiler(>=5.5) return [.rowID] - #else - return [Column.rowID] - #endif } else { // WITHOUT ROWID table: group by primary key columns return primaryKey.columns.map { Column($0) } diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index 4bb52256d..903cf7f7d 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. /// diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index a0fb30551..d65258e86 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1667,12 +1667,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 diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index 8ef622ba9..8f0bd8ab3 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -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/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index bdfb58e3b..58a469288 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -252,7 +252,6 @@ extension ValueObservation: Refinable { } } -#if compiler(>=5.6) && canImport(_Concurrency) extension ValueObservation { // MARK: - Asynchronous Observation /// The database observation, as an asynchronous sequence of @@ -350,7 +349,6 @@ public struct AsyncValueObservation: AsyncSequence { } } } -#endif #if canImport(Combine) extension ValueObservation { diff --git a/Tests/GRDBCombineTests/Support.swift b/Tests/GRDBCombineTests/Support.swift index 88e194c50..89f315cf3 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,9 +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, @@ -127,31 +124,5 @@ public func assertFailure( 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, - file: StaticString = #file, - 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 = #file, - 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) - } -} -#endif #endif diff --git a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift index 7ea9a8095..8d850380e 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 = #filePath, line: UInt = #line) throws { // Test DatabaseRegionConvertible do { @@ -31,27 +31,6 @@ 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 { try dbWriter.write { db in try db.create(table: "a") { t in diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index d16284f8a..674a5003c 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -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/DatabaseValueConversionTests.swift b/Tests/GRDBTests/DatabaseValueConversionTests.swift index 82c246cd0..9b1b091ee 100644 --- a/Tests/GRDBTests/DatabaseValueConversionTests.swift +++ b/Tests/GRDBTests/DatabaseValueConversionTests.swift @@ -34,14 +34,14 @@ private let jpegData = try! Data(contentsOf: Bundle(for: DatabaseValueConversion 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 = #filePath, + line: UInt = #line) throws { func stringRepresentation(_ value: T?) -> String { guard let value = value else { return "nil" } @@ -86,12 +86,12 @@ class DatabaseValueConversionTests : GRDBTestCase { } } - private func _assertFailedDecoding( + private func assertFailedDecoding( _ db: Database, _ sql: String, _ type: T.Type, - file: StaticString, - line: UInt) throws + file: StaticString = #filePath, + line: UInt = #line) throws { // We can only test failed decoding from database value, since // StatementColumnConvertible only supports optimistic decoding which @@ -100,61 +100,6 @@ 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 { diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 5a7b4c433..0ff9e4081 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -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..6f3077f2c 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) } diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index d7f3ff400..6f25c8aa0 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,11 +22,7 @@ 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 diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index 8f322063b..34690bd73 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,11 +22,7 @@ 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 diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index 2e23f03f4..c9068f829 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,11 +23,7 @@ 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 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/ForeignKeyInfoTests.swift b/Tests/GRDBTests/ForeignKeyInfoTests.swift index 483db5179..f9b95d7d7 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 = #filePath, 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..4d16d0979 100644 --- a/Tests/GRDBTests/FoundationDateComponentsTests.swift +++ b/Tests/GRDBTests/FoundationDateComponentsTests.swift @@ -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 = #filePath, 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..16a1038b2 100644 --- a/Tests/GRDBTests/FoundationDateTests.swift +++ b/Tests/GRDBTests/FoundationDateTests.swift @@ -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 = #filePath, + 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 = #filePath, + 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/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 6c0d5b2e4..00f5b44f4 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -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 = #filePath, 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 = #filePath, 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) { + func assert(_ record: EncodableRecord, isEncodedIn row: Row, file: StaticString = #filePath, line: UInt = #line) { let recordDict = 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 = #filePath, 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 = #filePath, 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 = #filePath, 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() @@ -259,7 +202,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/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index e0dfba00d..97523ade9 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -36,11 +36,7 @@ private class Person : Record, Hashable { } required init(row: Row) { - #if compiler(>=5.5) id = row[.rowID] - #else - id = row[Column.rowID] - #endif age = row["age"] name = row["name"] creationDate = row["creationDate"] @@ -48,11 +44,7 @@ private class Person : Record, Hashable { } override func encode(to container: inout PersistenceContainer) { - #if compiler(>=5.5) container[.rowID] = id - #else - container[Column.rowID] = id - #endif container["name"] = name container["age"] = age container["creationDate"] = creationDate 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/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 4db189940..9cfad00dc 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -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], + func assertValueObservationRecordingMatch( + recorded recordedValues: R, + expected expectedValues: E, + allowMissingLastValue: Bool = false, _ 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], - _ 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 = #filePath, + line: UInt = #line) throws where Reducer.Value: Equatable { @@ -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 = #filePath, + line: UInt = #line) throws { func test( @@ -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/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index b7252bb2a..7b9f14f8f 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -741,7 +741,6 @@ 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, *) @@ -936,5 +935,4 @@ class ValueObservationTests: GRDBTestCase { .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } -#endif } From 23cbf13af0ced0ea0abdee97254cb151448f8290 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Jul 2022 13:54:37 +0200 Subject: [PATCH 11/73] Swift 5.7 required: Availability checks --- Documentation/FTS5Tokenizers.md | 2 - GRDB/Core/Database.swift | 82 ++++--------------- .../DatabaseValueConvertible+Encodable.swift | 6 +- .../StandardLibrary/StandardLibrary.swift | 3 - GRDB/Core/WALSnapshot.swift | 29 +------ GRDB/QueryInterface/SQL/SQLFunctions.swift | 3 - GRDB/Record/EncodableRecord.swift | 14 +--- GRDB/Record/FetchableRecord+Decodable.swift | 29 +++---- GRDB/Record/FetchableRecord.swift | 1 - README.md | 2 - .../DatabaseDateDecodingStrategyTests.swift | 79 +++++++++--------- .../DatabaseDateEncodingStrategyTests.swift | 5 -- Tests/GRDBTests/DatabaseFunctionTests.swift | 22 +++-- .../DatabasePoolConcurrencyTests.swift | 16 ---- Tests/GRDBTests/DatabaseQueueTests.swift | 16 ---- Tests/GRDBTests/DatabaseRegionTests.swift | 8 -- Tests/GRDBTests/DatabaseTraceTests.swift | 12 --- .../GRDBTests/FTS5WrapperTokenizerTests.swift | 11 +-- ...tablePersistableRecordEncodableTests.swift | 13 --- .../QueryInterfaceExpressionsTests.swift | 20 ++--- Tests/GRDBTests/ValueObservationTests.swift | 24 +----- 21 files changed, 97 insertions(+), 300 deletions(-) diff --git a/Documentation/FTS5Tokenizers.md b/Documentation/FTS5Tokenizers.md index 14e827be1..1e321a2cc 100644 --- a/Documentation/FTS5Tokenizers.md +++ b/Documentation/FTS5Tokenizers.md @@ -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/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index c6658dece..9e921f29e 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -296,12 +296,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() { @@ -608,16 +605,10 @@ 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 } @@ -626,39 +617,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // 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, 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) + #endif } - #endif // Precondition: configuration.trace != nil private func trace_v2( @@ -690,13 +664,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: @@ -1611,20 +1580,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 } @@ -1643,22 +1604,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 { diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift index 5682ca7c9..e87d799bf 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift @@ -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/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index f2163cd75..69d2a966a 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -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/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index 6b2a2f62d..7bbf523c7 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 } @@ -36,16 +36,7 @@ final class WALSnapshot { init?(_ db: Database) { var snapshot: UnsafeMutablePointer? let code: CInt = withUnsafeMutablePointer(to: &snapshot) { -#if GRDBCUSTOMSQLITE 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 { return nil @@ -54,14 +45,7 @@ final class WALSnapshot { } 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/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 55fc2d5c6..d491eabfb 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -170,7 +170,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 +180,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 +190,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) } diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 9a2c6a21b..1d5a4b685 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -144,10 +144,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 } @@ -366,7 +364,6 @@ 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 @@ -375,7 +372,6 @@ public enum DatabaseDateEncodingStrategy { /// Encodes the result of the user-provided function case custom((Date) -> DatabaseValueConvertible?) - @available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private static let iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime @@ -395,11 +391,7 @@ public enum DatabaseDateEncodingStrategy { case .secondsSince1970: return Int64(floor(date.timeIntervalSince1970)) 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) case .formatted(let formatter): return formatter.string(from: date) case .custom(let format): diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 1932faf37..21d0f6575 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -500,7 +500,6 @@ extension ColumnDecoder: SingleValueDecodingContainer { } } -@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private let iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime @@ -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 { @@ -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.swift b/GRDB/Record/FetchableRecord.swift index ee520c196..004bc9014 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -581,7 +581,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/README.md b/README.md index 35be12298..6ac927ffd 100644 --- a/README.md +++ b/README.md @@ -615,8 +615,6 @@ 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. See [Configuration](http://groue.github.io/GRDB.swift/docs/5.26/Structs/Configuration.html) for more details and configuration options. diff --git a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift index b390ee7b7..331ed23c2 100644 --- a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift @@ -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 } @@ -366,47 +365,45 @@ 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) - } - - // 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") -// } -// } + 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) } + +// 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") +// } +// } } } } diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index 4247fb829..b5b7fa927 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 } @@ -171,10 +170,6 @@ 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) for (date, value) in zip(testedDates, [ 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/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 87ce7c2e0..445d67a39 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 // diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 2e0331844..c1a89bb46 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -125,10 +125,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 +149,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 +174,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 +194,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/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 860ab1d17..853368f79 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -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)") 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/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/MutablePersistableRecordEncodableTests.swift b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift index b67c4c60e..507e3cd01 100644 --- a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift @@ -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/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 7617a1958..dee5bd5f7 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -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/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 7b9f14f8f..3ec80bbac 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -419,20 +419,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 +469,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: "") From 20dcab75c74e3bf5c9c06752aefb10478ba0524c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Jul 2022 14:10:31 +0200 Subject: [PATCH 12/73] Swift 5.7 required: SPM resources --- Package.swift | 11 +++++++-- Tests/GRDBTests/DatabaseQueueTests.swift | 4 ---- .../DatabaseValueConversionTests.swift | 13 +---------- Tests/GRDBTests/GRDBTestCase.swift | 6 +++++ Tests/GRDBTests/InflectionsTests.swift | 23 +------------------ 5 files changed, 17 insertions(+), 40 deletions(-) diff --git a/Package.swift b/Package.swift index e003cb869..5b0cdff70 100644 --- a/Package.swift +++ b/Package.swift @@ -31,11 +31,18 @@ let package = Package( path: "Tests", exclude: [ "CocoaPods", - "CustomSQLite", "Crash", + "CustomSQLite", + "GRDBTests/getThreadsCount.c", + "Info.plist", "Performance", "SPM", - "GRDBTests/getThreadsCount.c", + "generatePerformanceReport.rb", + "parsePerformanceTests.rb", + ], + resources: [ + .copy("GRDBTests/Betty.jpeg"), + .copy("GRDBTests/InflectionsTests.json"), ]) ], swiftLanguageVersions: [.v5] diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index c1a89bb46..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 diff --git a/Tests/GRDBTests/DatabaseValueConversionTests.swift b/Tests/GRDBTests/DatabaseValueConversionTests.swift index 9b1b091ee..aaeb229f4 100644 --- a/Tests/GRDBTests/DatabaseValueConversionTests.swift +++ b/Tests/GRDBTests/DatabaseValueConversionTests.swift @@ -27,10 +27,7 @@ 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 { @@ -288,7 +285,6 @@ class DatabaseValueConversionTests : GRDBTestCase { return .rollback } - #if !SWIFT_PACKAGE // jpegData is turned to Blob try dbQueue.inTransaction { db in @@ -305,7 +301,6 @@ class DatabaseValueConversionTests : GRDBTestCase { try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: jpegData, expectedDatabaseValueConversion: jpegData) return .rollback } - #endif } func testNumericAffinity() throws { @@ -549,7 +544,6 @@ class DatabaseValueConversionTests : GRDBTestCase { return .rollback } - #if !SWIFT_PACKAGE // jpegData is turned to Blob try dbQueue.inTransaction { db in @@ -566,7 +560,6 @@ class DatabaseValueConversionTests : GRDBTestCase { try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: jpegData, expectedDatabaseValueConversion: jpegData) return .rollback } - #endif } func testNoneAffinity() throws { @@ -738,7 +731,6 @@ class DatabaseValueConversionTests : GRDBTestCase { return .rollback } - #if !SWIFT_PACKAGE // jpegData is turned to Blob try dbQueue.inTransaction { db in @@ -755,7 +747,6 @@ class DatabaseValueConversionTests : GRDBTestCase { try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: jpegData, expectedDatabaseValueConversion: jpegData) return .rollback } - #endif } func testNumericAffinity(_ columnName: String) throws { @@ -973,7 +964,6 @@ class DatabaseValueConversionTests : GRDBTestCase { return .rollback } - #if !SWIFT_PACKAGE // jpegData is turned to Blob try dbQueue.inTransaction { db in @@ -990,6 +980,5 @@ class DatabaseValueConversionTests : GRDBTestCase { try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: jpegData, expectedDatabaseValueConversion: jpegData) return .rollback } - #endif } } diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 00f5b44f4..62c981b14 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -167,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 { 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 From 86de843bda955f9bb00368464bc8f6431537b4fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Jul 2022 14:27:54 +0200 Subject: [PATCH 13/73] Swift 5.7 required: Xcode 14 updates --- .../xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme | 2 +- .../xcshareddata/xcschemes/GRDBCombineDemo.xcscheme | 2 +- .../GRDBDemoiOS.xcodeproj/project.pbxproj | 12 ++++++------ .../xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme | 2 +- .../xcshareddata/xcschemes/GRDBDemoiOS.xcscheme | 2 +- GRDB.xcodeproj/project.pbxproj | 10 +++++++++- .../xcshareddata/xcschemes/GRDBOSX.xcscheme | 2 +- .../xcshareddata/xcschemes/GRDBWatchOS.xcscheme | 2 +- .../xcshareddata/xcschemes/GRDBiOS.xcscheme | 2 +- .../xcshareddata/xcschemes/GRDBtvOS.xcscheme | 2 +- GRDBCustom.xcodeproj/project.pbxproj | 8 +++++++- .../xcshareddata/xcschemes/GRDBOSX.xcscheme | 2 +- .../xcshareddata/xcschemes/GRDBiOS.xcscheme | 2 +- .../GRDBProfiling.xcodeproj/project.pbxproj | 6 +++++- .../xcshareddata/xcschemes/GRDBProfiling.xcscheme | 2 +- 15 files changed, 38 insertions(+), 20 deletions(-) diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme index b229953c3..2cc6c09fb 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 @@ Date: Sun, 24 Jul 2022 14:43:55 +0200 Subject: [PATCH 14/73] Swift 5.7 required: SPM testing convenience Make it possible to test SQLITE_ENABLE_FTS5 and SQLITE_ENABLE_PREUPDATE_HOOK with `make test_SPM`. This is very handy because Xcode 14 beta 3 has difficulties testing GRDBCustom. --- Package.swift | 21 +++++++++++++++++++-- Sources/CSQLite/shim.h | 21 +++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index 5b0cdff70..c93cc0850 100644 --- a/Package.swift +++ b/Package.swift @@ -1,8 +1,21 @@ // swift-tools-version:5.7 // The swift-tools-version declares the minimum version of Swift required to build this package. +import Foundation import PackageDescription +// Don't rely on those environment variables. They are ONLY testing conveniences: +// $ SQLITE_ENABLE_FTS5=1 SQLITE_ENABLE_PREUPDATE_HOOK=1 make test_SPM +var swiftSettings: [SwiftSetting] = [] +var cSettings: [CSetting] = [] +if ProcessInfo.processInfo.environment["SQLITE_ENABLE_FTS5"] == "1" { + swiftSettings.append(.define("SQLITE_ENABLE_FTS5")) +} +if ProcessInfo.processInfo.environment["SQLITE_ENABLE_PREUPDATE_HOOK"] == "1" { + swiftSettings.append(.define("SQLITE_ENABLE_PREUPDATE_HOOK")) + cSettings.append(.define("GRDB_SQLITE_ENABLE_PREUPDATE_HOOK")) +} + let package = Package( name: "GRDB", platforms: [ @@ -24,7 +37,9 @@ let package = Package( .target( name: "GRDB", dependencies: ["CSQLite"], - path: "GRDB"), + path: "GRDB", + cSettings: cSettings, + swiftSettings: swiftSettings), .testTarget( name: "GRDBTests", dependencies: ["GRDB"], @@ -43,7 +58,9 @@ let package = Package( resources: [ .copy("GRDBTests/Betty.jpeg"), .copy("GRDBTests/InflectionsTests.json"), - ]) + ], + cSettings: cSettings, + swiftSettings: swiftSettings) ], swiftLanguageVersions: [.v5] ) 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 */ From fe225fe452afc03074770f2a6108f289a36bca8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Aug 2022 12:40:06 +0200 Subject: [PATCH 15/73] BREAKING: Remove deprecated methods --- CHANGELOG.md | 1 + GRDB.xcodeproj/project.pbxproj | 28 +- GRDB/Core/Database+Schema.swift | 20 +- GRDB/Core/Database+Statements.swift | 167 ------ GRDB/Core/DatabaseRegion.swift | 14 +- GRDB/Core/Statement.swift | 6 - GRDB/Core/StatementAuthorizer.swift | 2 +- GRDB/Core/TransactionObserver.swift | 4 +- GRDB/FTS/FTS3.swift | 8 - GRDB/FTS/FTS4.swift | 8 - GRDB/FTS/FTS5.swift | 8 - GRDB/Fixit/GRDB-5.0.swift | 542 ------------------ GRDB/Fixits.swift | 57 ++ .../Association/AssociationAggregate.swift | 115 ---- .../Request/RequestProtocols.swift | 11 - GRDB/QueryInterface/SQL/SQLExpression.swift | 3 - GRDB/QueryInterface/SQL/SQLFunctions.swift | 11 - GRDB/QueryInterface/SQL/SQLSelection.swift | 19 - GRDB/QueryInterface/SQL/Table.swift | 2 +- .../Schema/VirtualTableModule.swift | 20 - .../TableRecord+QueryInterfaceRequest.swift | 9 - GRDB/Record/EncodableRecord.swift | 4 - GRDB/ValueObservation/ValueObservation.swift | 26 - GRDBCustom.xcodeproj/project.pbxproj | 20 +- .../GRDBTests/CompilationProtocolTests.swift | 4 +- Tests/GRDBTests/DatabaseRegionTests.swift | 26 +- ...ValueObservationRegionRecordingTests.swift | 4 +- Tests/GRDBTests/VirtualTableModuleTests.swift | 4 +- 28 files changed, 101 insertions(+), 1042 deletions(-) delete mode 100644 GRDB/Fixit/GRDB-5.0.swift create mode 100644 GRDB/Fixits.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index bef30f951..9790f2751 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -97,6 +97,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: Swift 5.7+ and Xcode 14+ are required. - **Breaking**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ are required. +- **Breaking**: Removed deprecated methods ## 5.26.0 diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 9db71ef11..ad0bfc95d 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -490,6 +490,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 +553,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 */; }; @@ -1025,7 +1026,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 */; }; @@ -1470,6 +1470,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 +1496,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 = ""; }; @@ -2423,14 +2423,6 @@ path = ValueReducer; sourceTree = ""; }; - 56D7E449221595FE0052464B /* Fixit */ = { - isa = PBXGroup; - children = ( - 567ECE4E2222E431009245CA /* GRDB-5.0.swift */, - ); - path = Fixit; - sourceTree = ""; - }; 56DAA2C41DE99D8D006E10C8 /* Cursor */ = { isa = PBXGroup; children = ( @@ -2526,8 +2518,8 @@ isa = PBXGroup; children = ( 56A2FA3524424D2A00E97D23 /* Export.swift */, + 566DDE0C288D763C0000DCFB /* Fixits.swift */, 56A2386F1B9C75030082EB20 /* Core */, - 56D7E449221595FE0052464B /* Fixit */, 5698AC291D9E5A480056AF8C /* FTS */, 56A238911B9C750B0082EB20 /* Migration */, 56300B6D1C53F592005A543B /* QueryInterface */, @@ -2960,6 +2952,7 @@ 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 */, @@ -2997,7 +2990,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 */, @@ -3108,6 +3100,7 @@ 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 */, @@ -3199,7 +3192,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 */, @@ -3717,6 +3709,7 @@ 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 */, @@ -3808,7 +3801,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 */, @@ -4090,6 +4082,7 @@ 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 */, @@ -4176,7 +4169,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 */, diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index a3d242c3e..2bcfb0a7e 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -126,17 +126,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,14 +134,6 @@ 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. public func viewExists(_ name: String) throws -> Bool { try schemaIdentifiers().contains { diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index c91d7fe3d..46e135555 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -60,46 +60,6 @@ extension Database { return statement } - /// 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. /// /// let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0) @@ -202,138 +162,11 @@ 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. /// /// let statements = try db.allStatements(sql: """ diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 0f134c4ce..cadb45156 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -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) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index a994296a1..c6120e06f 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -358,12 +358,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" diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 8f3cbbf00..255dc0a56 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -74,7 +74,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])) diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index ffdd7cf02..be77b89db 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -901,9 +901,9 @@ 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) } diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index 3dd31a534..f36a73f63 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -79,14 +79,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/FTS4.swift b/GRDB/FTS/FTS4.swift index 6166bfad5..726e4c442 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:) diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 3669a52d4..90b3c47a2 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:) 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..333bbb559 --- /dev/null +++ b/GRDB/Fixits.swift @@ -0,0 +1,57 @@ +// Fixits for changes introduced by GRDB 6.0.0 +// swiftlint:disable all + +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() } +} + +extension DatabaseUUIDEncodingStrategy { + @available(*, unavailable, renamed: "uppercaseString") + public static var string: Self { preconditionFailure() } +} + +@available(*, unavailable, renamed: "Statement") +public typealias SelectStatement = Statement + +@available(*, unavailable, renamed: "SQLExpression.AssociativeBinaryOperator") +public typealias SQLAssociativeBinaryOperator = SQLExpression.AssociativeBinaryOperator + +@available(*, unavailable, renamed: "Statement") +public typealias UpdateStatement = Statement + +extension ValueObservation where Reducer == ValueReducers.Auto { + @available(*, unavailable, renamed: "tracking(_:)") + public static func trackingVaryingRegion( + _ fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + { preconditionFailure() } +} + diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index b442506ae..135c0bc8f 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -45,34 +45,6 @@ extension AssociationToMany { .forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") } - /// 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) - @available(*, deprecated, message: "Did you mean average(Column(...))? If not, prefer average(value.databaseValue) instead.") // swiftlint:disable:this line_length - public func average(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression])) - if let column = expression as? ColumnExpression { - 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. /// @@ -100,34 +72,6 @@ extension AssociationToMany { } } - /// Creates an aggregate which evaluate to the maximum value of the given - /// expression in associated records. - /// - /// When the maximized expression is a column, the aggregate has a default - /// name which is "maximum[Key][Column]", where key is the key of the - /// association. For example: - /// - /// For example: - /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var maxPlayerScore: Double - /// } - /// let request = Team.annotated(with: Team.players.max(Column("score"))) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) - /// - /// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db) - @available(*, deprecated, message: "Did you mean max(Column(...))? If not, prefer max(value.databaseValue) instead.") // swiftlint:disable:this line_length - public func max(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression])) - if let column = expression as? ColumnExpression { - 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. /// @@ -155,34 +99,6 @@ extension AssociationToMany { } } - /// Creates an aggregate which evaluate to the minimum value of the given - /// expression in associated records. - /// - /// When the minimized expression is a column, the aggregate has a default - /// name which is "minimum[Key][Column]", where key is the key of the - /// association. For example: - /// - /// For example: - /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var minPlayerScore: Double - /// } - /// let request = Team.annotated(with: Team.players.min(Column("score"))) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) - /// - /// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db) - @available(*, deprecated, message: "Did you mean min(Column(...))? If not, prefer min(value.databaseValue) instead.") // swiftlint:disable:this line_length - public func min(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression])) - if let column = expression as? ColumnExpression { - 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. /// @@ -210,37 +126,6 @@ extension AssociationToMany { } } - /// 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 - /// . - @available(*, deprecated, message: "Did you mean sum(Column(...))? If not, prefer sum(value.databaseValue) instead.") // swiftlint:disable:this line_length - public func sum(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression])) - if let column = expression as? ColumnExpression { - 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. /// diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 90ef03457..782ac2109 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -150,17 +150,6 @@ public protocol FilteredRequest { } 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 diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index d65258e86..72696c126 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -370,9 +370,6 @@ public struct SQLExpression { } } -@available(*, deprecated, renamed: "SQLExpression.AssociativeBinaryOperator") -public typealias SQLAssociativeBinaryOperator = SQLExpression.AssociativeBinaryOperator - // MARK: - Creating Expressions extension SQLExpression { diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index d491eabfb..d2acfc445 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -22,17 +22,6 @@ public func average(_ value: SQLSpecificExpressible) -> SQLExpression { // MARK: - COUNT(...) -/// Returns an expression that evaluates the `COUNT` SQL function. -/// -/// // 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) diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index cd6655582..e37707cb1 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -74,25 +74,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 { diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index b17dcdfd4..722937b6a 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) } } 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+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 78ce4f920..5fdf6e7f1 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -150,15 +150,6 @@ extension TableRecord { 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 diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 1d5a4b685..9ced8258e 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -425,10 +425,6 @@ 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 { switch self { case .deferredToUUID: diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 58a469288..33c11b930 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -747,30 +747,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/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index a47819af8..2dbf1478f 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -35,8 +35,6 @@ 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 */; }; 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 +328,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 */; }; @@ -814,7 +814,6 @@ 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 = ""; }; 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 +976,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 = ""; }; @@ -1303,14 +1303,6 @@ path = ValueObservation; sourceTree = ""; }; - 5614089D221596A100DAD589 /* Fixit */ = { - isa = PBXGroup; - children = ( - 5614089E221596A100DAD589 /* GRDB-5.0.swift */, - ); - path = Fixit; - sourceTree = ""; - }; 5614DEEE1BA9D6F9003163B3 /* Frameworks */ = { isa = PBXGroup; children = ( @@ -1966,8 +1958,8 @@ isa = PBXGroup; children = ( 56A2FA3724424F4200E97D23 /* Export.swift */, + 566DDE11288D76400000DCFB /* Fixits.swift */, 56A2386F1B9C75030082EB20 /* Core */, - 5614089D221596A100DAD589 /* Fixit */, 5698AC291D9E5A480056AF8C /* FTS */, 56A238911B9C750B0082EB20 /* Migration */, 5656A8252295BD56001FF3FF /* QueryInterface */, @@ -2320,6 +2312,7 @@ 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 */, @@ -2416,7 +2409,6 @@ 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 */, @@ -2692,6 +2684,7 @@ 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 */, @@ -2788,7 +2781,6 @@ 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 */, diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index b0bd21231..1c4f259f5 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -153,7 +153,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 +161,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/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 853368f79..64ad3955f 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 { @@ -258,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(*)") } @@ -310,7 +310,7 @@ class DatabaseRegionTests : GRDBTestCase { XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "full database") } else { - let expectedRegion = DatabaseRegion.fullTable("foo") + let expectedRegion = DatabaseRegion(table: "foo") XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(*)") } @@ -322,7 +322,7 @@ class DatabaseRegionTests : GRDBTestCase { XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "full database") } else { - let expectedRegion = DatabaseRegion.fullTable("foo") + let expectedRegion = DatabaseRegion(table: "foo") XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "FOO(*)") } @@ -747,7 +747,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/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/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() } From 6f0d45eedb8aced88e9ee808f356c2240dec8d3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 16 Jan 2022 14:25:36 +0100 Subject: [PATCH 16/73] BREAKING: throwing DatabaseWriter.barrierWriteWithoutTransaction It used to be rethrowing, but it was then unable to deal with closed databases. The async version is modified accordingly: it accepts a Result, instead of a raw Database. DatabaseMigrator.asyncMigrate is impacted as well: it accepts a Result, instead of a (Database, Error?) tuple. --- Documentation/Migrations.md | 7 ++-- GRDB/Core/DatabasePool.swift | 19 +++++++---- GRDB/Core/DatabaseQueue.swift | 6 ++-- GRDB/Core/DatabaseWriter.swift | 20 ++++++------ GRDB/Fixits.swift | 8 +++++ GRDB/Migration/DatabaseMigrator.swift | 23 ++++++------- Tests/GRDBTests/DatabaseMigratorTests.swift | 32 ++++++++++++------- .../DatabasePoolConcurrencyTests.swift | 2 +- 8 files changed, 68 insertions(+), 49 deletions(-) diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index a7d94127a..72915c0bf 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -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/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index db11fd85a..5c670e829 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -651,17 +651,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 = 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 = readerPool else { + updates(.failure(DatabaseError.connectionIsClosed())) + return + } + readerPool.asyncBarrier { + self.writer.sync { updates(.success($0)) } } } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index ed0936f5c..922c357ab 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -309,12 +309,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, diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 6b4a8a0ab..d471eb461 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. @@ -446,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) } }) } } } @@ -754,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) } diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 333bbb559..54a51f0b9 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -33,6 +33,14 @@ extension Database { public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> 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 DatabaseUUIDEncodingStrategy { @available(*, unavailable, renamed: "uppercaseString") public static var string: Self { preconditionFailure() } diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 13ae52339..b7546125f 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -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) + 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)) } } } @@ -477,12 +478,8 @@ extension DatabaseMigrator { { 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() diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index c1384c914..c9945aa36 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -19,9 +19,10 @@ class DatabaseMigratorTests : GRDBTestCase { func test(writer: 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() @@ -125,16 +126,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")) @@ -413,19 +414,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/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 445d67a39..33327ba72 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1304,7 +1304,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { // Wait for read to start s1.wait() - dbPool.barrierWriteWithoutTransaction { _ in } + try! dbPool.barrierWriteWithoutTransaction { _ in } expectation.fulfill() s4.signal() } From 458e1e26756698f2529f76fbe5623a118d2c5c71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 1 Feb 2022 18:49:37 +0100 Subject: [PATCH 17/73] BREAKING: throwing DatabaseQueue() initializer As a consequence, FTS3.tokenize(_:) is a throwing method as well. --- CHANGELOG.md | 1 + .../GRDBAsyncDemo/Persistence.swift | 2 +- .../GRDBAsyncDemoTests/AppDatabaseTests.swift | 16 +-- .../PlayerRequestTests.swift | 4 +- .../GRDBAsyncDemoTests/PlayerTests.swift | 10 +- .../GRDBCombineDemo/Persistence.swift | 2 +- .../AppDatabaseTests.swift | 16 +-- .../PlayerRequestTests.swift | 4 +- .../GRDBCombineDemoTests/PlayerTests.swift | 10 +- .../GRDBDemoiOSTests/AppDatabaseTests.swift | 16 +-- .../GRDBDemoiOSTests/PlayerTests.swift | 10 +- Documentation/GRDB6MigrationGuide.md | 10 ++ .../Associations.playground/Contents.swift | 2 +- .../Contents.swift | 2 +- .../MyPlayground.playground/Contents.swift | 2 +- .../Tour.playground/Contents.swift | 2 +- .../Contents.swift | 2 +- GRDB/Core/Configuration.swift | 4 +- GRDB/Core/Database.swift | 10 +- GRDB/Core/DatabaseFunction.swift | 4 +- GRDB/Core/DatabaseQueue.swift | 7 +- GRDB/FTS/FTS3.swift | 17 ++- GRDB/FTS/FTS3Pattern.swift | 20 +-- GRDB/FTS/FTS5TokenizerDescriptor.swift | 28 ++-- README.md | 2 +- .../GRDBiOS-framework/AppDelegate.swift | 2 +- .../GRDBiOS-static/AppDelegate.swift | 2 +- .../CustomSQLite/AppDelegate.swift | 2 +- .../DatabaseReaderReadPublisherTests.swift | 4 +- .../DatabaseWriterWritePublisherTests.swift | 8 +- .../ValueObservationPublisherTests.swift | 6 +- .../DatabaseConfigurationTests.swift | 2 +- Tests/GRDBTests/DatabaseMigratorTests.swift | 22 +-- .../DatabaseQueueInMemoryTests.swift | 2 +- Tests/GRDBTests/DatabaseReaderTests.swift | 4 +- Tests/GRDBTests/DatabaseWriterTests.swift | 4 +- Tests/GRDBTests/FTS3TokenizerTests.swift | 132 +++++++++--------- Tests/GRDBTests/ValueObservationTests.swift | 10 +- Tests/SPM/ios/ios/AppDelegate.swift | 2 +- Tests/SPM/macos/macos/AppDelegate.swift | 2 +- 40 files changed, 213 insertions(+), 194 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9790f2751..1c34bdc47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -98,6 +98,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: Swift 5.7+ and Xcode 14+ are required. - **Breaking**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ are required. - **Breaking**: Removed deprecated methods +- **Breaking**: The in-memory `DatabaseQueue()` initializer can now throw errors. ## 5.26.0 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/GRDBAsyncDemoTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift index 64fb529f6..fd50726ad 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 @@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase { 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,7 +54,7 @@ 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) @@ -81,7 +81,7 @@ class AppDatabaseTests: XCTestCase { 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) @@ -99,7 +99,7 @@ class AppDatabaseTests: XCTestCase { 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 @@ -111,7 +111,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 @@ -123,7 +123,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/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/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/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/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index 7df94ebe8..cbe504013 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -5,6 +5,7 @@ Migrating From GRDB 5 to GRDB 6 - [Preparing the Migration to GRDB 6](#preparing-the-migration-to-grdb-6) - [New requirements](#new-requirements) +- [Other Changes](#other-changes) ## Preparing the Migration to GRDB 6 @@ -23,3 +24,12 @@ GRDB requirements have been bumped: - **macOS 10.13+** (was macOS 10.10+) - **tvOS 11.0+** (was tvOS 11.0+) - **watchOS 4.0+** (was watchOS 2.0+) + +## Other Changes + +- The initializer of in-memory databases can now throw errors: + + ```diff + -let dbQueue = DatabaseQueue() + +let dbQueue = try DatabaseQueue() + ``` diff --git a/Documentation/Playgrounds/Associations.playground/Contents.swift b/Documentation/Playgrounds/Associations.playground/Contents.swift index fd3fad7b9..66be6ed96 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 diff --git a/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift b/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift index f3b03b89e..fbb1d4377 100644 --- a/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift +++ b/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift @@ -72,7 +72,7 @@ class Bar: Base { //: 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() +let dbQueue = try DatabaseQueue() try dbQueue.write { db in // Database table diff --git a/Documentation/Playgrounds/MyPlayground.playground/Contents.swift b/Documentation/Playgrounds/MyPlayground.playground/Contents.swift index 0819f2496..f815d8f1e 100644 --- a/Documentation/Playgrounds/MyPlayground.playground/Contents.swift +++ b/Documentation/Playgrounds/MyPlayground.playground/Contents.swift @@ -6,7 +6,7 @@ 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? diff --git a/Documentation/Playgrounds/Tour.playground/Contents.swift b/Documentation/Playgrounds/Tour.playground/Contents.swift index 77be71509..c79f27742 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 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/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 7c7e7f0d3..da2e43f2d 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() diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 9e921f29e..f31c08fa8 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 @@ -157,8 +157,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib lazy var observationBroker = DatabaseObservationBroker(self) /// The list of compile options used when building SQLite - static let sqliteCompileOptions: Set = DatabaseQueue().inDatabase { - try! Set(String.fetchCursor($0, 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. @@ -1412,7 +1414,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: /// diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index b71b70ca5..d5b44d60a 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -73,7 +73,7 @@ public final class DatabaseFunction: Hashable { /// } /// } /// - /// 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) @@ -374,7 +374,7 @@ extension DatabaseFunction { /// } /// } /// -/// 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) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 922c357ab..d9f1eaa7a 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") diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index f36a73f63..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]) } 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/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/README.md b/README.md index 6ac927ffd..7d0a4d2ec 100644 --- a/README.md +++ b/README.md @@ -458,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. 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/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..6d312b357 100644 --- a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift @@ -144,7 +144,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } @@ -285,7 +285,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } diff --git a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift index a8fbb14c1..1ef238a31 100644 --- a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift @@ -96,7 +96,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -300,7 +300,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -326,7 +326,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -388,7 +388,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } diff --git a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift index a30ed393a..f74294afb 100644 --- a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift +++ b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift @@ -118,7 +118,7 @@ class ValueObservationPublisherTests : XCTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -225,7 +225,7 @@ class ValueObservationPublisherTests : XCTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -439,7 +439,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/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index 9db22be08..84232185d 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) diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index c9945aa36..1bbc2c5fa 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -10,7 +10,7 @@ class DatabaseMigratorTests : GRDBTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -31,7 +31,7 @@ class DatabaseMigratorTests : GRDBTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -49,7 +49,7 @@ class DatabaseMigratorTests : GRDBTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -94,7 +94,7 @@ class DatabaseMigratorTests : GRDBTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -146,7 +146,7 @@ class DatabaseMigratorTests : GRDBTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -203,7 +203,7 @@ class DatabaseMigratorTests : GRDBTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -230,7 +230,7 @@ class DatabaseMigratorTests : GRDBTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -258,7 +258,7 @@ class DatabaseMigratorTests : GRDBTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -288,7 +288,7 @@ class DatabaseMigratorTests : GRDBTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -319,7 +319,7 @@ class DatabaseMigratorTests : GRDBTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -371,7 +371,7 @@ class DatabaseMigratorTests : GRDBTestCase { } try Test(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } 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/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index 674a5003c..fabe17716 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -3,9 +3,9 @@ import GRDB class DatabaseReaderTests : GRDBTestCase { - func testAnyDatabaseReader() { + func testAnyDatabaseReader() throws { // This test passes if this code compiles. - let reader: DatabaseReader = DatabaseQueue() + let reader: DatabaseReader = try DatabaseQueue() let _: DatabaseReader = AnyDatabaseReader(reader) } diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 0ff9e4081..eda69a5cd 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -148,9 +148,9 @@ class DatabaseWriterTests : GRDBTestCase { try test(makeDatabasePool()) } - func testAnyDatabaseWriter() { + func testAnyDatabaseWriter() throws { // This test passes if this code compiles. - let writer: DatabaseWriter = DatabaseQueue() + let writer: DatabaseWriter = try DatabaseQueue() let _: DatabaseWriter = AnyDatabaseWriter(writer) } 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/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 3ec80bbac..5966543b3 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -757,7 +757,7 @@ class ValueObservationTests: GRDBTestCase { } try await AsyncTest(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -792,7 +792,7 @@ class ValueObservationTests: GRDBTestCase { } try await AsyncTest(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -831,7 +831,7 @@ class ValueObservationTests: GRDBTestCase { } try await AsyncTest(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -867,7 +867,7 @@ class ValueObservationTests: GRDBTestCase { } try await AsyncTest(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @@ -915,7 +915,7 @@ class ValueObservationTests: GRDBTestCase { } try await AsyncTest(test) - .run { DatabaseQueue() } + .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } diff --git a/Tests/SPM/ios/ios/AppDelegate.swift b/Tests/SPM/ios/ios/AppDelegate.swift index e6f48b344..b257fc310 100644 --- a/Tests/SPM/ios/ios/AppDelegate.swift +++ b/Tests/SPM/ios/ios/AppDelegate.swift @@ -4,7 +4,7 @@ import GRDB @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> 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) { From 58293befc9a9588e2f2077c6ec8d2fabcd1e76e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Jul 2022 17:10:56 +0200 Subject: [PATCH 18/73] BREAKING: Optional is a database value like others --- GRDB.xcodeproj/project.pbxproj | 10 + GRDB/Core/DatabaseValueConvertible.swift | 396 +--------------- GRDB/Core/Row.swift | 337 ++++---------- GRDB/Core/RowAdapter.swift | 9 - GRDB/Core/StatementColumnConvertible.swift | 427 ++---------------- ...aseValueConvertible+RawRepresentable.swift | 26 ++ .../Support/StandardLibrary/Optional.swift | 97 ++++ GRDB/Fixits.swift | 6 + .../Request/QueryInterfaceRequest.swift | 21 - .../Request/RequestProtocols.swift | 44 +- GRDB/QueryInterface/SQL/Table.swift | 284 +----------- .../TableRecord+QueryInterfaceRequest.swift | 36 +- GRDB/Record/FetchableRecord+Decodable.swift | 2 + GRDB/Record/FetchableRecord+TableRecord.swift | 99 +--- GRDB/Record/TableRecord.swift | 99 +--- GRDB/Utils/Utils.swift | 12 - GRDBCustom.xcodeproj/project.pbxproj | 6 + README.md | 49 +- Tests/GRDBTests/DatabaseCursorTests.swift | 8 +- .../DatabaseDateEncodingStrategyTests.swift | 91 +++- .../DatabaseUUIDEncodingStrategyTests.swift | 132 +++++- .../DatabaseValueConvertibleFetchTests.swift | 183 +++++++- ...ntable+DatabaseValueConvertibleTests.swift | 132 +++++- .../RecordMinimalPrimaryKeyRowIDTests.swift | 6 + .../RecordPrimaryKeyHiddenRowIDTests.swift | 6 + ...StatementColumnConvertibleFetchTests.swift | 160 ++++++- ...bleRecord+QueryInterfaceRequestTests.swift | 4 + Tests/GRDBTests/TableRecordDeleteTests.swift | 1 + Tests/GRDBTests/TableTests.swift | 19 +- ...rvationDatabaseValueConvertibleTests.swift | 19 +- 30 files changed, 1087 insertions(+), 1634 deletions(-) create mode 100644 GRDB/Core/Support/StandardLibrary/Optional.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index ad0bfc95d..fd65b6bc4 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -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 */; }; @@ -1318,6 +1322,7 @@ 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 = ""; }; @@ -1783,6 +1788,7 @@ 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */, 5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */, 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */, + 5615877F288D875E00A67323 /* Optional.swift */, 5605F1581C672E4000235C62 /* StandardLibrary.swift */, ); path = StandardLibrary; @@ -2945,6 +2951,7 @@ 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 */, @@ -3094,6 +3101,7 @@ 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 */, @@ -3703,6 +3711,7 @@ 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 */, @@ -4076,6 +4085,7 @@ 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 */, diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index a027ecdb5..ef1b454e6 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 @@ -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) } } @@ -162,51 +139,6 @@ public final class DatabaseValueCursor: Databas } } -/// 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))) - } -} - /// DatabaseValueConvertible comes with built-in methods that allow to fetch /// cursors, arrays, or single values: /// @@ -293,7 +225,7 @@ extension DatabaseValueConvertible { 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 } } @@ -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/Row.swift b/GRDB/Core/Row.swift index 21c756b21..c503cc39c 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -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 { @@ -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,20 +320,33 @@ 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 @@ -377,45 +362,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(_ column: Column) -> Value? { - try! decodeIfPresent(Value.self, forKey: column.name) - } - - /// 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[Column("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[Column("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(_ 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. + /// 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[Column("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[Column("missing")] // nil @inlinable public subscript(_ column: Column) -> Value { try! decode(Value.self, forKey: column.name) @@ -426,14 +389,27 @@ 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) -> Value @@ -444,7 +420,7 @@ extension Row { 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 +434,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,13 +449,13 @@ 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 @@ -702,24 +678,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 +695,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 +710,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 +723,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 +745,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 +764,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 +782,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 @@ -2068,11 +1956,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 +2006,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 +2015,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))) } @@ -2269,17 +2141,6 @@ private struct StatementRowImpl: RowImpl { context: RowDecodingContext(statement: statement, index: index)) } - func fastDecodeIfPresent( - _ type: Value.Type, - atUncheckedIndex index: Int) - throws -> Value? - { - try Value.fastDecodeIfPresent( - fromStatement: sqliteStatement, - atUncheckedIndex: Int32(index), - context: RowDecodingContext(statement: statement, index: index)) - } - func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { throw RowDecodingError.valueMismatch(Data.self, statement: statement, index: index) diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index d9505506e..abd7b6c4a 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -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/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 14d5785cc..17be96725 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -19,8 +19,22 @@ /// } /// } public protocol StatementColumnConvertible { + /// Creates a value from a raw SQLite statement pointer, if possible. + /// + /// This method can be called with a NULL database value. + /// + /// - warning: Do not customize the default implementation. + /// + /// - parameters: + /// - sqliteStatement: A pointer to an SQLite statement. + /// - index: The column index. + /// - returns: A decoded value, or, if decoding is impossible, nil. + static func fromStatement( + _ sqliteStatement: SQLiteStatement, + atUncheckedIndex index: Int32) + -> Self? - /// 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: /// @@ -30,18 +44,30 @@ public protocol StatementColumnConvertible { /// } /// } /// - /// 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. /// + /// - 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: Int32) } +extension StatementColumnConvertible { + // `Optional` overrides this default behavior. + /// Default implementation fails on decoding NULL. + @inline(__always) + @inlinable + public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? { + if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { + return nil + } + return self.init(sqliteStatement: sqliteStatement, index: index) + } +} + // MARK: - Conversions extension DatabaseValueConvertible where Self: StatementColumnConvertible { @@ -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( @@ -94,21 +104,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { @inline(__always) @inlinable - static func fastDecodeIfPresent( + static func fastDecode( fromStatement sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32, 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) } } @@ -177,55 +179,6 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible } } -/// 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))) - } -} - /// Types that adopt both DatabaseValueConvertible and /// StatementColumnConvertible can be efficiently initialized from /// database values. @@ -300,8 +253,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { adapter: 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) @@ -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/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift index b49824f5e..07ac9b1f3 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: Int32) { + 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/Optional.swift b/GRDB/Core/Support/StandardLibrary/Optional.swift new file mode 100644 index 000000000..9b77dfda8 --- /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: Int32) -> 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: Int32) { + guard let value = Wrapped(sqliteStatement: sqliteStatement, index: index) else { + return nil + } + self = .some(value) + } +} diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 54a51f0b9..2e48aa6ac 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -46,6 +46,12 @@ extension DatabaseUUIDEncodingStrategy { public static var string: Self { preconditionFailure() } } +@available(*, unavailable, message: "FastNullableDatabaseValueCursor has been replaced with FastDatabaseValueCursor") +typealias FastNullableDatabaseValueCursor = FastDatabaseValueCursor + +@available(*, unavailable, message: "NullableDatabaseValueCursor has been replaced with DatabaseValueCursor") +typealias NullableDatabaseValueCursor = DatabaseValueCursor + @available(*, unavailable, renamed: "Statement") public typealias SelectStatement = Statement diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 83f22d3a3..ca4f82b67 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -185,27 +185,6 @@ where RowDecoder: Identifiable, } } -@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. diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 782ac2109..d3b429401 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -233,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: PrimaryKeyType) -> Self { + if key.databaseValue.isNull { return none() } return filter(keys: [key]) @@ -257,13 +257,13 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { // 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 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) } } @@ -395,38 +395,6 @@ where Self: FilteredRequest, } } -@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 - { - filter(keys: ids) - } -} - extension TableRequest where Self: OrderedRequest { /// Creates a request ordered by primary key. public func orderByPrimaryKey() -> Self { diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 722937b6a..4f4fb6131 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -221,7 +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?) + public func filter(key: PrimaryKeyType) -> QueryInterfaceRequest where PrimaryKeyType: DatabaseValueConvertible { @@ -411,47 +411,6 @@ extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConv } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) -extension Table -where RowDecoder: Identifiable, - RowDecoder.ID: _OptionalProtocol, - RowDecoder.ID.Wrapped: DatabaseValueConvertible -{ - /// Creates a request filtered by primary key. - /// - /// // SELECT * FROM player WHERE id = 1 - /// let table = Table("player") - /// let request = table.filter(id: 1) - /// - /// - parameter id: A primary key - public func filter(id: RowDecoder.ID.Wrapped) -> QueryInterfaceRequest { - all().filter(id: id) - } - - /// Creates a request filtered by primary key. - /// - /// // SELECT * FROM player WHERE id IN (1, 2, 3) - /// let table = Table("player") - /// let request = table.filter(ids: [1, 2, 3]) - /// - /// - parameter ids: A collection of primary keys - public func filter(ids: Collection) - -> QueryInterfaceRequest - where Collection: Swift.Collection, Collection.Element == RowDecoder.ID.Wrapped - { - all().filter(ids: ids) - } - - /// Creates a request which selects the primary key. - /// - /// // SELECT id FROM player - /// let table = Table("player") - /// let request = try table.selectID() - public func selectID() -> QueryInterfaceRequest { - all().selectID() - } -} - extension Table { // MARK: - Counting All @@ -657,72 +616,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 +681,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 { @@ -1369,32 +1190,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) } } @@ -1470,12 +1270,12 @@ extension Table { /// - key: A primary key value. /// - returns: Whether a database row was deleted. @discardableResult - public func deleteOne(_ db: Database, key: PrimaryKeyType?) + public func deleteOne(_ db: Database, key: PrimaryKeyType) throws -> Bool where PrimaryKeyType: DatabaseValueConvertible { - guard let key = key else { - // Avoid hitting the database + if key.databaseValue.isNull { + // Don't hit the database return false } return try deleteAll(db, keys: [key]) > 0 @@ -1539,69 +1339,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 } } diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 5fdf6e7f1..4cbbc74dd 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -165,7 +165,7 @@ extension TableRecord { /// /// // SELECT * FROM player WHERE id = 1 /// let request = Player.filter(key: 1) - public static func filter(key: PrimaryKeyType?) + public static func filter(key: PrimaryKeyType) -> QueryInterfaceRequest where PrimaryKeyType: DatabaseValueConvertible { @@ -380,37 +380,3 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { 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/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 21d0f6575..0920f52eb 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -533,12 +533,14 @@ extension DatabaseDateDecodingStrategy { } } + /// - precondition: value is not NULL fileprivate func decode( fromStatement sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32, 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 { diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index 1dae5ad2d..34de54178 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -133,12 +133,12 @@ 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?) + public static func fetchOne(_ db: Database, key: PrimaryKeyType) throws -> Self? where PrimaryKeyType: DatabaseValueConvertible { - guard let key = key else { - // Avoid hitting the database + if key.databaseValue.isNull { + // Don't hit the database return nil } return try filter(key: key).fetchOne(db) @@ -207,72 +207,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. /// @@ -319,33 +253,6 @@ extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID: } } -@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 - { - if ids.isEmpty { - // Avoid hitting the database - return [] - } - return try filter(ids: ids).fetchSet(db) - } -} - extension FetchableRecord where Self: TableRecord { // MARK: Fetching by Key diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 1e14454ff..c9c265042 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -197,32 +197,11 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// - id: A primary key value. /// - returns: Whether a row 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) } } @@ -299,12 +278,12 @@ extension TableRecord { /// - key: A primary key value. /// - returns: Whether a database row was deleted. @discardableResult - public static func deleteOne(_ db: Database, key: PrimaryKeyType?) + public static func deleteOne(_ db: Database, key: PrimaryKeyType) throws -> Bool where PrimaryKeyType: DatabaseValueConvertible { - guard let key = key else { - // Avoid hitting the database + if key.databaseValue.isNull { + // Don't hit the database return false } return try deleteAll(db, keys: [key]) > 0 @@ -369,68 +348,6 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { } } -@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 { diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 62b20dd37..49ef225c5 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -20,18 +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 { } - // MARK: - Internal /// Reserved for GRDB: do not use. diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 2dbf1478f..3c93e153a 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -35,6 +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 */; }; + 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 */; }; @@ -814,6 +816,7 @@ 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 = ""; }; + 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 = ""; }; @@ -1245,6 +1248,7 @@ 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */, 5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */, 56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */, + 56158784288D878500A67323 /* Optional.swift */, 5605F1581C672E4000235C62 /* StandardLibrary.swift */, ); path = StandardLibrary; @@ -2306,6 +2310,7 @@ 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 */, @@ -2678,6 +2683,7 @@ 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 */, diff --git a/README.md b/README.md index 7d0a4d2ec..d00145668 100644 --- a/README.md +++ b/README.md @@ -1249,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 @@ -1258,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 diff --git a/Tests/GRDBTests/DatabaseCursorTests.swift b/Tests/GRDBTests/DatabaseCursorTests.swift index 8000ee6ef..4faf542cd 100644 --- a/Tests/GRDBTests/DatabaseCursorTests.swift +++ b/Tests/GRDBTests/DatabaseCursorTests.swift @@ -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/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index b5b7fa927..035318b16 100644 --- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -50,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 { @@ -283,6 +288,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) + """) + } } } @@ -321,6 +368,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/DatabaseUUIDEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift index 268ec77e4..5963b00ac 100644 --- a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift @@ -23,14 +23,19 @@ 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 { @@ -226,6 +231,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 +350,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/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/RawRepresentable+DatabaseValueConvertibleTests.swift b/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift index 6d2931bf9..0d1801a28 100644 --- a/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift @@ -25,25 +25,39 @@ 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 { @@ -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/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 270c71ca3..c7bb89bc5 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -599,6 +599,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 +749,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)) + } } } } diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 97523ade9..73553f6ff 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -696,6 +696,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)) + } } } } @@ -849,6 +852,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/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift index f0dbc1a75..87a83c933 100644 --- a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift +++ b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift @@ -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..f30015da6 100644 --- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -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..a04d3e9ca 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -46,6 +46,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) diff --git a/Tests/GRDBTests/TableTests.swift b/Tests/GRDBTests/TableTests.swift index a82d6b723..7645b584d 100644 --- a/Tests/GRDBTests/TableTests.swift +++ b/Tests/GRDBTests/TableTests.swift @@ -134,6 +134,9 @@ 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) """) @@ -250,6 +253,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 +265,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 +313,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 +325,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 +829,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 +937,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/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'") }) } From dd551759789780b691d8c824efeddd67334c7704 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Jul 2022 17:39:11 +0200 Subject: [PATCH 19/73] SE-0345: if let x { } https://github.com/apple/swift-evolution/blob/main/proposals/0345-if-let-shorthand.md --- .../PlayerListViewController.swift | 2 +- GRDB/Core/Database+Statements.swift | 4 +- GRDB/Core/Database.swift | 6 +-- GRDB/Core/DatabasePool.swift | 18 ++++---- GRDB/Core/DatabaseRegion.swift | 18 ++++---- GRDB/Core/RowAdapter.swift | 2 +- GRDB/Core/Statement.swift | 6 +-- .../Foundation/DatabaseDateComponents.swift | 4 +- GRDB/Core/WALSnapshot.swift | 4 +- GRDB/FTS/FTS5.swift | 4 +- GRDB/FTS/FTS5CustomTokenizer.swift | 10 ++--- GRDB/FTS/FTS5Tokenizer.swift | 2 +- GRDB/QueryInterface/FTS3+QueryInterface.swift | 2 +- GRDB/QueryInterface/FTS5+QueryInterface.swift | 2 +- .../Request/RequestProtocols.swift | 2 +- GRDB/Record/FetchableRecord+Decodable.swift | 2 +- GRDB/Record/FetchableRecord+TableRecord.swift | 2 +- GRDB/Utils/Inflections.swift | 2 +- .../ValueConcurrentObserver.swift | 44 ++++++++----------- .../ValueWriteOnlyObserver.swift | 39 +++++++--------- README.md | 2 +- .../PublisherExpectations/Finished.swift | 2 +- Tests/GRDBTests/DatabaseTimestampTests.swift | 2 +- .../DatabaseValueConversionTests.swift | 2 +- 24 files changed, 84 insertions(+), 99 deletions(-) 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/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 46e135555..4ef866d23 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -333,7 +333,7 @@ public class SQLStatementCursor: Cursor { } var statementEnd: UnsafePointer? = nil - let compiledStatement = try Statement( + let statement = try Statement( database: database, statementStart: baseAddress + offset, statementEnd: &statementEnd, @@ -341,7 +341,7 @@ public class SQLStatementCursor: Cursor { offset = statementEnd! - baseAddress - guard let statement = compiledStatement else { + guard let statement else { try checkArgumentsAreEmpty() return nil } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index f31c08fa8..ac1095066 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -373,7 +373,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib func close() throws { SchedulingWatchdog.preconditionValidQueue(self) - guard let sqliteConnection = sqliteConnection else { + guard let sqliteConnection else { // Already closed return } @@ -413,7 +413,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib func close_v2() { SchedulingWatchdog.preconditionValidQueue(self) - guard let sqliteConnection = sqliteConnection else { + guard let sqliteConnection else { // Already closed return } @@ -643,7 +643,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: diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 5c670e829..51fa71730 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -348,7 +348,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 @@ -362,7 +362,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 } @@ -394,7 +394,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 @@ -406,7 +406,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 } @@ -437,7 +437,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 @@ -527,7 +527,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() @@ -620,7 +620,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 } @@ -652,7 +652,7 @@ extension DatabasePool: DatabaseReader { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { - guard let readerPool = readerPool else { + guard let readerPool else { throw DatabaseError.connectionIsClosed() } return try readerPool.barrier { @@ -661,7 +661,7 @@ extension DatabasePool: DatabaseReader { } public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { - guard let readerPool = readerPool else { + guard let readerPool else { updates(.failure(DatabaseError.connectionIsClosed())) return } diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index cadb45156..bf1a51a7d 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 } @@ -87,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] = [:] @@ -105,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) } @@ -125,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] = [:] @@ -170,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) { @@ -183,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) } @@ -207,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 } @@ -253,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 { @@ -328,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) diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index abd7b6c4a..46274d132 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -458,7 +458,7 @@ extension Row { /// Returns self if adapter is nil func adapted(with adapter: RowAdapter?, layout: _RowLayout) throws -> Row { - guard let adapter = adapter else { + guard let adapter else { return self } return try Row(base: self, adapter: adapter._layoutedAdapter(from: layout)) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index c6120e06f..49984acb7 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -115,12 +115,12 @@ 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 @@ -467,7 +467,7 @@ final class StatementCursor: DatabaseCursor { extension Statement { var releasesDatabaseLock: Bool { - guard let transactionEffect = transactionEffect else { + guard let transactionEffect else { return false } diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 20dff9652..075a6f17f 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -76,12 +76,12 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC 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/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index 7bbf523c7..ee216190a 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -38,10 +38,10 @@ final class WALSnapshot { let code: CInt = withUnsafeMutablePointer(to: &snapshot) { return sqlite3_snapshot_get(db.sqliteConnection, "main", $0) } - guard code == SQLITE_OK, let s = snapshot else { + guard code == SQLITE_OK, let snapshot else { return nil } - self.snapshot = s + self.snapshot = snapshot } deinit { diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 90b3c47a2..4ac953388 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -259,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..b52c541c6 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -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,7 +92,7 @@ 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() } @@ -103,7 +103,7 @@ extension Database { tokenizerHandle: UnsafeMutablePointer?) -> Int32 { - guard let constructorPointer = constructorPointer else { + guard let constructorPointer else { return SQLITE_ERROR } let constructor = Unmanaged.fromOpaque(constructorPointer).takeUnretainedValue() @@ -119,7 +119,7 @@ extension Database { } func xDeleteTokenizer(tokenizerPointer: OpaquePointer?) { - guard let tokenizerPointer = tokenizerPointer else { return } + guard let tokenizerPointer else { return } Unmanaged.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).release() } @@ -133,7 +133,7 @@ extension Database { tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer?, Int32, Int32, Int32) -> Int32)?) -> Int32 { - guard let tokenizerPointer = tokenizerPointer else { + guard let tokenizerPointer else { return SQLITE_ERROR } let object = Unmanaged diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index 551270802..ac93e776d 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -128,7 +128,7 @@ extension FTS5Tokenizer { pText: pText, nText: nText, tokenCallback: { (contextPointer, flags, pToken, nToken, _ /* iStart */, _ /* iEnd */) -> Int32 in - guard let contextPointer = contextPointer else { + guard let contextPointer else { return SQLITE_ERROR } 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/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index d3b429401..28919133b 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -306,7 +306,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// /// - parameter key: A unique key public func filter(key: [String: DatabaseValueConvertible?]?) -> Self { - guard let key = key else { + guard let key else { return none() } return filter(keys: [key]) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 0920f52eb..73b51064b 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -150,7 +150,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 } diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index 34de54178..ba17b07cd 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -315,7 +315,7 @@ extension FetchableRecord where Self: TableRecord { /// - 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 { + guard let key else { // Avoid hitting the database return nil } 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/ValueObservation/ValueConcurrentObserver.swift b/GRDB/ValueObservation/ValueConcurrentObserver.swift index 57728ea2f..98b3f06ef 100644 --- a/GRDB/ValueObservation/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/ValueConcurrentObserver.swift @@ -192,11 +192,10 @@ final class ValueConcurrentObserver { 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 { + 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") @@ -351,9 +350,8 @@ extension ValueConcurrentObserver { // 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 */ } + let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } + guard let onChange else { return /* Cancelled */ } onChange(initialValue) } } @@ -380,9 +378,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 @@ -394,7 +391,7 @@ extension ValueConcurrentObserver { // and keeps WAL snapshots (`sqlite3_snapshot`) valid // and comparable. let isModified: Bool = withExtendedLifetime(initialSnapshot) { - guard let initialWALSnapshot = initialWALSnapshot, + guard let initialWALSnapshot, let currentWALSnapshot = WALSnapshot(writerDB) else { return true @@ -443,9 +440,8 @@ extension ValueConcurrentObserver { // 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 */ } + let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } + guard let onChange else { return /* Cancelled */ } onChange(value) } } @@ -489,13 +485,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?() @@ -567,9 +562,8 @@ extension ValueConcurrentObserver: TransactionObserver { // 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 +587,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 +608,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: ValueObservationEvents? = 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/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/ValueWriteOnlyObserver.swift index 440a17ec4..d1d114b8c 100644 --- a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/ValueWriteOnlyObserver.swift @@ -152,11 +152,10 @@ 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) + 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") @@ -248,9 +247,8 @@ extension ValueWriteOnlyObserver { // 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 */ } + let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } + guard let onChange else { return /* Cancelled */ } onChange(initialValue) } } @@ -270,11 +268,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 +335,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?() @@ -394,9 +390,8 @@ extension ValueWriteOnlyObserver: TransactionObserver { // 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) } } @@ -417,21 +412,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): (ValueObservationEvents?, 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 +433,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: ValueObservationEvents? = 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/README.md b/README.md index d00145668..c8fb63e25 100644 --- a/README.md +++ b/README.md @@ -6202,7 +6202,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. 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/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/DatabaseValueConversionTests.swift b/Tests/GRDBTests/DatabaseValueConversionTests.swift index aaeb229f4..022977cce 100644 --- a/Tests/GRDBTests/DatabaseValueConversionTests.swift +++ b/Tests/GRDBTests/DatabaseValueConversionTests.swift @@ -41,7 +41,7 @@ class DatabaseValueConversionTests : GRDBTestCase { 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) } From c0c6b34869c309523f00bc91e973028085a9159a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Jul 2022 18:01:50 +0200 Subject: [PATCH 20/73] SE-0346: primary associated types --- CHANGELOG.md | 1 + Documentation/AssociationsBasics.md | 8 ++++---- .../GRDBAsyncDemo/GRDBAsyncDemo/Player.swift | 2 +- .../GRDBCombineDemo/Player.swift | 2 +- .../GRDBDemoiOS/GRDBDemoiOS/Player.swift | 2 +- Documentation/GRDB6MigrationGuide.md | 17 +++++++++++++++++ .../GoodPracticesForDesigningRecordTypes.md | 8 ++++---- Documentation/QueryInterfaceOrganization.md | 8 ++++---- GRDB/Core/Cursor.swift | 2 +- GRDB/Core/FetchRequest.swift | 2 +- .../Request/RequestProtocols.swift | 10 +++++----- Tests/GRDBTests/DerivableRequestTests.swift | 4 ++-- 12 files changed, 42 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c34bdc47..6502c6b20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -99,6 +99,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ are required. - **Breaking**: Removed deprecated methods - **Breaking**: The in-memory `DatabaseQueue()` initializer can now throw errors. +- **New**: 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). ## 5.26.0 diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 5dd37e5ff..e59ab6534 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -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)) @@ -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/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift index 9bd337573..609df14a0 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift @@ -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/GRDBCombineDemo/Player.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift index 9bd337573..609df14a0 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift @@ -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/GRDBDemoiOS/GRDBDemoiOS/Player.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift index b905e6138..cacb7112d 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift @@ -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/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index cbe504013..27d97f938 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -5,6 +5,7 @@ Migrating 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) - [Other Changes](#other-changes) @@ -25,6 +26,22 @@ GRDB requirements have been bumped: - **tvOS 11.0+** (was tvOS 11.0+) - **watchOS 4.0+** (was watchOS 2.0+) +## 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)) + } + } +``` + +The `Cursor` protocol has also gained a primary associated type (the type of its elements). + ## Other Changes - The initializer of in-memory databases can now throw errors: diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 406cbce75..e708cc4f7 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -299,8 +299,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 +342,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) 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/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index bc4fdc94b..5aafa7af2 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -234,7 +234,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 diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index b474d1aef..c66ed2373 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -10,7 +10,7 @@ /// 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 diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 28919133b..524c198c2 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: @@ -619,7 +619,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. @@ -747,9 +747,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. /// diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift index 6f3077f2c..fb360a85d 100644 --- a/Tests/GRDBTests/DerivableRequestTests.swift +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -74,7 +74,7 @@ private var libraryMigrator: DatabaseMigrator = { }() // Define DerivableRequest extensions -extension DerivableRequest where RowDecoder == Author { +extension DerivableRequest { // SelectionRequest func selectCountry() -> Self { select(Column("country")) @@ -93,7 +93,7 @@ extension DerivableRequest where RowDecoder == Author { } } -extension DerivableRequest where RowDecoder == Book { +extension DerivableRequest { // OrderedRequest func orderByTitle() -> Self { order(Column("title").collating(.localizedCaseInsensitiveCompare)) From a9fcf1b9c1d87d99bcf129a4f411ef14c6a2799a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Mar 2022 13:29:05 +0200 Subject: [PATCH 21/73] SE-0335, SE-0341, SE-0346, SE-0352, SE-0358: some, any, primary associated types --- .../GRDBAsyncDemo/AppDatabase.swift | 4 +- .../GRDBCombineDemo/AppDatabase.swift | 4 +- .../GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift | 4 +- Documentation/FTS5Tokenizers.md | 10 +- Documentation/SQLInterpolation.md | 2 +- GRDB/Core/Cursor.swift | 20 ++- GRDB/Core/Database+Schema.swift | 10 +- GRDB/Core/DatabaseFunction.swift | 30 ++--- GRDB/Core/DatabasePool.swift | 4 +- GRDB/Core/DatabaseQueue.swift | 2 +- GRDB/Core/DatabaseReader.swift | 14 +-- GRDB/Core/DatabaseRegion.swift | 6 +- GRDB/Core/DatabaseRegionObservation.swift | 24 ++-- GRDB/Core/DatabaseSnapshot.swift | 2 +- GRDB/Core/DatabaseValue.swift | 4 +- GRDB/Core/DatabaseValueConvertible.swift | 26 ++-- GRDB/Core/DatabaseWriter.swift | 12 +- GRDB/Core/FetchRequest.swift | 17 ++- GRDB/Core/Row.swift | 64 +++++----- GRDB/Core/RowAdapter.swift | 52 ++++---- GRDB/Core/SQL.swift | 4 +- GRDB/Core/SQLRequest.swift | 12 +- GRDB/Core/Statement.swift | 24 ++-- GRDB/Core/StatementColumnConvertible.swift | 26 ++-- .../DatabaseValueConvertible+Decodable.swift | 4 +- .../DatabaseValueConvertible+Encodable.swift | 6 +- .../StandardLibrary/JSONRequiredEncoder.swift | 4 +- GRDB/Core/TransactionObserver.swift | 32 ++--- GRDB/FTS/FTS5CustomTokenizer.swift | 2 +- GRDB/FTS/FTS5Tokenizer.swift | 2 +- GRDB/FTS/FTS5WrapperTokenizer.swift | 4 +- GRDB/Migration/DatabaseMigrator.swift | 11 +- GRDB/QueryInterface/ForeignKey.swift | 2 +- .../Request/Association/Association.swift | 14 +-- .../Association/AssociationAggregate.swift | 100 +++++++-------- .../Request/CommonTableExpression.swift | 20 +-- .../Request/QueryInterfaceRequest.swift | 34 +++--- .../Request/RequestProtocols.swift | 50 ++++---- GRDB/QueryInterface/SQL/Column.swift | 2 +- GRDB/QueryInterface/SQL/SQLExpression.swift | 12 +- GRDB/QueryInterface/SQL/SQLFunctions.swift | 24 ++-- GRDB/QueryInterface/SQL/SQLOperators.swift | 111 +++++++++-------- GRDB/QueryInterface/SQL/SQLSelection.swift | 2 +- GRDB/QueryInterface/SQL/SQLSubquery.swift | 2 +- GRDB/QueryInterface/SQL/Table.swift | 61 ++++------ .../SQLGeneration/SQLGenerationContext.swift | 6 +- .../SQLGeneration/SQLQueryGenerator.swift | 6 +- .../SQLInterpolation+QueryInterface.swift | 73 +++++------ .../Schema/TableDefinition.swift | 12 +- .../TableRecord+Association.swift | 2 +- .../TableRecord+QueryInterfaceRequest.swift | 35 +++--- GRDB/Record/EncodableRecord+Encodable.swift | 16 +-- GRDB/Record/EncodableRecord.swift | 40 +++--- GRDB/Record/FetchableRecord+Decodable.swift | 16 +-- GRDB/Record/FetchableRecord+TableRecord.swift | 35 ++---- GRDB/Record/FetchableRecord.swift | 30 +++-- GRDB/Record/PersistableRecord.swift | 12 +- GRDB/Record/Record.swift | 6 +- GRDB/Record/TableRecord.swift | 30 ++--- GRDB/Utils/OrderedDictionary.swift | 20 ++- .../DatabaseCancellable.swift | 4 +- .../SharedValueObservation.swift | 8 +- .../ValueConcurrentObserver.swift | 2 +- GRDB/ValueObservation/ValueObservation.swift | 25 ++-- .../ValueObservationScheduler.swift | 4 +- .../ValueWriteOnlyObserver.swift | 2 +- README.md | 16 +-- TODO.md | 2 + .../DatabaseReaderReadPublisherTests.swift | 66 +++++----- ...abaseRegionObservationPublisherTests.swift | 18 ++- .../DatabaseWriterWritePublisherTests.swift | 115 ++++++++---------- .../ValueObservationPublisherTests.swift | 90 ++++++-------- .../GRDBTests/AssociationAggregateTests.swift | 2 +- ...ciationBelongsToDecodableRecordTests.swift | 2 +- ...ciationBelongsToFetchableRecordTests.swift | 2 +- .../AssociationBelongsToRowScopeTests.swift | 2 +- ...sociationBelongsToSQLDerivationTests.swift | 2 +- .../AssociationChainRowScopesTests.swift | 2 +- .../GRDBTests/AssociationChainSQLTests.swift | 2 +- .../AssociationHasManyOrderingTests.swift | 2 +- ...sociationHasManyThroughOrderingTests.swift | 2 +- .../AssociationHasOneSQLDerivationTests.swift | 2 +- ...ionHasOneThroughDecodableRecordTests.swift | 2 +- ...ionHasOneThroughFetchableRecordTests.swift | 2 +- ...ssociationHasOneThroughRowScopeTests.swift | 2 +- ...ationHasOneThroughSQLDerivationTests.swift | 2 +- ...ociationParallelDecodableRecordTests.swift | 2 +- .../AssociationParallelRowScopesTests.swift | 2 +- .../AssociationParallelSQLTests.swift | 2 +- ...ciationPrefetchingCodableRecordTests.swift | 2 +- ...ationPrefetchingFetchableRecordTests.swift | 2 +- ...sociationPrefetchingObservationTests.swift | 2 +- .../AssociationPrefetchingRowTests.swift | 2 +- .../AssociationPrefetchingSQLTests.swift | 2 +- .../AssociationRowScopeSearchTests.swift | 2 +- .../AssociationTableAliasTestsSQLTests.swift | 2 +- Tests/GRDBTests/BackupTestCase.swift | 8 +- .../GRDBTests/CompilationSubClassTests.swift | 2 +- .../DatabaseAbortedTransactionTests.swift | 8 +- Tests/GRDBTests/DatabaseMigratorTests.swift | 99 +++++++-------- Tests/GRDBTests/DatabasePoolBackupTests.swift | 8 +- .../GRDBTests/DatabaseQueueBackupTests.swift | 8 +- Tests/GRDBTests/DatabaseReaderTests.swift | 4 +- Tests/GRDBTests/DatabaseSavepointTests.swift | 2 +- .../DatabaseValueConversionTests.swift | 2 +- Tests/GRDBTests/DatabaseWriterTests.swift | 16 +-- Tests/GRDBTests/FTS3PatternTests.swift | 2 +- Tests/GRDBTests/FTS3RecordTests.swift | 2 +- Tests/GRDBTests/FTS4RecordTests.swift | 2 +- Tests/GRDBTests/FTS5PatternTests.swift | 2 +- Tests/GRDBTests/FTS5RecordTests.swift | 2 +- ...bleRecord+QueryInterfaceRequestTests.swift | 2 +- .../FoundationDateComponentsTests.swift | 2 +- Tests/GRDBTests/FoundationDateTests.swift | 2 +- Tests/GRDBTests/FoundationNSDateTests.swift | 2 +- Tests/GRDBTests/GRDBTestCase.swift | 4 +- Tests/GRDBTests/JoinSupportTests.swift | 2 +- ...MutablePersistableRecordChangesTests.swift | 2 +- .../MutablePersistableRecordTests.swift | 2 +- Tests/GRDBTests/PersistableRecordTests.swift | 2 +- .../QueryInterfaceExpressionsTests.swift | 2 +- .../QueryInterfacePromiseTests.swift | 2 +- .../QueryInterfaceRequestTests.swift | 2 +- ...ntable+DatabaseValueConvertibleTests.swift | 2 +- .../Record+QueryInterfaceRequestTests.swift | 2 +- Tests/GRDBTests/RecordEditedTests.swift | 2 +- ...imalNonOptionalPrimaryKeySingleTests.swift | 2 +- .../RecordMinimalPrimaryKeyRowIDTests.swift | 2 +- .../RecordMinimalPrimaryKeySingleTests.swift | 2 +- .../RecordPrimaryKeyHiddenRowIDTests.swift | 2 +- .../RecordPrimaryKeyMultipleTests.swift | 2 +- .../GRDBTests/RecordPrimaryKeyNoneTests.swift | 2 +- .../RecordPrimaryKeyRowIDTests.swift | 2 +- .../RecordPrimaryKeySingleTests.swift | 2 +- ...leWithReplaceConflictResolutionTests.swift | 2 +- Tests/GRDBTests/RecordSubClassTests.swift | 2 +- .../RecordWithColumnNameManglingTests.swift | 2 +- Tests/GRDBTests/SQLRequestTests.swift | 2 +- Tests/GRDBTests/SelectStatementTests.swift | 2 +- .../StatementArguments+FoundationTests.swift | 2 +- Tests/GRDBTests/StatementArgumentsTests.swift | 2 +- ...bleRecord+QueryInterfaceRequestTests.swift | 2 +- Tests/GRDBTests/TableRecordDeleteTests.swift | 2 +- Tests/GRDBTests/UpdateStatementTests.swift | 2 +- .../ValueObservationPrintTests.swift | 24 ++-- .../GRDBTests/ValueObservationRecorder.swift | 16 +-- Tests/GRDBTests/ValueObservationTests.swift | 61 +++++----- 147 files changed, 907 insertions(+), 1044 deletions(-) diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift index 9caff8c4c..69cd51d96 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift @@ -7,7 +7,7 @@ import GRDB /// 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/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift index e536c8def..955febbcb 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift @@ -8,7 +8,7 @@ import GRDB /// 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/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index 3abba5a5a..db00ee36f 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -6,7 +6,7 @@ import GRDB /// 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/FTS5Tokenizers.md b/Documentation/FTS5Tokenizers.md index 1e321a2cc..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()) 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/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 5aafa7af2..6b65a64ab 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -19,7 +19,7 @@ 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 @@ -36,7 +36,7 @@ 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) // Prefer `forEach` over `next()` looping, as a slight performance @@ -112,9 +112,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 +142,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 +163,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 +181,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 @@ -685,14 +681,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 2bcfb0a7e..9d7931178 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -363,11 +363,10 @@ 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( + 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 } @@ -611,11 +610,10 @@ extension Database { /// 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, + 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 { diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index d5b44d60a..4c0dd8fb8 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -43,7 +43,7 @@ public final class DatabaseFunction: Hashable { _ name: String, argumentCount: Int32? = nil, pure: Bool = false, - function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) + function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?) { self.identity = Identity(name: name, nArg: argumentCount ?? -1) self.pure = pure @@ -68,7 +68,7 @@ public final class DatabaseFunction: Hashable { /// } /// } /// - /// func finalize() -> DatabaseValueConvertible? { + /// func finalize() -> (any DatabaseValueConvertible)? { /// return sum /// } /// } @@ -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: (Int32, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)? + init(compute: @escaping (Int32, 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((Int32, 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 /// @@ -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) @@ -369,7 +371,7 @@ extension DatabaseFunction { /// } /// } /// -/// func finalize() -> DatabaseValueConvertible? { +/// func finalize() -> (any DatabaseValueConvertible)? { /// return sum /// } /// } @@ -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 51fa71730..4b98d3fcb 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -730,7 +730,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 @@ -761,7 +761,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 d9f1eaa7a..9e3156263 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -348,7 +348,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 b7abe63a1..719412ede 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -281,14 +281,14 @@ public protocol DatabaseReader: AnyObject, Sendable { /// 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,7 +341,7 @@ 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, + to writer: some DatabaseWriter, pagesPerStep: Int32 = -1, progress: ((DatabaseBackupProgress) throws -> Void)? = nil) throws @@ -555,7 +555,7 @@ extension DatabaseReader { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { if scheduler.immediateInitialValue() { do { @@ -599,10 +599,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 } @@ -651,7 +651,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 bf1a51a7d..02027d078 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -369,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: @@ -388,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..2c30a578f 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -45,7 +45,7 @@ extension DatabaseRegionObservation { /// deallocated. See the `extent` property for more information. /// /// - parameter regions: A list of observed regions. - public init(tracking regions: DatabaseRegionConvertible...) { + public init(tracking regions: any DatabaseRegionConvertible...) { self.init(tracking: regions) } @@ -68,7 +68,7 @@ extension DatabaseRegionObservation { /// deallocated. See the `extent` property for more information. /// /// - parameter regions: A list of observed regions. - public init(tracking regions: [DatabaseRegionConvertible]) { + public init(tracking regions: [any DatabaseRegionConvertible]) { self.init( extent: .observerLifetime, observedRegion: DatabaseRegion.union(regions)) @@ -79,18 +79,18 @@ extension DatabaseRegionObservation { /// 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. + /// - parameter writer: A DatabaseWriter. /// - parameter onChange: A closure that is provided a database connection /// with write access each time the observed region has been modified. /// - returns: a TransactionObserver public func start( - in dbWriter: DatabaseWriter, + in writer: some DatabaseWriter, onChange: @escaping (Database) -> Void) - throws -> TransactionObserver + throws -> any TransactionObserver { // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. - return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in + try writer.unsafeReentrantWrite { db in let region = try observedRegion(db).observableRegion(db) let observer = DatabaseRegionObserver(region: region, onChange: onChange) db.add(transactionObserver: observer, extent: extent) @@ -111,7 +111,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 +160,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 +183,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 } @@ -211,7 +211,7 @@ extension DatabasePublishers { private var lock = NSRecursiveLock() // Allow re-entrancy init( - writer: DatabaseWriter, + writer: some DatabaseWriter, observation: DatabaseRegionObservation, downstream: Downstream) { 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 022a9106d..e85f3013a 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 diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index ef1b454e6..ae15394cf 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -110,7 +110,7 @@ public final class DatabaseValueCursor: Databas public var _isDone = false private let columnIndex: Int32 - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + 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 @@ -178,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) @@ -198,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)) @@ -221,7 +221,7 @@ 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 @@ -245,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)) @@ -279,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)) @@ -300,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)) @@ -324,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)) @@ -347,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)) @@ -438,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 /// ... @@ -458,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. @@ -473,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. @@ -487,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. diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index d471eb461..05661e450 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -288,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) } } @@ -367,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( @@ -685,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 } @@ -782,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 c66ed2373..56804c8e8 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -4,7 +4,8 @@ /// 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 @@ -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 c503cc39c..dfb738a66 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 } @@ -274,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: @@ -353,7 +353,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(_ column: Column) -> DatabaseValueConvertible? { + public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? { self[column.name] } @@ -380,7 +380,7 @@ extension Row { /// let row = try Row.fetchOne(db, sql: "SELECT ...")! /// let name: String? = row[Column("missing")] // nil @inlinable - public subscript(_ column: Column) -> Value { + public subscript(_ column: some ColumnExpression) -> Value { try! decode(Value.self, forKey: column.name) } @@ -411,11 +411,9 @@ extension Row { /// 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) } @@ -460,7 +458,7 @@ extension Row { /// /// The returned data does not owns its bytes: it must not be used longer /// than the row's lifetime. - public func dataNoCopy(_ column: Column) -> Data? { + public func dataNoCopy(_ column: some ColumnExpression) -> Data? { try! decodeDataNoCopyIfPresent(forKey: column.name) } } @@ -1094,7 +1092,7 @@ public final class RowCursor: DatabaseCursor { public var _isDone = false @usableFromInline let _row: Row // Reused for performance - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + 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) @@ -1149,7 +1147,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) @@ -1169,7 +1167,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. @@ -1190,7 +1188,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. @@ -1211,7 +1209,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) @@ -1258,7 +1256,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)) @@ -1283,7 +1281,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)) @@ -1308,7 +1306,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)) @@ -1333,7 +1331,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)) @@ -1441,7 +1439,7 @@ extension FetchRequest where RowDecoder == Row { /// 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] @@ -1470,7 +1468,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. @@ -1482,7 +1480,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. @@ -1494,7 +1492,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. @@ -1698,13 +1696,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 } @@ -1712,7 +1710,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 @@ -2026,9 +2024,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) } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index 46274d132..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,12 +452,12 @@ 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 { + func adapted(with adapter: (any RowAdapter)?, layout: some _RowLayout) throws -> Row { guard let adapter else { return self } @@ -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 diff --git a/GRDB/Core/SQL.swift b/GRDB/Core/SQL.swift index 19891d08b..3f9ae00d9 100644 --- a/GRDB/Core/SQL.swift +++ b/GRDB/Core/SQL.swift @@ -96,7 +96,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 +172,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 /// } /// diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 04bca77e7..ae6bf582a 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, @@ -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/Statement.swift b/GRDB/Core/Statement.swift index 49984acb7..d37880152 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -250,7 +250,7 @@ public final class Statement { } // 1-based index - func bind(_ 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. @@ -601,12 +601,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() } @@ -618,7 +618,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() } @@ -649,12 +649,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() } @@ -662,14 +662,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 @@ -685,7 +683,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 @@ -904,7 +902,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) } } @@ -917,7 +915,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) } } diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 17be96725..7a2d458b7 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -149,7 +149,7 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible public var _isDone = false @usableFromInline let columnIndex: Int32 - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + 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 @@ -210,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) @@ -230,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)) @@ -250,7 +250,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Self? { // fetchOne handles both a missing row, and one row with a NULL value. @@ -277,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)) @@ -311,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)) @@ -332,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)) @@ -353,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)) @@ -376,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)) @@ -466,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 /// ... @@ -486,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. @@ -501,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. @@ -515,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. 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 e87d799bf..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] = [:] 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/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index be77b89db..4e61b3ede 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -10,7 +10,7 @@ extension Database { /// the observer lifetime (observation lasts until observer /// is deallocated). public func add( - transactionObserver: TransactionObserver, + transactionObserver: some TransactionObserver, extent: TransactionObservationExtent = .observerLifetime) { SchedulingWatchdog.preconditionValidQueue(self) @@ -24,7 +24,7 @@ extension Database { } /// Remove a transaction observer. - public func remove(transactionObserver: TransactionObserver) { + public func remove(transactionObserver: some TransactionObserver) { SchedulingWatchdog.preconditionValidQueue(self) // Drop cached statements that delete, because the removal of an @@ -193,15 +193,15 @@ 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) { + func disableUntilNextTransaction(transactionObserver: some TransactionObserver) { if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) { observation.isDisabled = true statementObservations.removeFirst { $0.0 === observation } @@ -804,15 +804,15 @@ final class TransactionObservation { // It is still interested in transactions commits & rollbacks. var isDisabled = false - 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,7 +825,7 @@ final class TransactionObservation { } } - func isWrapping(_ observer: TransactionObserver) -> Bool { + func isWrapping(_ observer: some TransactionObserver) -> Bool { self.observer === observer } @@ -950,7 +950,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 +976,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 @@ -1142,7 +1142,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 +1168,7 @@ public struct DatabasePreUpdateEvent { tableNameCString: tableNameCString)) } - private let impl: DatabasePreUpdateEventImpl + private let impl: any DatabasePreUpdateEventImpl } extension DatabasePreUpdateEvent: DatabaseEventProtocol { @@ -1336,7 +1336,7 @@ enum DatabaseEventPredicate { // Only events that match observedKinds case matching(observedKinds: [DatabaseEventKind], advertisedKinds: [DatabaseEventKind]) - func evaluate(_ event: DatabaseEventProtocol) -> Bool { + func evaluate(_ event: some DatabaseEventProtocol) -> Bool { switch self { case .true: return true @@ -1372,7 +1372,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/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index b52c541c6..9d3bb4500 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -139,7 +139,7 @@ extension Database { 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 ac93e776d..54ca29223 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -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/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index dfee9e0bd..ac2a46e39 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -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 diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index b7546125f..a4c3be606 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) } @@ -228,7 +228,7 @@ public struct DatabaseMigrator { /// 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, + _ writer: some DatabaseWriter, completion: @escaping (Result) -> Void) { writer.asyncBarrierWriteWithoutTransaction { dbResult in @@ -456,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) } @@ -472,9 +472,8 @@ 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 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..a78763445 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 diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 135c0bc8f..966308a71 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -62,9 +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) - public func average(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + public func average(_ expression: some 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 { @@ -89,9 +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) - public func max(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + public func max(_ expression: some 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 { @@ -116,9 +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) - public func min(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + public func min(_ expression: some 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 { @@ -146,9 +146,9 @@ extension AssociationToMany { /// /// This aggregate invokes the `SUM` SQL function. See also `total(_:)`, and /// . - public func sum(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + public func sum(_ expression: some 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 { @@ -176,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. @@ -249,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) } } @@ -287,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) } } @@ -305,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") } } @@ -324,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.* @@ -357,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)) } } @@ -387,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) @@ -434,7 +424,7 @@ public func && ( /// :nodoc: public func && ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 && rhs } @@ -443,7 +433,7 @@ public func && ( // TODO: test /// :nodoc: public func && ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -468,7 +458,7 @@ public func || ( /// :nodoc: public func || ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 || rhs } @@ -477,7 +467,7 @@ public func || ( // TODO: test /// :nodoc: public func || ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -506,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 } @@ -518,7 +508,7 @@ public func == ( /// /// Author.having(3 == Author.books.count) public func == ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -563,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 } @@ -575,7 +565,7 @@ public func != ( /// /// Author.having(3 != Author.books.count) public func != ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -620,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 } @@ -632,7 +622,7 @@ public func === ( /// /// Author.having(3 === Author.books.count) public func === ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -659,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 } @@ -671,7 +661,7 @@ public func !== ( /// /// Author.having(3 !== Author.books.count) public func !== ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -700,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 } @@ -712,7 +702,7 @@ public func <= ( /// /// Author.having(3 <= Author.books.count) public func <= ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -739,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 } @@ -751,7 +741,7 @@ public func < ( /// /// Author.having(3 < Author.books.count) public func < ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -778,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 } @@ -790,7 +780,7 @@ public func > ( /// /// Author.having(3 > Author.books.count) public func > ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -817,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 } @@ -829,7 +819,7 @@ public func >= ( /// /// Author.having(3 >= Author.books.count) public func >= ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -867,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 } @@ -879,7 +869,7 @@ public func + ( /// /// Author.annotated(with: 1 + Author.books.count) public func + ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -906,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 } @@ -918,7 +908,7 @@ public func - ( /// /// Author.annotated(with: 1 - Author.books.count) public func - ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -945,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 } @@ -957,7 +947,7 @@ public func * ( /// /// Author.annotated(with: 2 * Author.books.count) public func * ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -984,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 } @@ -996,7 +986,7 @@ public func / ( /// /// Author.annotated(with: 2 / Author.books.count) public func / ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -1010,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/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index 293a7b9a0..b5e07e947 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, @@ -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 ca4f82b67..84a7b5caf 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) @@ -156,7 +156,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) @@ -192,7 +192,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 @@ -215,7 +215,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) @@ -254,7 +254,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) @@ -264,7 +264,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 @@ -427,7 +427,7 @@ 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 @@ -507,11 +507,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) } } @@ -527,8 +527,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) } } @@ -541,7 +541,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) } @@ -554,7 +554,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) } @@ -567,7 +567,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) } @@ -580,7 +580,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) } diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 524c198c2..0c4d8f61a 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -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,7 +146,7 @@ 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 { @@ -159,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 } } @@ -233,7 +233,7 @@ 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 { + public func filter(key: some DatabaseValueConvertible) -> Self { if key.databaseValue.isNull { return none() } @@ -256,7 +256,7 @@ 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 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 { ($0 as! Date?).flatMap(strategy.encode)?.databaseValue } @@ -277,10 +277,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// let request = try Player...filter(encodedKeys: [1, 2, 3]) /// /// - parameter keys: A collection of primary keys - func filter(rawKeys: Sequence) - -> Self - where Sequence.Element: DatabaseValueConvertible - { + func filter(rawKeys: some Sequence) -> Self { let keys = Array(rawKeys) if keys.isEmpty { return none() @@ -305,7 +302,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// index on the key columns. /// /// - parameter key: A unique key - public func filter(key: [String: DatabaseValueConvertible?]?) -> Self { + public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> Self { guard let key else { return none() } @@ -321,7 +318,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() } @@ -387,10 +384,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 - { + public func filter(ids: some Collection) -> Self { filter(keys: ids) } } @@ -430,21 +424,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) } @@ -461,7 +455,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 } } @@ -496,7 +490,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. /// @@ -533,7 +527,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 } } @@ -550,7 +544,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 } } diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index 903cf7f7d..1bc67c9cf 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -76,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/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 72696c126..249f2e4f9 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1694,9 +1694,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 { @@ -1739,7 +1739,7 @@ extension Sequence where Element: SQLSpecificExpressible { } } -extension Sequence where Element == SQLSpecificExpressible { +extension Sequence where Element == any SQLSpecificExpressible { /// Returns an expression by joining all elements with an associative SQL /// binary operator. /// @@ -1853,7 +1853,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), @@ -1864,7 +1864,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 d2acfc445..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,7 +26,7 @@ public func average(_ value: SQLSpecificExpressible) -> SQLExpression { /// /// // COUNT(email) /// count(Column("email")) -public func count(_ counted: SQLSpecificExpressible) -> SQLExpression { +public func count(_ counted: some SQLSpecificExpressible) -> SQLExpression { .count(counted.sqlExpression) } @@ -37,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) } @@ -48,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]) } @@ -59,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]) } @@ -70,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]) } @@ -81,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]) } @@ -96,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]) } @@ -111,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]) } @@ -277,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)) } @@ -292,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..e8ec42407 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, @@ -332,7 +332,7 @@ extension Sequence where Self.Iterator.Element: SQLExpressible { /// /// // 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) } } @@ -343,7 +343,7 @@ extension Sequence where Self.Iterator.Element == SQLExpressible { /// /// // 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/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index e37707cb1..f2da3af91 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -288,7 +288,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 4f4fb6131..3945e9ab6 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -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,10 +390,7 @@ 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) } @@ -863,7 +856,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( @@ -1162,10 +1155,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) } } @@ -1210,7 +1200,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) } } @@ -1238,9 +1228,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 { @@ -1270,10 +1259,7 @@ 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 - { + public func deleteOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { if key.databaseValue.isNull { // Don't hit the database return false @@ -1307,10 +1293,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 @@ -1360,7 +1343,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 @@ -1378,7 +1361,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 } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 633a4edea..a761c8de8 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -399,19 +399,19 @@ 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) } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index dbe6271c0..1ceaea2d9 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -473,7 +473,7 @@ struct SQLQueryGenerator: Refinable { /// 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 +605,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 +619,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 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..e5112e3bf 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) } @@ -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/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 98b49fa7d..05685015d 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( diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 4cbbc74dd..08584faf7 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 { @@ -136,7 +136,7 @@ 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) } @@ -146,7 +146,7 @@ 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) } @@ -157,7 +157,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) } @@ -165,10 +165,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) } @@ -176,9 +173,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) } @@ -190,7 +186,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) } @@ -201,7 +197,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) } @@ -236,7 +232,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) } @@ -245,7 +241,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) } @@ -365,10 +361,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) } diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index 06c1e133c..a9f052a67 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -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 9ced8258e..ab5fefb52 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -212,14 +212,14 @@ 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? { + public subscript(_ column: String) -> (any DatabaseValueConvertible)? { get { storage[column] ?? nil } set { storage.updateValue(newValue, forKey: column) } } @@ -229,7 +229,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 } } @@ -252,13 +252,13 @@ public struct PersistenceContainer { 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 @@ -296,7 +296,7 @@ public struct PersistenceContainer { var isEmpty: Bool { storage.isEmpty } /// An iterator over the (column, value) pairs - func makeIterator() -> IndexingIterator> { + func makeIterator() -> IndexingIterator> { storage.makeIterator() } @@ -370,7 +370,7 @@ public enum DatabaseDateEncodingStrategy { case formatted(DateFormatter) /// Encodes the result of the user-provided function - case custom((Date) -> DatabaseValueConvertible?) + case custom((Date) -> (any DatabaseValueConvertible)?) private static let iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() @@ -378,24 +378,24 @@ public enum DatabaseDateEncodingStrategy { 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: - return Self.iso8601Formatter.string(from: date) + 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 } } } @@ -425,14 +425,14 @@ public enum DatabaseUUIDEncodingStrategy { /// Encodes UUIDs as lowercased strings such as "e621e1f8-c36c-495a-93fc-0c247a3e6e5f" case lowercaseString - 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 } } } @@ -459,9 +459,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 73b51064b..1bf3de91e 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -208,9 +208,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 +251,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,7 +340,7 @@ 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 } else { @@ -414,7 +414,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 +490,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) diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index ba17b07cd..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,10 +131,7 @@ 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 - { + public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? { if key.databaseValue.isNull { // Don't hit the database return nil @@ -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 [] @@ -217,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 { @@ -241,10 +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 - { + public static func fetchSet(_ db: Database, ids: some Collection) throws -> Set { if ids.isEmpty { // Avoid hitting the database return [] @@ -275,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) @@ -296,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 [] @@ -314,7 +301,7 @@ 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? { + public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? { guard let key else { // Avoid hitting the database return nil @@ -337,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 004bc9014..bb2932dd5 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -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)) @@ -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. @@ -518,7 +522,7 @@ public final class RecordCursor: DatabaseCursor { public var _isDone = false private let row: Row // Instanciated once, reused for performance - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + 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) diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index a09a63995..df5408616 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -236,10 +236,7 @@ extension MutablePersistableRecord { /// - 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 - { + public func update(_ db: Database, columns: some Sequence) throws { try update(db, columns: Set(columns.map(\.name))) } @@ -250,10 +247,7 @@ extension MutablePersistableRecord { /// - 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 - { + public func update(_ db: Database, columns: some Sequence) throws { try update(db, columns: Set(columns)) } @@ -668,7 +662,7 @@ extension PersistableRecord { extension PersistenceContainer { /// Convenience initializer from a database connection and a record - init(_ db: Database, _ record: Record) throws { + 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) diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index e1a1c882c..0334f1042 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -71,7 +71,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,14 +82,14 @@ 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()] } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index c9c265042..944da1316 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()] } } @@ -172,10 +172,7 @@ extension TableRecord { /// - 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 - { + public static func exists(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { try !filter(key: key).isEmpty(db) } } @@ -217,7 +214,7 @@ extension TableRecord { /// - 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 { + public static func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try !filter(key: key).isEmpty(db) } } @@ -246,9 +243,8 @@ extension TableRecord { /// - keys: A sequence of primary keys. /// - returns: The number of deleted rows @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 { @@ -278,10 +274,7 @@ extension TableRecord { /// - key: A primary key value. /// - returns: Whether a database row was deleted. @discardableResult - public static func deleteOne(_ db: Database, key: PrimaryKeyType) - throws -> Bool - where PrimaryKeyType: DatabaseValueConvertible - { + public static func deleteOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { if key.databaseValue.isNull { // Don't hit the database return false @@ -312,10 +305,7 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// - 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 - { + public static func deleteAll(_ db: Database, ids: some Collection) throws -> Int { if ids.isEmpty { // Avoid hitting the database return 0 @@ -361,7 +351,7 @@ extension TableRecord { /// - keys: An array of key dictionaries. /// - returns: The number of deleted rows @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 @@ -379,7 +369,7 @@ extension TableRecord { /// - key: A dictionary of values. /// - returns: Whether a database row 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 } } 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/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 8f0bd8ab3..28cd65402 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -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 @@ -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 { diff --git a/GRDB/ValueObservation/ValueConcurrentObserver.swift b/GRDB/ValueObservation/ValueConcurrentObserver.swift index 98b3f06ef..d3669c4c7 100644 --- a/GRDB/ValueObservation/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/ValueConcurrentObserver.swift @@ -191,7 +191,7 @@ final class ValueConcurrentObserver { // `WALSnapshot` class. extension ValueConcurrentObserver { // Starts the observation - func start() -> DatabaseCancellable { + func start() -> AnyDatabaseCancellable { let (notificationCallbacks, databaseAccess) = lock.synchronized { (self.notificationCallbacks, self.databaseAccess) } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 33c11b930..edd31390b 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -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 { @@ -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) @@ -264,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 @@ -309,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) @@ -320,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() } @@ -396,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 { @@ -458,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 @@ -667,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> { @@ -712,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> { diff --git a/GRDB/ValueObservation/ValueObservationScheduler.swift b/GRDB/ValueObservation/ValueObservationScheduler.swift index 46c380d95..37cf5ac5f 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 } diff --git a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/ValueWriteOnlyObserver.swift index d1d114b8c..9f9b499e3 100644 --- a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/ValueWriteOnlyObserver.swift @@ -151,7 +151,7 @@ final class ValueWriteOnlyObserver DatabaseCancellable { + func start() -> AnyDatabaseCancellable { let (notificationCallbacks, writer) = lock.synchronized { (self.notificationCallbacks, self.databaseAccess?.writer) } diff --git a/README.md b/README.md index c8fb63e25..253fdfdb5 100644 --- a/README.md +++ b/README.md @@ -2741,7 +2741,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 } } ``` @@ -3638,12 +3638,12 @@ 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] { + override class var databaseSelection: [any SQLSelectable] { [AllColums(), Column.rowID] } } @@ -3893,7 +3893,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, @@ -4756,12 +4756,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 @@ -4771,7 +4771,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. +> :point_up: **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 @@ -5169,7 +5169,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 } diff --git a/TODO.md b/TODO.md index 12b64e2a9..ad6c0707b 100644 --- a/TODO.md +++ b/TODO.md @@ -23,6 +23,8 @@ - [ ] 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: databaseregionconvertible should return a cancellable +- [ ] RangeReplaceableCollection should have append(contentsOf: cursor) - [ ] GRDB 6: Swift 5.7 - [ ] GRDB 6: any / some - [ ] GRDB 6: primary associated types (cursor, requests, ...) diff --git a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift index 6d312b357..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 { try 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 { try 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 1ef238a31..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 { try 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 { try 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 { try 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 { try 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/ValueObservationPublisherTests.swift b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift index f74294afb..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 { try 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 { try 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 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..9431170df 100644 --- a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift @@ -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..a0efecca4 100644 --- a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -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..06ea3a483 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift @@ -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..4c7635125 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") 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 8d850380e..45972b0d3 100644 --- a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift @@ -31,7 +31,7 @@ class AssociationPrefetchingObservationTests: 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/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..140520cc4 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) diff --git a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift index aa6bdf2f8..e1c05d05e 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 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 bc6dba2e1..1d969c6cb 100644 --- a/Tests/GRDBTests/BackupTestCase.swift +++ b/Tests/GRDBTests/BackupTestCase.swift @@ -6,7 +6,7 @@ class BackupTestCase: GRDBTestCase { // A "user" error simply for testing purposes 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/CompilationSubClassTests.swift b/Tests/GRDBTests/CompilationSubClassTests.swift index 37ba8f720..494e099f9 100644 --- a/Tests/GRDBTests/CompilationSubClassTests.swift +++ b/Tests/GRDBTests/CompilationSubClassTests.swift @@ -10,7 +10,7 @@ private class UserRecord : Record { required init(row: Row) { 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 class var databaseSelection: [any 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() } 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/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 1bbc2c5fa..144686272 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -4,19 +4,18 @@ 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 { try 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: { dbResult in @@ -30,10 +29,9 @@ class DatabaseMigratorTests : GRDBTestCase { waitForExpectations(timeout: 5, handler: nil) } - try Test(test) - .run { try 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 { @@ -41,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 { try 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: """ @@ -93,14 +90,13 @@ class DatabaseMigratorTests : GRDBTestCase { } } - try Test(test) - .run { try 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: """ @@ -145,10 +141,9 @@ class DatabaseMigratorTests : GRDBTestCase { waitForExpectations(timeout: 5, handler: nil) } - try Test(test) - .run { try 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 { @@ -156,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: """ @@ -202,10 +197,9 @@ class DatabaseMigratorTests : GRDBTestCase { } } - try Test(test) - .run { try 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 { @@ -213,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) @@ -229,10 +223,9 @@ class DatabaseMigratorTests : GRDBTestCase { cancellable.cancel() } - try Test(test) - .run { try 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 { @@ -240,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: "") @@ -257,10 +250,9 @@ class DatabaseMigratorTests : GRDBTestCase { cancellable.cancel() } - try Test(test) - .run { try 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 { @@ -268,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: "") @@ -287,10 +279,9 @@ class DatabaseMigratorTests : GRDBTestCase { cancellable.cancel() } - try Test(test) - .run { try 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 { @@ -298,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") @@ -318,14 +309,13 @@ class DatabaseMigratorTests : GRDBTestCase { cancellable.cancel() } - try Test(test) - .run { try 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)") @@ -370,10 +360,9 @@ class DatabaseMigratorTests : GRDBTestCase { // try migrator.migrate(writer, upTo: "b") } - try Test(test) - .run { try 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 { 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/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/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index fabe17716..d2935629b 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -5,8 +5,8 @@ class DatabaseReaderTests : GRDBTestCase { func testAnyDatabaseReader() throws { // This test passes if this code compiles. - let reader: DatabaseReader = try DatabaseQueue() - let _: DatabaseReader = AnyDatabaseReader(reader) + let dbQueue = try DatabaseQueue() + let _: any DatabaseReader = AnyDatabaseReader(dbQueue) } // MARK: - Read 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/DatabaseValueConversionTests.swift b/Tests/GRDBTests/DatabaseValueConversionTests.swift index 022977cce..dbf12b844 100644 --- a/Tests/GRDBTests/DatabaseValueConversionTests.swift +++ b/Tests/GRDBTests/DatabaseValueConversionTests.swift @@ -99,7 +99,7 @@ class DatabaseValueConversionTests : GRDBTestCase { // 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: """ diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index eda69a5cd..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 @@ -150,8 +150,8 @@ class DatabaseWriterTests : GRDBTestCase { func testAnyDatabaseWriter() throws { // This test passes if this code compiles. - let writer: DatabaseWriter = try 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: """ 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 6f25c8aa0..6baea9ffd 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -34,7 +34,7 @@ extension Book : MutablePersistableRecord { } 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/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index 34690bd73..f23a989b7 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -34,7 +34,7 @@ extension Book : MutablePersistableRecord { } 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 c9068f829..8ebc2804a 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -35,7 +35,7 @@ extension Book : MutablePersistableRecord { } 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/FetchableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift index 52004ac3e..4d19279bf 100644 --- a/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift @@ -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/FoundationDateComponentsTests.swift b/Tests/GRDBTests/FoundationDateComponentsTests.swift index 4d16d0979..176145e90 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: """ diff --git a/Tests/GRDBTests/FoundationDateTests.swift b/Tests/GRDBTests/FoundationDateTests.swift index 16a1038b2..553cf2e11 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: """ 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 62c981b14..a81ab226a 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 @@ -133,7 +133,7 @@ class GRDBTestCase: XCTestCase { XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)", file: file, line: line) } - func assert(_ record: EncodableRecord, isEncodedIn row: Row, file: StaticString = #filePath, line: UInt = #line) { + func assert(_ record: some EncodableRecord, isEncodedIn row: Row, file: StaticString = #filePath, line: UInt = #line) { let recordDict = record.databaseDictionary let rowDict = Dictionary(row, uniquingKeysWith: { (left, _) in left }) XCTAssertEqual(recordDict, rowDict, file: file, line: line) diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index 28bd96f17..ed676751f 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -198,7 +198,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..a069f292d 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -29,7 +29,7 @@ private struct Player: FetchableRecord, MutablePersistableRecord, Codable { } 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() diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index 11eefc9c9..fd7e0708c 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -86,7 +86,7 @@ private struct MutablePersistableRecordCustomizedCountry : MutablePersistableRec 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: """ diff --git a/Tests/GRDBTests/PersistableRecordTests.swift b/Tests/GRDBTests/PersistableRecordTests.swift index ff7f15316..deb80f7ef 100644 --- a/Tests/GRDBTests/PersistableRecordTests.swift +++ b/Tests/GRDBTests/PersistableRecordTests.swift @@ -106,7 +106,7 @@ private struct Citizenship : PersistableRecord { 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: """ diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index dee5bd5f7..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: """ 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 0d1801a28..7dfdfb171 100644 --- a/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift @@ -60,7 +60,7 @@ extension FastWrapper: StatementColumnConvertible where RawValue: StatementColum 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)") diff --git a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift index f3ca0b73b..fc78aec09 100644 --- a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift @@ -38,7 +38,7 @@ private class Reader : Record { 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/RecordEditedTests.swift b/Tests/GRDBTests/RecordEditedTests.swift index 535e4bafc..4c1dae91c 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -131,7 +131,7 @@ private class PersonWithModifiedCaseColumns: Record { 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) diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 51df91e5d..97bdbddd7 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -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) diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index c7bb89bc5..98a557ac6 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -49,7 +49,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) diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index cae1f356c..8fba71a17 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -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) diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 73553f6ff..8c2487690 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -83,7 +83,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) diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index 79835ab01..ac74dda2f 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -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) diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index c114bfe30..969b8dab8 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -55,7 +55,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..8ffc8c00c 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -77,7 +77,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) diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index 53686dd82..3ae89c19a 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -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) diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index 110cde402..5ee5efc71 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -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) diff --git a/Tests/GRDBTests/RecordSubClassTests.swift b/Tests/GRDBTests/RecordSubClassTests.swift index ff707813f..73f3fded2 100644 --- a/Tests/GRDBTests/RecordSubClassTests.swift +++ b/Tests/GRDBTests/RecordSubClassTests.swift @@ -104,7 +104,7 @@ private class PersonWithOverrides : Person { 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..3b2c05b36 100644 --- a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift +++ b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift @@ -45,7 +45,7 @@ class BadlyMangledStuff : Record { 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/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..a71576d4b 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: """ 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/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index f30015da6..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: """ diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index a04d3e9ca..167f95dae 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -24,7 +24,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)") diff --git a/Tests/GRDBTests/UpdateStatementTests.swift b/Tests/GRDBTests/UpdateStatementTests.swift index 401977207..4834bf0d7 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: """ 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/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 9cfad00dc..70ba5caae 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) @@ -367,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? @@ -394,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 @@ -424,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? @@ -469,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 @@ -577,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( diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 5966543b3..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") @@ -589,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") @@ -633,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") @@ -677,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)") } @@ -729,7 +731,7 @@ class ValueObservationTests: GRDBTestCase { @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)") } @@ -756,15 +758,14 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { try 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)") } @@ -791,15 +792,14 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { try 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)") } @@ -830,15 +830,14 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { try 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)") } @@ -866,15 +865,14 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { try 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)") } @@ -914,9 +912,8 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { try 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) } } } From 7ffc332327d6ebe1a61d139de24e413e83d80cd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 25 Jul 2022 14:06:22 +0200 Subject: [PATCH 22/73] BREAKING: replace selectID() with selectPrimaryKey(as:) Since Optional is a database value like others, selectID would be a request of optionals for records with an optional ID type: struct Player: Identifiable, MutablePersistableRecord { var id: Int64? } Player.selectID() // QueryInterface This is not good, because primary keys are not null. And those requests would fetch impractical types such as [Int64?], Set, Int64??. Instead, we introduce selectPrimaryKey(as:), which allows the user to provide the desired type. Player.selectPrimaryKey(as: Int64.self) // QueryInterface --- CHANGELOG.md | 1 + .../GRDBAsyncDemoTests/AppDatabaseTests.swift | 2 +- Documentation/GRDB6MigrationGuide.md | 10 +++++ .../GoodPracticesForDesigningRecordTypes.md | 6 +-- GRDB/Fixits.swift | 18 ++++++++ .../Request/QueryInterfaceRequest.swift | 44 ++++++++++--------- GRDB/QueryInterface/SQL/Table.swift | 22 ++++++++-- .../TableRecord+QueryInterfaceRequest.swift | 26 +++++++---- README.md | 28 ++++++------ ...imalNonOptionalPrimaryKeySingleTests.swift | 22 ++++------ .../RecordMinimalPrimaryKeyRowIDTests.swift | 22 ++++------ .../RecordMinimalPrimaryKeySingleTests.swift | 24 +++++----- Tests/GRDBTests/TableTests.swift | 5 ++- 13 files changed, 138 insertions(+), 92 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6502c6b20..5da6aa9bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -99,6 +99,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ are required. - **Breaking**: Removed deprecated methods - **Breaking**: The in-memory `DatabaseQueue()` initializer can now throw errors. +- **Breaking**: The `selectID()` method is replaced with `selectPrimaryKey(as:)`. - **New**: 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). ## 5.26.0 diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift index fd50726ad..2d0dd4ef8 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift @@ -61,7 +61,7 @@ class AppDatabaseTests: XCTestCase { _ = 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 diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index 27d97f938..be65e86f3 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -50,3 +50,13 @@ The `Cursor` protocol has also gained a primary associated type (the type of its -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() + } + } + ``` diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index e708cc4f7..8eef81786 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -371,13 +371,13 @@ Extensions to the `DerivableRequest` protocol can not change the type of request // Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~ extension QueryInterfaceRequest where RowDecoder == Author { // 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 diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 2e48aa6ac..b61dda4b7 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -52,12 +52,30 @@ typealias FastNullableDatabaseValueCursor has been replaced with DatabaseValueCursor") typealias NullableDatabaseValueCursor = DatabaseValueCursor +@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() } +} + @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 diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 84a7b5caf..1f69d446d 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -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 @@ -165,26 +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) - } -} - extension QueryInterfaceRequest: FilteredRequest { /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 3945e9ab6..f91af0a7e 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -393,14 +393,28 @@ extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConv public func filter(ids: some Collection) -> QueryInterfaceRequest { 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) } } diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 08584faf7..35b5c1d55 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -130,6 +130,24 @@ 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 @@ -364,12 +382,4 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { 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() - } } diff --git a/README.md b/README.md index 253fdfdb5..cd778ba04 100644 --- a/README.md +++ b/README.md @@ -3016,9 +3016,6 @@ 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]) ``` @@ -4076,7 +4073,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) | @@ -4491,16 +4488,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 @@ -4677,6 +4664,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 diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 97bdbddd7..17a1fefd1 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -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 98a557ac6..688eabd2f 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -787,33 +787,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 8fba71a17..27d635e89 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -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/TableTests.swift b/Tests/GRDBTests/TableTests.swift index 7645b584d..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, *) { @@ -140,7 +142,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) } } } From 42987dd8498a6be880833139181fb8f687817bb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 25 Jul 2022 14:38:40 +0200 Subject: [PATCH 23/73] Cleanup filter(rawKeys:) --- GRDB/QueryInterface/Request/RequestProtocols.swift | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 0c4d8f61a..e70216489 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -278,8 +278,14 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// /// - parameter keys: A collection of primary keys func filter(rawKeys: some Sequence) -> Self { - let keys = Array(rawKeys) - if keys.isEmpty { + // 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() } @@ -289,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) } } From 11a6d53d8abb94dd4cfa8573e5d53cfc46f3c352 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 25 Jul 2022 16:01:07 +0200 Subject: [PATCH 24/73] SE-0326: closure result type inference https://github.com/apple/swift-evolution/blob/main/proposals/0326-extending-multi-statement-closure-inference.md --- GRDB/Core/Database.swift | 6 +++--- GRDB/Core/Statement.swift | 2 +- GRDB/Core/TransactionObserver.swift | 8 ++++---- GRDB/Core/WALSnapshot.swift | 2 +- GRDB/FTS/FTS5Tokenizer.swift | 2 +- GRDB/Migration/DatabaseMigrator.swift | 2 +- GRDB/QueryInterface/Request/QueryInterfaceRequest.swift | 2 +- GRDB/QueryInterface/SQL/SQLAssociation.swift | 2 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 2 +- GRDB/ValueObservation/ValueConcurrentObserver.swift | 6 +++--- GRDB/ValueObservation/ValueWriteOnlyObserver.swift | 4 ++-- 11 files changed, 19 insertions(+), 19 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ac1095066..36c3fc5f8 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -322,7 +322,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib let authorizerP = Unmanaged.passUnretained(authorizer).toOpaque() sqlite3_set_authorizer( sqliteConnection, - { (authorizerP, actionCode, cString1, cString2, cString3, cString4) -> Int32 in + { (authorizerP, actionCode, cString1, cString2, cString3, cString4) in Unmanaged .fromOpaque(authorizerP.unsafelyUnwrapped) .takeUnretainedValue() @@ -503,9 +503,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. diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index d37880152..344429d90 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -925,7 +925,7 @@ 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: ", ") + "]" diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 4e61b3ede..afb881494 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -1234,7 +1234,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 +1244,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 +1298,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 +1306,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) }) } diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index ee216190a..ce1df691d 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -35,7 +35,7 @@ final class WALSnapshot { /// error occurs. init?(_ db: Database) { var snapshot: UnsafeMutablePointer? - let code: CInt = withUnsafeMutablePointer(to: &snapshot) { + let code = withUnsafeMutablePointer(to: &snapshot) { return sqlite3_snapshot_get(db.sqliteConnection, "main", $0) } guard code == SQLITE_OK, let snapshot else { diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index 54ca29223..6410c6843 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -127,7 +127,7 @@ extension FTS5Tokenizer { tokenization: tokenization, pText: pText, nText: nText, - tokenCallback: { (contextPointer, flags, pToken, nToken, _ /* iStart */, _ /* iEnd */) -> Int32 in + tokenCallback: { (contextPointer, flags, pToken, nToken, _ /* iStart */, _ /* iEnd */) in guard let contextPointer else { return SQLITE_ERROR } diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index a4c3be606..79a684f68 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -389,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 diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 1f69d446d..42e9eba0f 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -830,7 +830,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/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/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 0bf05666d..d6ffd85a1 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -893,7 +893,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/ValueObservation/ValueConcurrentObserver.swift b/GRDB/ValueObservation/ValueConcurrentObserver.swift index d3669c4c7..25dc0d8a1 100644 --- a/GRDB/ValueObservation/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/ValueConcurrentObserver.swift @@ -279,7 +279,7 @@ extension ValueConcurrentObserver { } // Reduce - let initialValue: Reducer.Value = reduceQueue.sync { + let initialValue = reduceQueue.sync { guard let initialValue = reducer._value(fetchedValue) else { fatalError("Broken contract: reducer has no initial value") } @@ -390,7 +390,7 @@ extension ValueConcurrentObserver { // database versions. It prevents database checkpointing, // and keeps WAL snapshots (`sqlite3_snapshot`) valid // and comparable. - let isModified: Bool = withExtendedLifetime(initialSnapshot) { + let isModified = withExtendedLifetime(initialSnapshot) { guard let initialWALSnapshot, let currentWALSnapshot = WALSnapshot(writerDB) else { @@ -608,7 +608,7 @@ extension ValueConcurrentObserver: DatabaseCancellable { func notifyError(_ error: Error) { scheduler.schedule { - let events: ValueObservationEvents? = self.lock.synchronized { + let events = self.lock.synchronized { let events = self.notificationCallbacks?.events self.notificationCallbacks = nil return events diff --git a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/ValueWriteOnlyObserver.swift index 9f9b499e3..1b9ced0c3 100644 --- a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/ValueWriteOnlyObserver.swift @@ -413,7 +413,7 @@ extension ValueWriteOnlyObserver: TransactionObserver { extension ValueWriteOnlyObserver: DatabaseCancellable { func cancel() { // Notify cancellation - let (events, writer): (ValueObservationEvents?, Writer?) = lock.synchronized { + let (events, writer) = lock.synchronized { let events = notificationCallbacks?.events notificationCallbacks = nil return (events, databaseAccess?.writer) @@ -433,7 +433,7 @@ extension ValueWriteOnlyObserver: DatabaseCancellable { func notifyError(_ error: Error) { scheduler.schedule { - let events: ValueObservationEvents? = self.lock.synchronized { + let events = self.lock.synchronized { let events = self.notificationCallbacks?.events self.notificationCallbacks = nil return events From 180c8975aca238b54cfb7f58e2c3eb5576b4c1ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 26 Jul 2022 08:10:22 +0200 Subject: [PATCH 25/73] Stop using #filePath --- Tests/GRDBCombineTests/Support.swift | 4 ++-- .../AssociationPrefetchingObservationTests.swift | 2 +- Tests/GRDBTests/DatabaseValueConversionTests.swift | 4 ++-- Tests/GRDBTests/ForeignKeyInfoTests.swift | 2 +- Tests/GRDBTests/FoundationDateComponentsTests.swift | 2 +- Tests/GRDBTests/FoundationDateTests.swift | 4 ++-- Tests/GRDBTests/GRDBTestCase.swift | 12 ++++++------ Tests/GRDBTests/ValueObservationRecorder.swift | 6 +++--- 8 files changed, 18 insertions(+), 18 deletions(-) diff --git a/Tests/GRDBCombineTests/Support.swift b/Tests/GRDBCombineTests/Support.swift index 89f315cf3..bf9c1d3a7 100644 --- a/Tests/GRDBCombineTests/Support.swift +++ b/Tests/GRDBCombineTests/Support.swift @@ -103,7 +103,7 @@ final class AsyncTest { @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func assertNoFailure( _ completion: Subscribers.Completion, - file: StaticString = #filePath, + file: StaticString = #file, line: UInt = #line) { if case let .failure(error) = completion { @@ -114,7 +114,7 @@ public func assertNoFailure( @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func assertFailure( _ completion: Subscribers.Completion, - file: StaticString = #filePath, + file: StaticString = #file, line: UInt = #line, test: (ExpectedFailure) -> Void) { diff --git a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift index 45972b0d3..b97580fbe 100644 --- a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift @@ -13,7 +13,7 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { _ db: Database, _ request: QueryInterfaceRequest, _ expectedDescriptions: String..., - file: StaticString = #filePath, line: UInt = #line) throws + file: StaticString = #file, line: UInt = #line) throws { // Test DatabaseRegionConvertible do { diff --git a/Tests/GRDBTests/DatabaseValueConversionTests.swift b/Tests/GRDBTests/DatabaseValueConversionTests.swift index dbf12b844..7ea09e374 100644 --- a/Tests/GRDBTests/DatabaseValueConversionTests.swift +++ b/Tests/GRDBTests/DatabaseValueConversionTests.swift @@ -37,7 +37,7 @@ class DatabaseValueConversionTests : GRDBTestCase { _ type: T.Type, expectedSQLiteConversion: T?, expectedDatabaseValueConversion: T?, - file: StaticString = #filePath, + file: StaticString = #file, line: UInt = #line) throws { func stringRepresentation(_ value: T?) -> String { @@ -87,7 +87,7 @@ class DatabaseValueConversionTests : GRDBTestCase { _ db: Database, _ sql: String, _ type: T.Type, - file: StaticString = #filePath, + file: StaticString = #file, line: UInt = #line) throws { // We can only test failed decoding from database value, since diff --git a/Tests/GRDBTests/ForeignKeyInfoTests.swift b/Tests/GRDBTests/ForeignKeyInfoTests.swift index f9b95d7d7..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 = #filePath, line: UInt = #line) { + 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) { diff --git a/Tests/GRDBTests/FoundationDateComponentsTests.swift b/Tests/GRDBTests/FoundationDateComponentsTests.swift index 176145e90..b336a7525 100644 --- a/Tests/GRDBTests/FoundationDateComponentsTests.swift +++ b/Tests/GRDBTests/FoundationDateComponentsTests.swift @@ -349,7 +349,7 @@ class FoundationDateComponentsTests : GRDBTestCase { } func testDatabaseDateComponentsParsing() { - func assertParse(_ string: String, _ dateComponent: DatabaseDateComponents, file: StaticString = #filePath, line: UInt = #line) { + func assertParse(_ string: String, _ dateComponent: DatabaseDateComponents, file: StaticString = #file, line: UInt = #line) { do { // Test DatabaseValueConvertible adoption guard let parsed = DatabaseDateComponents.fromDatabaseValue(string.databaseValue) else { diff --git a/Tests/GRDBTests/FoundationDateTests.swift b/Tests/GRDBTests/FoundationDateTests.swift index 553cf2e11..024ef4395 100644 --- a/Tests/GRDBTests/FoundationDateTests.swift +++ b/Tests/GRDBTests/FoundationDateTests.swift @@ -326,7 +326,7 @@ class FoundationDateTests : GRDBTestCase { _ db: Database, _ expression: SQLExpression, equal expectedDate: Date, - file: StaticString = #filePath, + file: StaticString = #file, line: UInt = #line) throws { let request: SQLRequest = "SELECT \(expression)" @@ -375,7 +375,7 @@ class FoundationDateTests : GRDBTestCase { _ db: Database, _ expression: SQLExpression, equal expectedDate: String, - file: StaticString = #filePath, + file: StaticString = #file, line: UInt = #line) throws { let request: SQLRequest = "SELECT \(expression)" diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index a81ab226a..cbba5c64a 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -121,7 +121,7 @@ class GRDBTestCase: XCTestCase { do { try FileManager.default.removeItem(atPath: dbDirectoryPath) } catch { } } - func assertNoError(file: StaticString = #filePath, line: UInt = #line, _ test: () throws -> Void) { + func assertNoError(file: StaticString = #file, line: UInt = #line, _ test: () throws -> Void) { do { try test() } catch { @@ -129,31 +129,31 @@ class GRDBTestCase: XCTestCase { } } - func assertDidExecute(sql: String, file: StaticString = #filePath, line: UInt = #line) { + func assertDidExecute(sql: String, file: StaticString = #file, line: UInt = #line) { XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)", file: file, line: line) } - func assert(_ record: some EncodableRecord, isEncodedIn row: Row, file: StaticString = #filePath, line: UInt = #line) { + func assert(_ record: some EncodableRecord, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) { let recordDict = record.databaseDictionary let rowDict = Dictionary(row, uniquingKeysWith: { (left, _) in left }) XCTAssertEqual(recordDict, rowDict, file: file, line: line) } // Compare SQL strings (ignoring leading and trailing white space and semicolons. - func assertEqualSQL(_ lhs: String, _ rhs: String, file: StaticString = #filePath, line: UInt = #line) { + 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. - func assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #filePath, line: UInt = #line) 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. - func assertEqualSQL(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #filePath, line: UInt = #line) throws { + func assertEqualSQL(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { try databaseReader.unsafeRead { db in try assertEqualSQL(db, request, sql, file: file, line: line) } diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 70ba5caae..0d4a677be 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -313,7 +313,7 @@ extension XCTestCase { expected expectedValues: E, allowMissingLastValue: Bool = false, _ message: @autoclosure () -> String = "", - file: StaticString = #filePath, + file: StaticString = #file, line: UInt = #line) where R: BidirectionalCollection, @@ -357,7 +357,7 @@ extension GRDBTestCase { records expectedValues: [Reducer.Value], setup: (Database) throws -> Void, recordedUpdates: @escaping (Database) throws -> Void, - file: StaticString = #filePath, + file: StaticString = #file, line: UInt = #line) throws where Reducer.Value: Equatable @@ -568,7 +568,7 @@ extension GRDBTestCase { _ observation: ValueObservation, fails testFailure: (Failure, DatabaseWriter) throws -> Void, setup: (Database) throws -> Void, - file: StaticString = #filePath, + file: StaticString = #file, line: UInt = #line) throws { From dba7f1b2dc2f7e5f1cb239666b61dac75c6d221f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 26 Jul 2022 08:45:18 +0200 Subject: [PATCH 26/73] BREAKING: turn Cursor.isEmpty into a property https://github.com/apple/swift-evolution/blob/main/proposals/0310-effectful-readonly-properties.md --- CHANGELOG.md | 1 + Documentation/GRDB6MigrationGuide.md | 7 +++++++ GRDB/Core/Cursor.swift | 10 ++++++---- Tests/GRDBTests/CursorTests.swift | 7 +++++++ 4 files changed, 21 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5da6aa9bb..e66d72339 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -100,6 +100,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: Removed deprecated methods - **Breaking**: The in-memory `DatabaseQueue()` initializer can now throw errors. - **Breaking**: The `selectID()` method is replaced with `selectPrimaryKey(as:)`. +- **Breaking**: `Cursor.isEmpty` is now a throwing property, instead of a method. - **New**: 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). ## 5.26.0 diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index be65e86f3..0f97058d8 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -60,3 +60,10 @@ The `Cursor` protocol has also gained a primary associated type (the type of its } } ``` + +- `Cursor.isEmpty` is now a throwing property, instead of a method: + + ```diff + -if try cursor.isEmpty() { ... } + +if try cursor.isEmpty { ... } + ``` diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 6b65a64ab..bba2f6df7 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -243,10 +243,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 diff --git a/Tests/GRDBTests/CursorTests.swift b/Tests/GRDBTests/CursorTests.swift index 3174db7b7..19ad7206b 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() } From 34a4fa644451f2c668748af4a968e2fb170e6338 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 27 Jul 2022 19:43:59 +0200 Subject: [PATCH 27/73] TODO --- TODO.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/TODO.md b/TODO.md index ad6c0707b..883e4f020 100644 --- a/TODO.md +++ b/TODO.md @@ -23,19 +23,25 @@ - [ ] 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 +- [ ] Can we generate EXISTS with association? `Team.annotated(with: Team.players.exists)` - [ ] GRDB 6: databaseregionconvertible should return a cancellable - [ ] RangeReplaceableCollection should have append(contentsOf: cursor) +- [ ] GRDB 6: choose persistence table +- [ ] GRDB 6: decoding errors +- [ ] GRDB 6: encoding errors for record (`EncodableRecord.encode(to:)`) +- [?] 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) - [ ] 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) -- [ ] GRDB 6: choose persistence table +- [?] 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. From 55445dcc7c383ba42194d5a5711943c2070566c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 27 Jul 2022 20:01:26 +0200 Subject: [PATCH 28/73] NEW: RangeReplaceableCollection.append(contentsOf: cursor) --- CHANGELOG.md | 1 + GRDB/Core/Cursor.swift | 17 ++++++++++++----- GRDB/Core/Statement.swift | 4 +++- Tests/GRDBTests/CursorTests.swift | 7 +++++++ 4 files changed, 23 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e66d72339..fad1dcfc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -102,6 +102,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: The `selectID()` method is replaced with `selectPrimaryKey(as:)`. - **Breaking**: `Cursor.isEmpty` is now a throwing property, instead of a method. - **New**: 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). +- **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`. ## 5.26.0 diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index bba2f6df7..ee45c3566 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -21,10 +21,7 @@ extension RangeReplaceableCollection { /// - parameter cursor: The cursor whose elements feed the collection. 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. @@ -39,10 +36,20 @@ extension RangeReplaceableCollection { 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) } } } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 344429d90..56f3a86ae 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -425,7 +425,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 } } diff --git a/Tests/GRDBTests/CursorTests.swift b/Tests/GRDBTests/CursorTests.swift index 19ad7206b..29930f223 100644 --- a/Tests/GRDBTests/CursorTests.swift +++ b/Tests/GRDBTests/CursorTests.swift @@ -202,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 { From a20d543bcf62d1bf5944f5e11c6760280c154487 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Thu, 28 Jul 2022 13:10:23 +0200 Subject: [PATCH 29/73] Swiftlint: disable the for_where rule --- Scripts/swiftlint.yml | 1 + 1 file changed, 1 insertion(+) 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 From 33a039717ce980fd6df8ca9e846fd7fdf3644658 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Thu, 28 Jul 2022 13:16:06 +0200 Subject: [PATCH 30/73] Refer to UIApplication notifications by their names It looks like FB9801372 was fixed --- GRDB/Core/DatabasePool.swift | 9 ++------- GRDB/Core/DatabaseQueue.swift | 9 ++------- Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift | 6 +++--- 3 files changed, 7 insertions(+), 17 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 4b98d3fcb..bf4b986fe 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -214,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) } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 9e3156263..dbcf000f7 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -93,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) } 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 From 2011776cbef5c90e6c789660bc6bd13ab62f4c53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Thu, 28 Jul 2022 13:18:18 +0200 Subject: [PATCH 31/73] Remove misleading comments --- GRDB/Core/DatabaseReader.swift | 2 -- 1 file changed, 2 deletions(-) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 719412ede..800bb5c1c 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -374,7 +374,6 @@ extension DatabaseReader { 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. /// @@ -421,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) From 3000cd3c7f3577827b2185944473ea25ae0f0456 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Thu, 28 Jul 2022 13:36:10 +0200 Subject: [PATCH 32/73] TODO --- TODO.md | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/TODO.md b/TODO.md index 883e4f020..6bd61e623 100644 --- a/TODO.md +++ b/TODO.md @@ -17,29 +17,34 @@ ## 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 - [ ] Can we generate EXISTS with association? `Team.annotated(with: Team.players.exists)` -- [ ] GRDB 6: databaseregionconvertible should return a cancellable -- [ ] RangeReplaceableCollection should have append(contentsOf: cursor) +- [ ] 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 + - [ ] throwing FetchableRecord initializer FIRST + - [ ] throwing Decodable FetchableRecord initializer SECOND + - [ ] deal with as much value decoding error as possible - [ ] GRDB 6: encoding errors for record (`EncodableRecord.encode(to:)`) + - [ ] 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) -- [ ] GRDB 6: Swift 5.7 -- [ ] GRDB 6: any / some -- [ ] GRDB 6: primary associated types (cursor, requests, ...) -- [ ] GRDB 6: remove existential/generic duplicated methods + - [ ] 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 - [ ] GRDB 6: conflict resolution in persistence methods - [ ] GRDB 6: UPSERT - [ ] GRDB 6: support for RETURNING -- [ ] GRDB 6: allow mutating `update` (for timestamps) + - [ ] Support for default values: `Player.insert(db, returning: 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. @@ -48,7 +53,6 @@ - [ ] 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 - [ ] 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) From a15f731042767a5626ee69a9a5b70f2e8e4a1712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Thu, 28 Jul 2022 13:44:42 +0200 Subject: [PATCH 33/73] BREAKING: remove Record.copy() This will allow FetchableRecord.init(row:) to throw --- CHANGELOG.md | 1 + Documentation/GRDB6MigrationGuide.md | 2 + GRDB.xcodeproj/project.pbxproj | 8 -- GRDB/Fixits.swift | 6 +- GRDB/Record/Record.swift | 17 ---- GRDBCustom.xcodeproj/project.pbxproj | 6 -- .../GRDBTests.xcodeproj/project.pbxproj | 6 -- .../GRDBTests.xcodeproj/project.pbxproj | 6 -- .../GRDBTests/CompilationSubClassTests.swift | 1 - Tests/GRDBTests/RecordCopyTests.swift | 46 ---------- Tests/GRDBTests/RecordEditedTests.swift | 86 +------------------ 11 files changed, 9 insertions(+), 176 deletions(-) delete mode 100644 Tests/GRDBTests/RecordCopyTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index fad1dcfc6..096550d9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -101,6 +101,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: The in-memory `DatabaseQueue()` initializer can now throw errors. - **Breaking**: The `selectID()` method is replaced with `selectPrimaryKey(as:)`. - **Breaking**: `Cursor.isEmpty` is now a throwing property, instead of a method. +- **Breaking**: The `Record.copy()` method was removed, without replacement. - **New**: 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). - **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`. diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index 0f97058d8..27a54fdc8 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -67,3 +67,5 @@ The `Cursor` protocol has also gained a primary associated type (the type of its -if try cursor.isEmpty() { ... } +if try cursor.isEmpty { ... } ``` + +- The `Record.copy()` method was removed, without replacement. diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index fd65b6bc4..f75ca7afa 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -689,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 */; }; @@ -822,7 +821,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 */; }; @@ -1136,7 +1134,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 */; }; @@ -1576,7 +1573,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 = ""; }; @@ -1880,7 +1876,6 @@ 56176C9E1EACEDF9000F3F2B /* Record */ = { isa = PBXGroup; children = ( - 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */, 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */, 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */, 56DA7CF6260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */, @@ -3333,7 +3328,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 +3637,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 */, @@ -3943,7 +3936,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 */, diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index b61dda4b7..dcd78178e 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -58,6 +58,11 @@ extension QueryInterfaceRequest where RowDecoder: Identifiable, RowDecoder.ID: D 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 @@ -86,4 +91,3 @@ extension ValueObservation where Reducer == ValueReducers.Auto { -> ValueObservation> { preconditionFailure() } } - diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 0334f1042..9aa62c713 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -139,23 +139,6 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { 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 - } - - // MARK: - Compare with Previous Versions /// A boolean that indicates whether the record has changes that have not diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3c93e153a..3eb4a0ee5 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -726,7 +726,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 */; }; @@ -738,7 +737,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 */; }; @@ -1067,7 +1065,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 = ""; }; @@ -1346,7 +1343,6 @@ 56176C9E1EACEDF9000F3F2B /* Record */ = { isa = PBXGroup; children = ( - 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */, 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */, 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */, 56DA7D02260FAA1A00A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */, @@ -2583,7 +2579,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 */, @@ -2821,7 +2816,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 */, diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index a731f80e8..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 */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index e5db016ea..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 */, diff --git a/Tests/GRDBTests/CompilationSubClassTests.swift b/Tests/GRDBTests/CompilationSubClassTests.swift index 494e099f9..5438638ba 100644 --- a/Tests/GRDBTests/CompilationSubClassTests.swift +++ b/Tests/GRDBTests/CompilationSubClassTests.swift @@ -13,7 +13,6 @@ private class UserRecord : Record { override class var databaseSelection: [any 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) } 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 4c1dae91c..ebc73c3a8 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -377,49 +377,7 @@ 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() { let person = Person(name: "Arthur", age: 41) let changes = person.databaseChanges @@ -704,48 +662,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() From 927fc21f00320ade975dd031b7f7a17124f057cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Thu, 28 Jul 2022 14:29:28 +0200 Subject: [PATCH 34/73] NEW: ValueObservation.map accepts a throwing closure This will allow us to call a throwing FetchableRecord.init(row:) from this operator --- CHANGELOG.md | 1 + .../ValueConcurrentObserver.swift | 52 +++++++++++------- GRDB/ValueObservation/ValueReducer/Map.swift | 12 ++--- .../ValueReducer/RemoveDuplicates.swift | 4 +- .../ValueObservation/ValueReducer/Trace.swift | 4 +- .../ValueReducer/ValueReducer.swift | 2 +- .../ValueWriteOnlyObserver.swift | 54 ++++++++++++------- 7 files changed, 79 insertions(+), 50 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 096550d9a..5fa8b7156 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -104,6 +104,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: The `Record.copy()` method was removed, without replacement. - **New**: 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). - **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`. +- **New**: `ValueObservation.map` now accepts a throwing closure argument. ## 5.26.0 diff --git a/GRDB/ValueObservation/ValueConcurrentObserver.swift b/GRDB/ValueObservation/ValueConcurrentObserver.swift index 25dc0d8a1..9a6a5588c 100644 --- a/GRDB/ValueObservation/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/ValueConcurrentObserver.swift @@ -279,8 +279,8 @@ extension ValueConcurrentObserver { } // Reduce - let initialValue = 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 @@ -344,15 +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 { - let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } - guard let onChange 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) } } @@ -435,15 +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 { - let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } - guard let onChange 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 { @@ -557,7 +569,7 @@ 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 { 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 1b9ced0c3..604acbffe 100644 --- a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/ValueWriteOnlyObserver.swift @@ -207,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") } @@ -241,15 +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 { - let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } - guard let onChange 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 { @@ -385,15 +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 { - let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } - guard let onChange 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 { From 895964de1616f2c55c547f43260b400a9af31ade Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Thu, 28 Jul 2022 14:36:34 +0200 Subject: [PATCH 35/73] BREAKING: Throwing FetchableRecord.init(row:) --- CHANGELOG.md | 1 + Documentation/AssociationsBasics.md | 8 +- Documentation/GRDB6MigrationGuide.md | 57 +++ .../Contents.swift | 469 ------------------ .../contents.xcplayground | 4 - GRDB.xcworkspace/contents.xcworkspacedata | 3 - GRDB/Core/Row.swift | 32 +- .../SQLGeneration/SQLQueryGenerator.swift | 6 +- GRDB/Record/FetchableRecord+Decodable.swift | 8 +- GRDB/Record/FetchableRecord.swift | 12 +- GRDB/Record/Record.swift | 2 +- README.md | 18 +- ...ciationBelongsToFetchableRecordTests.swift | 12 +- ...ionHasOneThroughFetchableRecordTests.swift | 20 +- ...ciationPrefetchingCodableRecordTests.swift | 90 ++-- .../AssociationRowScopeSearchTests.swift | 4 +- Tests/GRDBTests/ColumnExpressionTests.swift | 4 +- .../GRDBTests/CompilationProtocolTests.swift | 4 + .../GRDBTests/CompilationSubClassTests.swift | 2 +- .../FetchableRecordDecodableTests.swift | 70 +-- ...MutablePersistableRecordChangesTests.swift | 4 +- .../Record+QueryInterfaceRequestTests.swift | 4 +- Tests/GRDBTests/RecordEditedTests.swift | 20 +- Tests/GRDBTests/RecordInitializersTests.swift | 30 +- ...imalNonOptionalPrimaryKeySingleTests.swift | 4 +- .../RecordMinimalPrimaryKeyRowIDTests.swift | 4 +- .../RecordMinimalPrimaryKeySingleTests.swift | 4 +- .../RecordPrimaryKeyHiddenRowIDTests.swift | 4 +- .../RecordPrimaryKeyMultipleTests.swift | 4 +- .../GRDBTests/RecordPrimaryKeyNoneTests.swift | 4 +- .../RecordPrimaryKeyRowIDTests.swift | 4 +- .../RecordPrimaryKeySingleTests.swift | 4 +- ...leWithReplaceConflictResolutionTests.swift | 4 +- Tests/GRDBTests/RecordSubClassTests.swift | 12 +- .../RecordWithColumnNameManglingTests.swift | 4 +- ...bservationQueryInterfaceRequestTests.swift | 4 +- .../FetchRecordClassTests.swift | 4 +- .../GRDBProfiling/AppDelegate.swift | 4 +- 38 files changed, 264 insertions(+), 684 deletions(-) delete mode 100644 Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift delete mode 100644 Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/contents.xcplayground diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fa8b7156..2571699f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -102,6 +102,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: The `selectID()` method is replaced with `selectPrimaryKey(as:)`. - **Breaking**: `Cursor.isEmpty` is now a throwing property, instead of a method. - **Breaking**: The `Record.copy()` method was removed, without replacement. +- **Breaking**: The `FetchableRecord.init(row:)` initializer can now throw errors. - **New**: 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). - **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`. - **New**: `ValueObservation.map` now accepts a throwing closure argument. diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index e59ab6534..5242404c6 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -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"] } } diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index 27a54fdc8..a37188fba 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -6,6 +6,7 @@ Migrating 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) @@ -42,6 +43,62 @@ Request protocols now come with a primary associated type, enabled by [SE-0346]( 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 ... + } + } + } + ``` + +
+ + ## Other Changes - The initializer of in-memory databases can now throw errors: diff --git a/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift b/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift deleted file mode 100644 index fbb1d4377..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 = try 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/GRDB.xcworkspace/contents.xcworkspacedata b/GRDB.xcworkspace/contents.xcworkspacedata index f80b4fd89..1fec2cce9 100644 --- a/GRDB.xcworkspace/contents.xcworkspacedata +++ b/GRDB.xcworkspace/contents.xcworkspacedata @@ -10,9 +10,6 @@ - - diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index dfb738a66..b2f56c2a0 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -487,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"] @@ -499,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"] @@ -522,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"] @@ -534,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"] @@ -557,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"] @@ -579,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"] @@ -872,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"] @@ -884,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"] @@ -904,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. @@ -914,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"] @@ -926,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"] @@ -973,7 +973,7 @@ extension Row { scope \(String(reflecting: scope)) only contains null values """)) } - return Record(row: scopedRow) + return try Record(row: scopedRow) } } @@ -987,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"] @@ -1026,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 } @@ -1038,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"] @@ -1072,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 } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 1ceaea2d9..4e8ec40ae 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -458,7 +458,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,7 +468,7 @@ 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"] @@ -644,7 +644,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/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 1bf3de91e..90aafb05d 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) } } @@ -342,7 +340,7 @@ private struct _RowDecoder: Decoder { { 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) diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index bb2932dd5..b675ef632 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 @@ -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) } @@ -535,8 +535,8 @@ public final class RecordCursor: DatabaseCursor { } /// :nodoc: - public func _element(sqliteStatement: SQLiteStatement) -> Record { - Record(row: row) + public func _element(sqliteStatement: SQLiteStatement) throws -> Record { + try Record(row: row) } } diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 9aa62c713..a0006c135 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. // diff --git a/README.md b/README.md index cd778ba04..4d8c722c6 100644 --- a/README.md +++ b/README.md @@ -2663,7 +2663,7 @@ Details follow: ```swift protocol FetchableRecord { /// Row initializer - init(row: Row) + init(row: Row) throws } ``` @@ -3334,14 +3334,14 @@ 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 @@ -3717,12 +3717,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 @@ -3953,14 +3949,14 @@ 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 @@ -6284,7 +6280,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]: @@ -6300,7 +6296,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:) } ``` diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift index a0efecca4..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"] } } diff --git a/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift b/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift index 06ea3a483..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"] } diff --git a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift index 4c7635125..f981209ba 100644 --- a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift @@ -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/AssociationRowScopeSearchTests.swift b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift index e1c05d05e..ba579efc3 100644 --- a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift +++ b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift @@ -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/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/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 1c4f259f5..2a37b5e6d 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -111,6 +111,10 @@ private class UserFetchableRecord2 : FetchableRecord { required init(row: Row) { } } +private struct UserFetchableRecord3 : FetchableRecord { + init(row: Row) throws { } +} + // MARK: - StatementColumnConvertible private struct UserStatementColumnConvertible1 : StatementColumnConvertible { diff --git a/Tests/GRDBTests/CompilationSubClassTests.swift b/Tests/GRDBTests/CompilationSubClassTests.swift index 5438638ba..5e5a2a485 100644 --- a/Tests/GRDBTests/CompilationSubClassTests.swift +++ b/Tests/GRDBTests/CompilationSubClassTests.swift @@ -7,7 +7,7 @@ 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: [any SQLSelectable] { super.databaseSelection } 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/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index a069f292d..d1a4f6e74 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -289,11 +289,11 @@ 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) { diff --git a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift index fc78aec09..1ee400cb6 100644 --- a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift @@ -13,11 +13,11 @@ 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 { diff --git a/Tests/GRDBTests/RecordEditedTests.swift b/Tests/GRDBTests/RecordEditedTests.swift index ebc73c3a8..94d2de96a 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -31,12 +31,12 @@ 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) { @@ -70,9 +70,9 @@ 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) { @@ -100,12 +100,12 @@ 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) { @@ -144,11 +144,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) } @@ -398,8 +398,8 @@ class RecordEditedTests: GRDBTestCase { } } - func testChangesAfterInitFromRow() { - let person = Person(row: Row(["name": "Arthur", "age": 41])) + func testChangesAfterInitFromRow() throws { + let person = try Person(row: Row(["name": "Arthur", "age": 41])) let changes = person.databaseChanges XCTAssertEqual(changes.count, 4) for (column, old) in changes { 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 17a1fefd1..64f1ed9a5 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -23,9 +23,9 @@ 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) { diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 688eabd2f..beae0f620 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -22,9 +22,9 @@ 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) { diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 27d635e89..69e1f7c8d 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -21,9 +21,9 @@ 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) { diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 8c2487690..d293a6838 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -35,12 +35,12 @@ private class Person : Record, Hashable { "persons" } - required init(row: Row) { + required init(row: Row) throws { id = row[.rowID] 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) { diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index ac74dda2f..0ce7a45d7 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -30,11 +30,11 @@ 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) { diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index 969b8dab8..5581cca55 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -28,10 +28,10 @@ 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) { diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index 8ffc8c00c..ebdc8891b 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -32,12 +32,12 @@ 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) { diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index 3ae89c19a..26d27929a 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -26,10 +26,10 @@ 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) { diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index 5ee5efc71..977d5f1d1 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -25,10 +25,10 @@ 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) { diff --git a/Tests/GRDBTests/RecordSubClassTests.swift b/Tests/GRDBTests/RecordSubClassTests.swift index 73f3fded2..e75187f62 100644 --- a/Tests/GRDBTests/RecordSubClassTests.swift +++ b/Tests/GRDBTests/RecordSubClassTests.swift @@ -31,12 +31,12 @@ 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) { @@ -65,9 +65,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,9 +86,9 @@ 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 { diff --git a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift index 3b2c05b36..e5dd27106 100644 --- a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift +++ b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift @@ -23,12 +23,12 @@ 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) { 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/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/GRDBProfiling/GRDBProfiling/AppDelegate.swift b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift index e8c161540..ad7fa84ea 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift @@ -361,7 +361,7 @@ class ItemRecord : Record { "items" } - required init(row: GRDB.Row) { + required init(row: GRDB.Row) throws { i0 = row["i0"] i1 = row["i1"] i2 = row["i2"] @@ -372,7 +372,7 @@ class ItemRecord : Record { i7 = row["i7"] i8 = row["i8"] i9 = row["i9"] - super.init(row: row) + try super.init(row: row) } override func encode(to container: inout PersistenceContainer) { From eb985419237cbc789275e6907b5a6c31a71de1b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2022 19:05:48 +0200 Subject: [PATCH 36/73] Documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d8c722c6..366d3f305 100644 --- a/README.md +++ b/README.md @@ -3119,7 +3119,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', From c26ed6c28026870a868678711317f7f1f75018c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jul 2022 19:10:29 +0200 Subject: [PATCH 37/73] NEW: throw decoding errors --- CHANGELOG.md | 1 + GRDB/Core/DatabaseValueConvertible.swift | 5 +- GRDB/Core/StatementColumnConvertible.swift | 5 +- TODO.md | 7 +- .../DatabaseDateDecodingStrategyTests.swift | 301 +++++++++--------- .../DatabaseValueConversionErrorTests.swift | 100 ++---- 6 files changed, 179 insertions(+), 240 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2571699f3..d745930e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -106,6 +106,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: 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). - **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`. - **New**: `ValueObservation.map` now accepts a throwing closure argument. +- **New**: Value requests now throw an error when they find unexpected database values (they used to crash in GRDB 5). ## 5.26.0 diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index ae15394cf..c504934fe 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -130,9 +130,8 @@ public final class DatabaseValueCursor: Databas } /// :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))) diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 7a2d458b7..571b6404c 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -170,9 +170,8 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible /// :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))) diff --git a/TODO.md b/TODO.md index 6bd61e623..38133d238 100644 --- a/TODO.md +++ b/TODO.md @@ -27,9 +27,10 @@ - [X] RangeReplaceableCollection should have append(contentsOf: cursor) - [ ] GRDB 6: choose persistence table - [ ] GRDB 6: decoding errors - - [ ] throwing FetchableRecord initializer FIRST - - [ ] throwing Decodable FetchableRecord initializer SECOND - - [ ] deal with as much value decoding error as possible + - [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: encoding errors for record (`EncodableRecord.encode(to:)`) - [ ] throwing EncodableRecord.encode FIRST - [?] GRDB 6: protocol-based record container? This could avoid computing & encoding values we do not need. diff --git a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift index 331ed23c2..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 } @@ -190,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") + } + } } } } @@ -233,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") + } + } } } } @@ -278,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") + } + } } } } @@ -333,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") + } + } } } } @@ -383,27 +379,26 @@ extension DatabaseDateDecodingStrategyTests { XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) } -// 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") -// } -// } + // 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") + } + } } } } @@ -430,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") + } + } } } } @@ -468,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/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"], \ From 80ec31f5881856f88bcdd30ce692253aebd85187 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Jul 2022 15:37:22 +0200 Subject: [PATCH 38/73] BREAKING: remove DerivableRequest.limit(_:offset:) --- CHANGELOG.md | 1 + Documentation/GRDB6MigrationGuide.md | 15 ++++++++ GRDB/Fixits.swift | 5 +++ .../Request/Association/Association.swift | 14 ------- .../Request/QueryInterfaceRequest.swift | 2 +- .../Request/RequestProtocols.swift | 30 --------------- .../AssociationPrefetchingSQLTests.swift | 37 ------------------- 7 files changed, 22 insertions(+), 82 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d745930e6..88962a6e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -103,6 +103,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: `Cursor.isEmpty` is now a throwing property, instead of a method. - **Breaking**: The `Record.copy()` method was removed, without replacement. - **Breaking**: The `FetchableRecord.init(row:)` initializer can now throw errors. +- **Breaking**: The `DerivableRequest.limit(_:offset_:)` method was removed, without replacement. - **New**: 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). - **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`. - **New**: `ValueObservation.map` now accepts a throwing closure argument. diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index a37188fba..dcf2d49ef 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -126,3 +126,18 @@ The record protocols have been refactored. We tried to keep the amount of modifi ``` - 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)) + ``` diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index dcd78178e..74af3ae20 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -1,6 +1,11 @@ // 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() } diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index a78763445..f89a9e13d 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -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/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 42e9eba0f..d3cd991e5 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -361,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) } diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index e70216489..e1439c5d6 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -762,20 +762,6 @@ public protocol DerivableRequest: AggregatingRequest, FilteredReques /// 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 @@ -810,22 +796,6 @@ public protocol DerivableRequest: AggregatingRequest, FilteredReques } 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/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 140520cc4..5a96828c6 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -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 { From 49a66e197b97543ed400594ca4b5b4c297105627 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Jul 2022 15:47:27 +0200 Subject: [PATCH 39/73] Foster some FetchRequest<...> in the documentation --- README.md | 4 ++-- Tests/GRDBTests/JoinSupportTests.swift | 19 +++++++++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 366d3f305..382990159 100644 --- a/README.md +++ b/README.md @@ -5794,7 +5794,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: @@ -5887,7 +5887,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), diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index ed676751f..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: [ From 36892fee55515f5b6831795ed087e8e75101e63a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Jul 2022 16:03:20 +0200 Subject: [PATCH 40/73] BREAKING: Bump minimum SQLite version to 3.19.3 --- CHANGELOG.md | 2 +- Documentation/GRDB6MigrationGuide.md | 1 + GRDB.swift.podspec | 2 +- GRDB/Core/Database+Schema.swift | 21 ++-------------- GRDB/Core/Database+Statements.swift | 2 -- GRDB/Core/Database.swift | 2 -- GRDB/Core/StatementAuthorizer.swift | 13 ---------- GRDB/Core/TransactionObserver.swift | 3 +-- .../Request/QueryInterfaceRequest.swift | 10 +------- GRDB/QueryInterface/SQL/SQLExpression.swift | 7 +----- README.md | 2 +- Tests/GRDBTests/ColumnInfoTests.swift | 20 +--------------- .../DatabaseConfigurationTests.swift | 6 ++--- Tests/GRDBTests/DatabaseRegionTests.swift | 24 +++++-------------- Tests/GRDBTests/DatabaseTests.swift | 10 -------- Tests/GRDBTests/SelectStatementTests.swift | 22 ++++------------- 16 files changed, 23 insertions(+), 124 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 88962a6e3..f67952c65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -96,7 +96,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## 6.0.0 - **Breaking**: Swift 5.7+ and Xcode 14+ are required. -- **Breaking**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ are required. +- **Breaking**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ / SQLite 3.19.3+ are required. - **Breaking**: Removed deprecated methods - **Breaking**: The in-memory `DatabaseQueue()` initializer can now throw errors. - **Breaking**: The `selectID()` method is replaced with `selectPrimaryKey(as:)`. diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index dcf2d49ef..5f86719c8 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -26,6 +26,7 @@ GRDB requirements have been bumped: - **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 diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 6e664a7d3..36bf19774 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -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/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 9d7931178..f834e57b0 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -572,14 +572,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 @@ -731,17 +723,8 @@ public struct ColumnInfo: FetchableRecord { /// 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: diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 4ef866d23..34abd03b0 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -455,10 +455,8 @@ struct StatementCache { #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) } 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 36c3fc5f8..90594dae8 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -617,8 +617,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // 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 os(Linux) let dbPointer = Unmanaged.passUnretained(self).toOpaque() sqlite3_trace(sqliteConnection, { (dbPointer, sql) in diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 255dc0a56..668c45601 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -152,19 +152,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: diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index afb881494..43c2bb220 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -737,8 +737,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 diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index d3cd991e5..904d42487 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -639,15 +639,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 { diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 249f2e4f9..bc9de466e 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -372,12 +372,7 @@ public struct SQLExpression { // 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. diff --git a/README.md b/README.md index 382990159..e01899368 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ **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 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) -**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.8.5+ • Swift 5.7+ / Xcode 14+ +**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 | | -------------- | ----------------------------------------------------------- | diff --git a/Tests/GRDBTests/ColumnInfoTests.swift b/Tests/GRDBTests/ColumnInfoTests.swift index 267404087..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") diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index 84232185d..79a5dcfbf 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -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/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 64ad3955f..d804efd4d 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -305,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(table: "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(table: "foo") - XCTAssertEqual(statement.databaseRegion, expectedRegion) - XCTAssertEqual(statement.databaseRegion.description, "FOO(*)") - } + let expectedRegion = DatabaseRegion(table: "foo") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "FOO(*)") } } } 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/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index a71576d4b..a63cc1e4d 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -334,23 +334,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 +350,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 +359,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 +375,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]) From b2eafd4a13eac543bc52f0434127b0f5600f757b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Jul 2022 16:34:21 +0200 Subject: [PATCH 41/73] SE-0361: Extensions on bound generic types https://github.com/apple/swift-evolution/blob/main/proposals/0361-bound-generic-extensions.md --- Documentation/GRDB6MigrationGuide.md | 11 +++++++++++ Documentation/GoodPracticesForDesigningRecordTypes.md | 4 ++-- GRDB/Core/Row.swift | 4 ++-- GRDB/Core/SQL.swift | 4 ++-- GRDB/Core/SQLRequest.swift | 2 +- GRDB/Fixits.swift | 2 +- .../Request/CommonTableExpression.swift | 2 +- .../Request/QueryInterfaceRequest.swift | 2 +- GRDB/QueryInterface/SQL/SQLExpression.swift | 2 +- GRDB/QueryInterface/SQL/SQLOperators.swift | 4 ++-- GRDB/QueryInterface/SQL/SQLSelection.swift | 2 +- .../SQLGeneration/SQLGenerationContext.swift | 2 +- .../AssociationBelongsToDecodableRecordTests.swift | 2 +- Tests/GRDBTests/TableRecordUpdateTests.swift | 2 +- 14 files changed, 28 insertions(+), 17 deletions(-) diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index 5f86719c8..c28a0a52f 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -42,6 +42,17 @@ Request protocols now come with a primary associated type, enabled by [SE-0346]( } ``` +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 diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 8eef81786..284ce79af 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -368,8 +368,8 @@ 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 selectId() -> QueryInterfaceRequest { selectPrimaryKey(as: Int64.self) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index b2f56c2a0..d5aa1fd45 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1433,7 +1433,7 @@ extension Row { } } -extension FetchRequest where RowDecoder == Row { +extension FetchRequest { // MARK: Fetching Rows @@ -1925,7 +1925,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() diff --git a/GRDB/Core/SQL.swift b/GRDB/Core/SQL.swift index 3f9ae00d9..0418b8a02 100644 --- a/GRDB/Core/SQL.swift +++ b/GRDB/Core/SQL.swift @@ -196,7 +196,7 @@ extension SQL: SQLOrderingTerm { } } -extension Sequence where Element == SQL { +extension Sequence { /// Returns the concatenated `SQL` literal of this sequence of literals, /// inserting the given separator between each element. /// @@ -215,7 +215,7 @@ 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. /// diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index ae6bf582a..1d97599e2 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -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. /// diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 74af3ae20..31c2f55e8 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -89,7 +89,7 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { @available(*, unavailable, renamed: "Statement") public typealias UpdateStatement = Statement -extension ValueObservation where Reducer == ValueReducers.Auto { +extension ValueObservation { @available(*, unavailable, renamed: "tracking(_:)") public static func trackingVaryingRegion( _ fetch: @escaping (Database) throws -> Value) diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index b5e07e947..26392b01e 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -151,7 +151,7 @@ extension CommonTableExpression { } } -extension CommonTableExpression where RowDecoder == Row { +extension CommonTableExpression { /// Creates a common table expression from a request. /// /// For example: diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 904d42487..e94aa77b4 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -805,7 +805,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]] { diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index bc9de466e..04fe96e7c 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1734,7 +1734,7 @@ extension Sequence where Element: SQLSpecificExpressible { } } -extension Sequence where Element == any SQLSpecificExpressible { +extension Sequence { /// Returns an expression by joining all elements with an associative SQL /// binary operator. /// diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index e8ec42407..af367909c 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -326,7 +326,7 @@ 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. /// @@ -337,7 +337,7 @@ extension Sequence where Self.Iterator.Element: SQLExpressible { } } -extension Sequence where Self.Iterator.Element == SQLExpressible { +extension Sequence { /// An SQL expression that checks the inclusion of an expression in /// a sequence. /// diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index f2da3af91..e8f64b038 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -231,7 +231,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, diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index a761c8de8..397a750d3 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -451,7 +451,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/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift index 9431170df..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)) } diff --git a/Tests/GRDBTests/TableRecordUpdateTests.swift b/Tests/GRDBTests/TableRecordUpdateTests.swift index 4154bdf30..c61353e6a 100644 --- a/Tests/GRDBTests/TableRecordUpdateTests.swift +++ b/Tests/GRDBTests/TableRecordUpdateTests.swift @@ -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) } From 9a9406a69d0e7b4e4e332f4a8eb11dc5bcfdbe7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Jul 2022 16:37:54 +0200 Subject: [PATCH 42/73] SE-0353: Constrained Existential Types https://github.com/apple/swift-evolution/blob/main/proposals/0353-constrained-existential-types.md --- GRDB/Core/DatabaseWriter.swift | 4 ++-- GRDB/Migration/DatabaseMigrator.swift | 4 +--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 05661e450..83ebc6e00 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -625,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) @@ -636,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 diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 79a684f68..c2f1472e5 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -481,9 +481,7 @@ extension DatabaseMigrator { promise(dbResult.map { _ in }) } } - .eraseToAnyPublisher() .receiveValues(on: scheduler) - .eraseToAnyPublisher() ) } } @@ -498,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) From 070ee2c7965f0100b5f9f65648b8d43aece9ece9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Jul 2022 12:47:09 +0200 Subject: [PATCH 43/73] Makefile: disable -warn-concurrency and -enable-actor-data-race-checks This creates issues with Xcode 14 beta 4 --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index f68c38d54..dc724ad20 100644 --- a/Makefile +++ b/Makefile @@ -57,7 +57,7 @@ ifeq ($(XCODEVERSION),14.0) MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=12.4" MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=16.0" #MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore - OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks' + OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' # -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks' GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' else # Swift 5.3 required: Xcode < 12.0 is not supported From e5d10ed8c1b14c7112608455b336c7bc446e4946 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Jul 2022 13:39:44 +0200 Subject: [PATCH 44/73] fix async AppDatabaseTests tests --- .../GRDBAsyncDemoTests/AppDatabaseTests.swift | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift index 2d0dd4ef8..29de329fe 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift @@ -29,7 +29,8 @@ 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 { @@ -76,7 +77,8 @@ 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 { @@ -94,7 +96,8 @@ 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 { @@ -106,7 +109,8 @@ class AppDatabaseTests: XCTestCase { 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 { From 2f2cccacf9ef2befc89522856a3c36b87cba8968 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Jul 2022 13:40:39 +0200 Subject: [PATCH 45/73] Remove UI tests of demo apps, since GRDBQuery is tested on its own (Don't test the framework) --- .../GRDBAsyncDemo.xcodeproj/project.pbxproj | 119 ------------------ .../xcschemes/GRDBAsyncDemo.xcscheme | 10 -- .../GRDBAsyncDemoUITests.swift | 81 ------------ .../GRDBAsyncDemoUITests/Info.plist | 22 ---- .../GRDBCombineDemo.xcodeproj/project.pbxproj | 119 ------------------ .../xcschemes/GRDBCombineDemo.xcscheme | 10 -- .../GRDBCombineDemoUITests.swift | 81 ------------ .../GRDBCombineDemoUITests/Info.plist | 22 ---- 8 files changed, 464 deletions(-) delete mode 100644 Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoUITests/GRDBAsyncDemoUITests.swift delete mode 100644 Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoUITests/Info.plist delete mode 100644 Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoUITests/GRDBCombineDemoUITests.swift delete mode 100644 Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoUITests/Info.plist 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 2cc6c09fb..42aed0aa2 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme @@ -38,16 +38,6 @@ ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj"> - - - - 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/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 1bd57e218..6eadb0a3a 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme @@ -38,16 +38,6 @@ ReferencedContainer = "container:GRDBCombineDemo.xcodeproj"> - - - - 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 - - From 087931164633f59a0e027ea6814363143a3bc494 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Tue, 16 Aug 2022 12:36:40 +0200 Subject: [PATCH 46/73] Make TransactionObserver.swift easier to read Add some documentation, and rename some types and variables. --- GRDB/Core/Database.swift | 12 +- GRDB/Core/Statement.swift | 22 +- GRDB/Core/StatementAuthorizer.swift | 25 ++- GRDB/Core/TransactionObserver.swift | 249 ++++++++++++++-------- Tests/GRDBTests/DatabaseRegionTests.swift | 28 +-- 5 files changed, 205 insertions(+), 131 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 90594dae8..a7a171f93 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -319,19 +319,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) 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 { diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 56f3a86ae..88c2b6f71 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -37,18 +37,21 @@ public final class Statement { return (0.. + .fromOpaque(authorizerP.unsafelyUnwrapped) + .takeUnretainedValue() + .authorize(actionCode, cString1, cString2, cString3, cString4) + }, + authorizerP) + } + /// Reset before compiling a new statement func reset() { selectedRegion = DatabaseRegion() @@ -36,7 +51,7 @@ final class StatementAuthorizer { isDropStatement = false } - func authorize( + private func authorize( _ actionCode: Int32, _ cString1: UnsafePointer?, _ cString2: UnsafePointer?, @@ -159,7 +174,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 diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 43c2bb220..6506af4b9 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -17,8 +17,8 @@ extension Database { // 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) } @@ -29,8 +29,8 @@ extension Database { // 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) } @@ -71,9 +71,9 @@ extension Database { add(transactionObserver: CommitHandler(closure), 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 @@ -169,20 +169,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() + } } } } @@ -201,17 +213,18 @@ class DatabaseObservationBroker { transactionObservations.removeFirst { $0.isWrapping(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 +243,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 +264,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 +286,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 +332,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 +349,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 +368,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 +389,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 +411,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 +436,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 @@ -511,15 +528,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 +591,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 +611,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 +623,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 +676,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) } } @@ -799,9 +828,9 @@ 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: (any TransactionObserver)? private var strongObserver: (any TransactionObserver)? @@ -829,19 +858,18 @@ final class TransactionObservation { } 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) } @@ -858,6 +886,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) } @@ -873,6 +902,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) } @@ -880,7 +910,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 @@ -1328,28 +1370,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 + + /// 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 } diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index d804efd4d..11a02dedd 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -524,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 } @@ -535,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 } @@ -592,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 } @@ -602,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 } @@ -612,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 } @@ -629,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 } @@ -644,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 } From fb6ea57d74c2be6457a03c1961d84f43591e8d29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Tue, 16 Aug 2022 12:54:40 +0200 Subject: [PATCH 47/73] =?UTF-8?q?Don=E2=80=99t=20setup=20database=20observ?= =?UTF-8?q?ation=20in=20read-only=20connections.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Observation of read-only connections has turned useless since read-only transactions are no longer reported to TransactionObserver, in #1213 --- GRDB/Core/Database+Statements.swift | 6 +++--- GRDB/Core/Database.swift | 12 ++++++++---- GRDB/Core/StatementAuthorizer.swift | 15 +++++++++------ GRDB/Core/TransactionObserver.swift | 4 ++++ 4 files changed, 24 insertions(+), 13 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 34abd03b0..df71e9189 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -389,7 +389,7 @@ extension Database { } // Database observation: prepare transaction observers. - observationBroker.statementWillExecute(statement) + observationBroker?.statementWillExecute(statement) } /// May throw a cancelled commit error, if a transaction observer cancels @@ -400,7 +400,7 @@ extension Database { clearSchemaCache() } - try observationBroker.statementDidExecute(statement) + try observationBroker?.statementDidExecute(statement) } /// Always throws an error @@ -416,7 +416,7 @@ extension Database { /// Exposes the user-provided cancelled commit error, if a transaction /// observer has cancelled a transaction. - try observationBroker.statementDidFail(statement) + try observationBroker?.statementDidFail(statement) throw DatabaseError( resultCode: resultCode, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index a7a171f93..455be5976 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -154,7 +154,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // Database observation lazy var authorizer = StatementAuthorizer(self) - lazy var observationBroker = DatabaseObservationBroker(self) + private(set) var observationBroker: DatabaseObservationBroker? /// The list of compile options used when building SQLite static func sqliteCompileOptions() throws -> Set { @@ -196,6 +196,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 { @@ -237,9 +243,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib setupDefaultFunctions() setupDefaultCollations() setupAuthorizer() - if !configuration.readonly { - observationBroker.installCommitAndRollbackHooks() - } + observationBroker?.installCommitAndRollbackHooks() try activateExtendedCodes() #if SQLITE_HAS_CODEC diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 267d4a276..3eec7d82e 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -106,18 +106,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 diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 6506af4b9..f6fd6f044 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -5,6 +5,8 @@ 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 @@ -14,6 +16,7 @@ extension Database { 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. @@ -26,6 +29,7 @@ extension Database { /// Remove a transaction observer. 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. From 065880802892f094d74e149fe445ec0c1bd85290 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Tue, 16 Aug 2022 15:39:02 +0200 Subject: [PATCH 48/73] Make Database.swift easier to read Enhance documentation, and rename some types and variables. --- GRDB/Core/Database+Schema.swift | 49 +++++--- GRDB/Core/Database.swift | 168 ++++++++++++++++++---------- GRDB/Core/StatementAuthorizer.swift | 8 +- 3 files changed, 154 insertions(+), 71 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index f834e57b0..da9d93fba 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -1,4 +1,29 @@ extension Database { + /// 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() + } + } + /// A SQLite schema. See enum SchemaIdentifier: Hashable { /// The main database @@ -29,7 +54,7 @@ extension Database { } } - /// A table identifier + /// The identifier of a database table or view. struct TableIdentifier { /// The SQLite schema var schemaID: SchemaIdentifier @@ -69,8 +94,8 @@ extension Database { /// since this method was last called. func clearSchemaCacheIfNeeded() throws { let schemaVersion = try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version")) - if _lastSchemaVersion != schemaVersion { - _lastSchemaVersion = schemaVersion + if lastSchemaVersion != schemaVersion { + lastSchemaVersion = schemaVersion clearSchemaCache() } } @@ -151,10 +176,7 @@ extension Database { private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool { // 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`. @@ -1032,12 +1054,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.swift b/GRDB/Core/Database.swift index 455be5976..daa45a3ba 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -127,33 +127,39 @@ 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: CInt? - 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) + + /// 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 @@ -163,28 +169,42 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } } - /// 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 @@ -373,6 +393,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } configuration.SQLiteConnectionWillClose?(sqliteConnection) + + // Finalize all cached statements since they would prevent + // immediate connection closing. internalStatementCache.clear() publicStatementCache.clear() @@ -383,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 @@ -413,6 +437,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } configuration.SQLiteConnectionWillClose?(sqliteConnection) + + // Finalize all cached statements since they would prevent + // immediate connection closing. internalStatementCache.clear() publicStatementCache.clear() @@ -519,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( @@ -543,13 +573,25 @@ 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] func recordingSelection(_ region: inout DatabaseRegion, _ block: () throws -> T) rethrows -> T { if region.isFullDatabase { return try block() @@ -764,7 +806,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 @@ -785,7 +827,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib return journalMode } - /// Throws SQLITE_ABORT for suspended databases, if statement would lock + /// 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). func checkForSuspensionViolation(from statement: Statement) throws { @@ -832,22 +874,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, @@ -866,6 +910,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 ...") @@ -876,26 +922,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 { @@ -954,6 +1003,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() @@ -971,6 +1021,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 ...") @@ -984,7 +1036,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 { @@ -1020,6 +1073,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 { @@ -1076,16 +1130,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. @@ -1149,6 +1204,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) diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 3eec7d82e..7e5224924 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -2,8 +2,12 @@ import Glibc #endif -/// A class that gathers information about one statement during its compilation, -/// with `sqlite3_set_authorizer`. +/// `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 From 5b7c58faf4fd6dd8432f91d21bbdebdf272714f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Tue, 16 Aug 2022 16:46:46 +0200 Subject: [PATCH 49/73] Make Database+Schema.swift easier to read --- GRDB/Core/Database+Schema.swift | 112 ++++++++++++------ .../Request/RequestProtocols.swift | 6 +- 2 files changed, 76 insertions(+), 42 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index da9d93fba..cc0fd9631 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -24,7 +24,7 @@ extension Database { } } - /// A SQLite schema. See + /// An SQLite schema. See enum SchemaIdentifier: Hashable { /// The main database case main @@ -35,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" @@ -59,7 +64,7 @@ extension Database { /// 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 @@ -85,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() } @@ -107,17 +112,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) } @@ -126,7 +131,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) @@ -159,14 +165,16 @@ extension Database { tableName.starts(with: "grdb_") } - /// 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) @@ -250,7 +258,7 @@ extension Database { primaryKey = .hiddenRowID case 1: // Single column - let pkColumn = pkColumns.first! + let pkColumn = pkColumns[0] // https://www.sqlite.org/lang_createtable.html: // @@ -296,12 +304,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). @@ -320,8 +337,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] { @@ -384,7 +402,17 @@ 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. + /// 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: some Sequence) @@ -485,6 +513,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 { @@ -497,20 +531,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? { @@ -621,9 +649,10 @@ 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. + /// 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) @@ -635,25 +664,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 } @@ -728,6 +758,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: """ @@ -1044,6 +1077,7 @@ enum SchemaObjectType: String { case view } +/// All objects in a database schema (tables, views, indexes, triggers). struct SchemaInfo: Equatable { private var objects: Set diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index e1439c5d6..d3e202a74 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -334,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: ", ")) """) } From 496c2ae359b99a28b381acc1b766dfe0b770fe68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Tue, 16 Aug 2022 17:38:06 +0200 Subject: [PATCH 50/73] Make Database+Statements.swift easier to read --- GRDB/Core/Database+Statements.swift | 62 ++++++++++++++++++++--------- GRDB/Core/Database.swift | 18 +++++++-- 2 files changed, 58 insertions(+), 22 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index df71e9189..2b8c477fe 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,6 +66,8 @@ extension Database { /// 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])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! @@ -105,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])! @@ -125,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])! @@ -169,6 +179,8 @@ extension Database { /// 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 (?); @@ -253,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"]) @@ -263,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. @@ -288,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 { @@ -300,6 +310,7 @@ extension Database { } } +/// A cursor over all statements in a SQL string. public class SQLStatementCursor: Cursor { private let database: Database private let cString: ContiguousArray @@ -321,17 +332,15 @@ 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 statement = try Statement( database: database, @@ -339,9 +348,11 @@ public class SQLStatementCursor: Cursor { 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 else { + // No statement found -> end of cursor. try checkArgumentsAreEmpty() return nil } @@ -378,12 +389,16 @@ 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) } @@ -400,13 +415,14 @@ extension Database { clearSchemaCache() } + // 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 + // 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 // @@ -414,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. + // 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) } } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index daa45a3ba..2da64ad0f 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -592,6 +592,14 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// 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() @@ -774,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 { @@ -827,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 { From e0786537dbf4c1457961eb04790f074ce133009d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Tue, 16 Aug 2022 17:49:41 +0200 Subject: [PATCH 51/73] BREAKING: replace Int32 with CInt everywhere it is possible --- GRDB/Core/Configuration.swift | 2 +- GRDB/Core/Database+Schema.swift | 4 +++ GRDB/Core/Database+Statements.swift | 12 ++++---- GRDB/Core/Database.swift | 20 ++++++------- GRDB/Core/DatabaseCollation.swift | 2 +- GRDB/Core/DatabaseFunction.swift | 26 ++++++++--------- GRDB/Core/DatabaseReader.swift | 4 +-- GRDB/Core/DatabaseValue.swift | 2 +- GRDB/Core/DatabaseValueConvertible.swift | 8 +++--- GRDB/Core/Row.swift | 24 ++++++++-------- GRDB/Core/RowDecodingError.swift | 4 +-- GRDB/Core/Statement.swift | 16 +++++------ GRDB/Core/StatementAuthorizer.swift | 6 ++-- GRDB/Core/StatementColumnConvertible.swift | 18 ++++++------ GRDB/Core/Support/Foundation/Data.swift | 24 ++++++++-------- .../Foundation/DatabaseDateComponents.swift | 2 +- GRDB/Core/Support/Foundation/Date.swift | 2 +- GRDB/Core/Support/Foundation/Decimal.swift | 2 +- GRDB/Core/Support/Foundation/UUID.swift | 2 +- ...aseValueConvertible+RawRepresentable.swift | 2 +- .../Support/StandardLibrary/Optional.swift | 4 +-- .../StandardLibrary/StandardLibrary.swift | 28 +++++++++---------- GRDB/Core/TransactionObserver.swift | 4 +-- GRDB/FTS/FTS4.swift | 2 +- GRDB/FTS/FTS5.swift | 4 +-- GRDB/FTS/FTS5CustomTokenizer.swift | 16 +++++------ GRDB/FTS/FTS5Tokenizer.swift | 28 +++++++++---------- GRDB/FTS/FTS5WrapperTokenizer.swift | 10 +++---- GRDB/Record/FetchableRecord+Decodable.swift | 8 +++--- .../GRDBTests/CompilationProtocolTests.swift | 12 ++++---- ...StatementColumnConvertibleFetchTests.swift | 2 +- 31 files changed, 152 insertions(+), 148 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index da2e43f2d..c18cf147e 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -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/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index cc0fd9631..b0d034aeb 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -98,6 +98,10 @@ 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 diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 2b8c477fe..e6b4d17cd 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -77,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( @@ -314,14 +314,14 @@ extension Database { 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 @@ -421,7 +421,7 @@ extension Database { /// Always throws an error @usableFromInline - func statementDidFail(_ statement: Statement, withResultCode resultCode: Int32) throws -> Never { + 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 @@ -477,11 +477,11 @@ 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, *) { - statement = try db.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT) + statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT)) } else { statement = try db.makeStatement(sql: sql) } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 2da64ad0f..5ca4fca52 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -137,7 +137,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// external connection modifies the schema. /// /// See `clearSchemaCacheIfNeeded()`. - var lastSchemaVersion: CInt? + var lastSchemaVersion: Int32? /// The cache for the available database schemas (main, temp, attached databases). var schemaCache = SchemaCache() @@ -230,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) @@ -301,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): @@ -670,7 +670,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib }, dbPointer) #else let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_trace_v2(sqliteConnection, UInt32(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in + 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 @@ -1311,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 { @@ -1323,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 @@ -1408,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))) @@ -1438,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) @@ -1495,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 @@ -1806,7 +1806,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/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 4c0dd8fb8..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 -> (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..( _ 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() } } @@ -166,8 +166,8 @@ public final class DatabaseFunction: Hashable { /// Feeds the `pApp` parameter of sqlite3_create_function_v2 /// private class FunctionDefinition { - let compute: (Int32, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)? - init(compute: @escaping (Int32, UnsafeMutablePointer?) + let compute: (CInt, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)? + init(compute: @escaping (CInt, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)?) { self.compute = compute @@ -197,7 +197,7 @@ public final class DatabaseFunction: Hashable { /// See private enum Kind { /// A regular function: SELECT f(1) - case function((Int32, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)?) + case function((CInt, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)?) /// An aggregate: SELECT f(foo) FROM bar GROUP BY baz case aggregate(() -> any DatabaseAggregate) @@ -215,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 @@ -233,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) @@ -290,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 }) { @@ -328,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) } } } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 800bb5c1c..b88cc459a 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -342,7 +342,7 @@ extension DatabaseReader { /// any `DatabaseError` that would happen while performing the backup. public func backup( to writer: some DatabaseWriter, - pagesPerStep: Int32 = -1, + 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 diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index e85f3013a..263018574 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -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 diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index c504934fe..84fb29e38 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -65,7 +65,7 @@ extension DatabaseValueConvertible { static func decode( fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, + atUncheckedIndex index: CInt, context: @autoclosure () -> RowDecodingContext) throws -> Self { @@ -78,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( @@ -108,13 +108,13 @@ public final class DatabaseValueCursor: Databas public let statement: Statement /// :nodoc: public var _isDone = false - private let columnIndex: Int32 + private let columnIndex: CInt 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 } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index d5aa1fd45..9081d9174 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -2103,7 +2103,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( @@ -2133,29 +2133,29 @@ private struct StatementRowImpl: RowImpl { { try Value.fastDecode( 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) } @@ -2182,11 +2182,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/RowDecodingError.swift b/GRDB/Core/RowDecodingError.swift index 657c110d6..cd4a9ef1e 100644 --- a/GRDB/Core/RowDecodingError.swift +++ b/GRDB/Core/RowDecodingError.swift @@ -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: ` diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 88c2b6f71..3cea80131 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -34,7 +34,7 @@ public final class Statement { /// 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) @@ -100,16 +100,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) @@ -151,7 +151,7 @@ public final class Statement { // Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)" fileprivate lazy var sqliteArgumentNames: [String?] = { - (0..?, _ cString2: UnsafePointer?, _ cString3: UnsafePointer?, _ cString4: UnsafePointer?) - -> Int32 + -> CInt { // Uncomment when debugging // print(""" @@ -195,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 571b6404c..5553c05dd 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -31,7 +31,7 @@ public protocol StatementColumnConvertible { /// - returns: A decoded value, or, if decoding is impossible, nil. static func fromStatement( _ sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32) + atUncheckedIndex index: CInt) -> Self? /// Creates a value from a raw SQLite statement pointer, if possible. @@ -39,7 +39,7 @@ public protocol StatementColumnConvertible { /// For example, here is the how Int64 adopts StatementColumnConvertible: /// /// extension Int64: StatementColumnConvertible { - /// init?(sqliteStatement: SQLiteStatement, index: Int32) { + /// init?(sqliteStatement: SQLiteStatement, index: CInt) { /// self = sqlite3_column_int64(sqliteStatement, index) /// } /// } @@ -52,7 +52,7 @@ public protocol StatementColumnConvertible { /// - 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: Int32) + init?(sqliteStatement: SQLiteStatement, index: CInt) } extension StatementColumnConvertible { @@ -60,7 +60,7 @@ extension StatementColumnConvertible { /// Default implementation fails on decoding NULL. @inline(__always) @inlinable - public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? { + public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? { if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { return nil } @@ -74,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 { @@ -95,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 @@ -106,7 +106,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { @inlinable static func fastDecode( fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, + atUncheckedIndex index: CInt, context: @autoclosure () -> RowDecodingContext) throws -> Self { @@ -147,13 +147,13 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible public let statement: Statement /// :nodoc: public var _isDone = false - @usableFromInline let columnIndex: Int32 + @usableFromInline let columnIndex: CInt 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 } 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 075a6f17f..37463d044 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -71,7 +71,7 @@ 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 } 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+RawRepresentable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift index 07ac9b1f3..a8c06371a 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift @@ -41,7 +41,7 @@ extension StatementBinding where Self: RawRepresentable, Self.RawValue: Statemen extension StatementColumnConvertible where Self: RawRepresentable, Self.RawValue: StatementColumnConvertible { @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { guard let rawValue = RawValue(sqliteStatement: sqliteStatement, index: index) else { return nil } diff --git a/GRDB/Core/Support/StandardLibrary/Optional.swift b/GRDB/Core/Support/StandardLibrary/Optional.swift index 9b77dfda8..4c9e3a3b9 100644 --- a/GRDB/Core/Support/StandardLibrary/Optional.swift +++ b/GRDB/Core/Support/StandardLibrary/Optional.swift @@ -75,7 +75,7 @@ extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvert extension Optional: StatementColumnConvertible where Wrapped: StatementColumnConvertible { @inline(__always) @inlinable - public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? { + public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? { if let value = Wrapped.fromStatement(sqliteStatement, atUncheckedIndex: index) { // Valid value return value @@ -88,7 +88,7 @@ extension Optional: StatementColumnConvertible where Wrapped: StatementColumnCon } } - public init?(sqliteStatement: SQLiteStatement, index: Int32) { + public init?(sqliteStatement: SQLiteStatement, index: CInt) { guard let value = Wrapped(sqliteStatement: sqliteStatement, index: index) else { return nil } diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index 69d2a966a..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)!) } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index f6fd6f044..9a825cbc9 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -984,7 +984,7 @@ protocol DatabaseEventProtocol { public struct DatabaseEvent { /// An event kind - public enum Kind: Int32 { + public enum Kind: CInt { /// SQLITE_INSERT case insert = 18 @@ -1091,7 +1091,7 @@ private struct CopiedDatabaseEventImpl: DatabaseEventImpl { public struct DatabasePreUpdateEvent { /// An event kind - public enum Kind: Int32 { + public enum Kind: CInt { /// SQLITE_INSERT case insert = 18 diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index 726e4c442..e08080082 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -288,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 4ac953388..ec53146b0 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -241,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 diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index 9d3bb4500..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 @@ -99,9 +99,9 @@ extension Database { func xCreateTokenizer( constructorPointer: UnsafeMutableRawPointer?, azArg: UnsafeMutablePointer?>?, - nArg: Int32, + nArg: CInt, tokenizerHandle: UnsafeMutablePointer?) - -> Int32 + -> CInt { guard let constructorPointer else { return SQLITE_ERROR @@ -126,12 +126,12 @@ extension Database { 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 else { return SQLITE_ERROR diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index 6410c6843..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 @@ -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 diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index ac2a46e39..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 } @@ -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/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 90aafb05d..9be222aec 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -509,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( @@ -522,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,7 +534,7 @@ extension DatabaseDateDecodingStrategy { /// - precondition: value is not NULL fileprivate func decode( fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, + atUncheckedIndex index: CInt, context: @autoclosure () -> RowDecodingContext) throws -> Date { @@ -589,7 +589,7 @@ extension DatabaseDateDecodingStrategy { fileprivate func decodeIfPresent( fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, + atUncheckedIndex index: CInt, context: @autoclosure () -> RowDecodingContext) throws -> Date? { diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 2a37b5e6d..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 @@ -118,19 +118,19 @@ private struct UserFetchableRecord3 : FetchableRecord { // 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 diff --git a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift index 87a83c933..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) } From 84940af3dcfa3b1be1125e8810aa9d234edfe958 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 17 Aug 2022 10:05:18 +0200 Subject: [PATCH 52/73] Cleanup statement separator character set --- GRDB/Core/Database.swift | 9 +++----- GRDB/Core/RowDecodingError.swift | 2 +- GRDB/Core/Statement.swift | 26 +++++++++++++++++----- Tests/GRDBTests/UpdateStatementTests.swift | 14 +++++++++--- 4 files changed, 36 insertions(+), 15 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 5ca4fca52..b42479448 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1681,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 } } } @@ -1709,8 +1707,7 @@ extension Database { return "" } defer { sqlite3_free(cString) } - return String(cString: cString) - .trimmingCharacters(in: .sqlStatementSeparators) + return String(cString: cString).trimmedSQLStatement } } diff --git a/GRDB/Core/RowDecodingError.swift b/GRDB/Core/RowDecodingError.swift index cd4a9ef1e..e2ca849d4 100644 --- a/GRDB/Core/RowDecodingError.swift +++ b/GRDB/Core/RowDecodingError.swift @@ -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/Statement.swift b/GRDB/Core/Statement.swift index 3cea80131..af5a8b875 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,8 +44,7 @@ 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. diff --git a/Tests/GRDBTests/UpdateStatementTests.swift b/Tests/GRDBTests/UpdateStatementTests.swift index 4834bf0d7..0db27cf65 100644 --- a/Tests/GRDBTests/UpdateStatementTests.swift +++ b/Tests/GRDBTests/UpdateStatementTests.swift @@ -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")) } From 4c73456f86909f7a9f27413ea84d670ac8509171 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 17 Aug 2022 11:24:34 +0200 Subject: [PATCH 53/73] Make SQL.swift easier to read --- GRDB/Core/SQL.swift | 78 +++++++++++++++++-- GRDB/QueryInterface/SQL/SQLOrdering.swift | 4 + GRDB/QueryInterface/SQL/SQLSelection.swift | 3 + .../SQLGeneration/SQLGenerationContext.swift | 22 +++++- 4 files changed, 98 insertions(+), 9 deletions(-) diff --git a/GRDB/Core/SQL.swift b/GRDB/Core/SQL.swift index 0418b8a02..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 @@ -185,12 +223,26 @@ 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) } @@ -198,7 +250,9 @@ extension SQL: SQLOrderingTerm { 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 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)) @@ -217,7 +274,9 @@ extension Sequence { 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 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/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/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index e8f64b038..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 diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 397a750d3..a4382cac2 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) } From 1bfba945d38cf14894fd79bc8cb7669baf372552 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 17 Aug 2022 14:29:55 +0200 Subject: [PATCH 54/73] Fix invalid Swift syntax in documentation --- .../Request/Association/AssociationAggregate.swift | 8 ++++---- GRDB/ValueObservation/SharedValueObservation.swift | 8 ++++---- GRDB/ValueObservation/ValueObservation.swift | 12 ++++++------ .../ValueObservation/ValueObservationScheduler.swift | 4 ++-- README.md | 2 +- 5 files changed, 17 insertions(+), 17 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 966308a71..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)") diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index 28cd65402..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. @@ -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)") /// }) /// @@ -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)") /// }) /// diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index edd31390b..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 { @@ -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. @@ -366,7 +366,7 @@ extension ValueObservation { /// .publisher(in: dbQueue) /// .sink( /// receiveCompletion: { completion in ... }, - /// receiveValue: { players: [Player] in + /// receiveValue: { (players: [Player]) in /// print("fresh players: \(players)") /// }) /// @@ -383,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. @@ -734,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") /// }) /// diff --git a/GRDB/ValueObservation/ValueObservationScheduler.swift b/GRDB/ValueObservation/ValueObservationScheduler.swift index 37cf5ac5f..488d7fac0 100644 --- a/GRDB/ValueObservation/ValueObservationScheduler.swift +++ b/GRDB/ValueObservation/ValueObservationScheduler.swift @@ -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/README.md b/README.md index e01899368..49606b4a7 100644 --- a/README.md +++ b/README.md @@ -286,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)") }) ``` From 27b65c9a80bf7702ff1bf592fe0c0d152cc8c1cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 17 Aug 2022 14:32:08 +0200 Subject: [PATCH 55/73] BREAKING: Starting DatabaseRegionObservation returns a cancellable --- CHANGELOG.md | 2 + Documentation/GRDB6MigrationGuide.md | 25 ++ GRDB/Core/DatabaseRegionObservation.swift | 140 +++++++---- GRDB/Fixits.swift | 8 + README.md | 85 +++++-- TODO.md | 2 +- .../DatabaseRegionObservationTests.swift | 218 +++++++++++------- 7 files changed, 329 insertions(+), 151 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f67952c65..822bd52c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -104,6 +104,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: The `Record.copy()` method was removed, without replacement. - **Breaking**: The `FetchableRecord.init(row:)` initializer can now throw errors. - **Breaking**: The `DerivableRequest.limit(_:offset_:)` method was removed, without replacement. +- **Breaking**: `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable. +- **Breaking**: The `DatabaseRegionObservation.extent` property was removed. - **New**: 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). - **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`. - **New**: `ValueObservation.map` now accepts a throwing closure argument. diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index c28a0a52f..a487d9b50 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -153,3 +153,28 @@ The record protocols have been refactored. We tried to keep the amount of modifi // 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. diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 2c30a578f..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,13 +33,16 @@ 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: any DatabaseRegionConvertible...) { @@ -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: [any DatabaseRegionConvertible]) { - self.init( - extent: .observerLifetime, - observedRegion: DatabaseRegion.union(regions)) + 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. /// + /// 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 writer: some DatabaseWriter, + onError: @escaping (Error) -> Void, onChange: @escaping (Database) -> Void) - throws -> any TransactionObserver + -> AnyDatabaseCancellable { + @LockedBox var state = ObservationState.pending + // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. - try writer.unsafeReentrantWrite { db 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 } } } @@ -204,9 +253,9 @@ 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 @@ -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/Fixits.swift b/GRDB/Fixits.swift index 31c2f55e8..9f789051e 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -46,6 +46,14 @@ extension DatabaseMigrator { { 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() } diff --git a/README.md b/README.md index 49606b4a7..2b175ce78 100644 --- a/README.md +++ b/README.md @@ -6580,7 +6580,7 @@ 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). @@ -6594,19 +6594,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 @@ -6615,42 +6619,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 diff --git a/TODO.md b/TODO.md index 38133d238..1da3a9262 100644 --- a/TODO.md +++ b/TODO.md @@ -23,7 +23,7 @@ - [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 - [ ] Can we generate EXISTS with association? `Team.annotated(with: Team.players.exists)` -- [ ] GRDB 6: have DatabaseRegionObservation produce DatabaseCancellable just as ValueObservation. +- [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 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)") // } From 546bba17fbc214342c387e484f1554eb772819e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 17 Aug 2022 14:32:42 +0200 Subject: [PATCH 56/73] Make LockedBox.swift easier to read --- GRDB/Utils/LockedBox.swift | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) 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() } From c86581dedcde15e26f093f224dea13557ae85235 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 17 Aug 2022 14:42:36 +0200 Subject: [PATCH 57/73] Make SQLQueryGenerator.swift easier to read --- .../SQLGeneration/SQLQueryGenerator.swift | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 4e8ec40ae..289decc5d 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. From 5004994344e355c4f005d65f375be2e8485b5fd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 17 Aug 2022 15:22:00 +0200 Subject: [PATCH 58/73] TODO --- TODO.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/TODO.md b/TODO.md index 1da3a9262..ce48515ae 100644 --- a/TODO.md +++ b/TODO.md @@ -21,8 +21,12 @@ - [ ] 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 -- [ ] Can we generate EXISTS with association? `Team.annotated(with: Team.players.exists)` +- [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 @@ -54,7 +58,7 @@ - [ ] 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 -- [ ] 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() From 1239c14e6d82f363047d86f67b76c2c2872e9b04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 17 Aug 2022 15:51:15 +0200 Subject: [PATCH 59/73] Explicit initializers for HasOneThrough and HasManyThrough associations --- .../Association/HasManyThroughAssociation.swift | 12 ++++++++++++ .../Association/HasOneThroughAssociation.swift | 12 ++++++++++++ GRDB/QueryInterface/SQL/Table.swift | 6 ++---- GRDB/QueryInterface/TableRecord+Association.swift | 6 ++---- 4 files changed, 28 insertions(+), 8 deletions(-) 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/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index f91af0a7e..2169b7a17 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -920,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) @@ -953,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) diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 05685015d..189ac2034 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -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) From c38d903f4d17a1a510a373a4d06fbc3411bc3a21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 17 Aug 2022 16:47:27 +0200 Subject: [PATCH 60/73] Make RequestProtocols.swift easier to read --- GRDB/Core/Database+Schema.swift | 19 +++++++++++++ .../Request/RequestProtocols.swift | 27 +++++++++++++++++-- GRDB/QueryInterface/SQL/SQLCollection.swift | 1 + 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index b0d034aeb..3e834ae85 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -700,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 { @@ -1038,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 } } diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index d3e202a74..e1826761a 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -274,7 +274,7 @@ 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: some Sequence) -> Self { @@ -412,13 +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 + // + // // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...) + // // SELECT * FROM player GROUP BY rowid + // Player.all().groupByPrimaryKey() return [.rowID] } 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) } } } @@ -795,6 +807,17 @@ public protocol DerivableRequest: AggregatingRequest, FilteredReques 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 { private func annotated(with aggregate: AssociationAggregate) -> Self { var request = self 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 } From 4ced8c78e7545e0314be8e5611cef603f3bb29d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 17 Aug 2022 17:05:03 +0200 Subject: [PATCH 61/73] Less "iff" (some people think this is a typo) iff = if and only if --- GRDB/Core/SchedulingWatchdog.swift | 2 +- GRDB/Core/TransactionObserver.swift | 2 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 12 ++++++++++-- 3 files changed, 12 insertions(+), 4 deletions(-) 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/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 9a825cbc9..369f53b0b 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -954,7 +954,7 @@ public enum DatabaseEventKind { } } - /// Returns true iff this is a delete event. + /// Returns whether this is a delete event. var isDelete: Bool { if case .delete = self { return true diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index d6ffd85a1..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 } } From 5243db7fbce6df985b5b268aca73391b35bc9074 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 17 Aug 2022 17:57:36 +0200 Subject: [PATCH 62/73] Spelling --- GRDB/Core/Cursor.swift | 2 +- GRDB/Core/Database+Schema.swift | 4 ++-- GRDB/Core/TransactionObserver.swift | 2 +- GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift | 2 +- GRDB/Record/FetchableRecord.swift | 2 +- README.md | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index ee45c3566..1917fd483 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -316,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. diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 3e834ae85..84f0a55a9 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -186,7 +186,7 @@ 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 try schema(schemaID).containsObjectNamed(name, ofType: type) } @@ -786,7 +786,7 @@ 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? diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 369f53b0b..f222e965a 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -164,7 +164,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 diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index a4382cac2..81edac4d0 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -435,7 +435,7 @@ public class TableAlias: Hashable { 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) diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index b675ef632..6a4d23cb5 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -520,7 +520,7 @@ public final class RecordCursor: DatabaseCursor { 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: (any RowAdapter)? = nil) throws { self.statement = statement diff --git a/README.md b/README.md index 2b175ce78..cf7eccb9e 100644 --- a/README.md +++ b/README.md @@ -3641,7 +3641,7 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](Doc // When you subclass Record, you need an override: class Book : Record { override class var databaseSelection: [any SQLSelectable] { - [AllColums(), Column.rowID] + [AllColumns(), Column.rowID] } } ``` From c553d2d69ea7d2d50923f428818500fad14648cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Thu, 18 Aug 2022 15:31:32 +0200 Subject: [PATCH 63/73] Documentation --- GRDB/QueryInterface/Schema/TableDefinition.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index e5112e3bf..d09e3183b 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -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) } From eda403bd3186876c1e32fb8a965785697de010c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Thu, 18 Aug 2022 15:31:42 +0200 Subject: [PATCH 64/73] StatementArguments is Hashable --- GRDB/Core/Statement.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index af5a8b875..7bca0787a 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -604,7 +604,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] From 0ed9367b267f25c74730199a5fe8213df690fd39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 20 Aug 2022 11:15:00 +0200 Subject: [PATCH 65/73] BREAKING: DatabaseCursor no longer exposes its prepared statement --- CHANGELOG.md | 1 + Documentation/GRDB6MigrationGuide.md | 9 ++++++ GRDB/Core/DatabaseRegion.swift | 2 +- GRDB/Core/DatabaseValueConvertible.swift | 9 +++--- GRDB/Core/Row.swift | 7 +++-- GRDB/Core/Statement.swift | 35 +++++++++++++++++----- GRDB/Core/StatementColumnConvertible.swift | 9 +++--- GRDB/Fixits.swift | 5 ++++ GRDB/Record/FetchableRecord.swift | 7 +++-- Tests/GRDBTests/RowFetchTests.swift | 17 +++++++++-- Tests/GRDBTests/SelectStatementTests.swift | 10 +++++-- 11 files changed, 82 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 822bd52c4..fa1e4a0a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -106,6 +106,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: The `DerivableRequest.limit(_:offset_:)` method was removed, without replacement. - **Breaking**: `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable. - **Breaking**: The `DatabaseRegionObservation.extent` property was removed. +- **Breaking**: The `statement` property of database cursors was replaced with read-only properties such as `sql` or `columnNames`. - **New**: 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). - **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`. - **New**: `ValueObservation.map` now accepts a throwing closure argument. diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index a487d9b50..05bb3b87f 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -178,3 +178,12 @@ The record protocols have been refactored. We tried to keep the amount of modifi ``` 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 + ``` diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 02027d078..9f47083b6 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -340,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. /// diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 84fb29e38..0e59f9b53 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -105,13 +105,14 @@ 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: CInt init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { - self.statement = statement + self._statement = statement if let adapter = adapter { // adapter may redefine the index of the leftmost column columnIndex = try CInt(adapter.baseColumnIndex(atIndex: 0, layout: statement)) @@ -126,7 +127,7 @@ 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: @@ -134,7 +135,7 @@ public final class DatabaseValueCursor: Databas try Value.decode( fromStatement: sqliteStatement, atUncheckedIndex: columnIndex, - context: RowDecodingContext(statement: statement, index: Int(columnIndex))) + context: RowDecodingContext(statement: _statement, index: Int(columnIndex))) } } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 9081d9174..acc03f583 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1087,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: (any RowAdapter)? = nil) throws { - self.statement = statement + 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 @@ -1103,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: diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 7bca0787a..e43085934 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -420,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 { @@ -437,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 @@ -449,7 +468,7 @@ extension DatabaseCursor { @inlinable public func forEach(_ body: (Element) throws -> Void) throws { if _isDone { return } - try statement.forEachStep { + try _statement.forEachStep { try body(_element(sqliteStatement: $0)) } _isDone = true @@ -468,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) @@ -482,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 diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 5553c05dd..b7009b92a 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -144,13 +144,14 @@ 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: CInt init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { - self.statement = statement + self._statement = statement if let adapter = adapter { // adapter may redefine the index of the leftmost column columnIndex = try CInt(adapter.baseColumnIndex(atIndex: 0, layout: statement)) @@ -165,7 +166,7 @@ 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: @@ -174,7 +175,7 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible try Value.fastDecode( fromStatement: sqliteStatement, atUncheckedIndex: columnIndex, - context: RowDecodingContext(statement: statement, index: Int(columnIndex))) + context: RowDecodingContext(statement: _statement, index: Int(columnIndex))) } } diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 9f789051e..71a09b25e 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -38,6 +38,11 @@ extension Database { public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> Statement { 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( diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 6a4d23cb5..422da1bf3 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -517,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 // Instantiated once, reused for performance init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { - self.statement = statement + self._statement = statement row = try Row(statement: statement).adapted(with: adapter, layout: statement) try statement.reset(withArguments: arguments) } @@ -531,7 +532,7 @@ 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: 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/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index a63cc1e4d..f68746e10 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -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() From a702fe6bc9c9f365317ca94ce1db556be4c11d07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Aug 2022 14:55:02 +0200 Subject: [PATCH 66/73] BREAKING: persistence callbacks, and support for RETURNING - Replace performInsert, performUpdate, etc with callbacks: willInsert, aroundInsert, didInsert, etc. - Always call didInsert, even with INSERT OR IGNORE - Explicit conflict resolution in persistence methods - Add ...AndFetch... methods --- CHANGELOG.md | 4 + .../GRDBAsyncDemo/GRDBAsyncDemo/Player.swift | 4 +- .../GRDBCombineDemo/Player.swift | 4 +- .../GRDBDemoiOS/GRDBDemoiOS/Player.swift | 4 +- Documentation/GRDB6MigrationGuide.md | 128 ++ .../GoodPracticesForDesigningRecordTypes.md | 18 +- .../Associations.playground/Contents.swift | 8 +- .../MyPlayground.playground/Contents.swift | 4 +- .../Tour.playground/Contents.swift | 4 +- GRDB.xcodeproj/project.pbxproj | 100 +- GRDB/Fixits.swift | 28 + .../Request/QueryInterfaceRequest.swift | 533 ++++++- GRDB/QueryInterface/SQL/Table.swift | 28 +- .../SQLGeneration/SQLQueryGenerator.swift | 76 +- GRDB/Record/EncodableRecord.swift | 12 +- .../Record/MutablePersistableRecord+DAO.swift | 273 ++++ .../MutablePersistableRecord+Delete.swift | 56 + .../MutablePersistableRecord+Insert.swift | 473 ++++++ .../MutablePersistableRecord+Save.swift | 372 +++++ .../MutablePersistableRecord+Update.swift | 842 ++++++++++ GRDB/Record/MutablePersistableRecord.swift | 303 ++++ GRDB/Record/PersistableRecord+Insert.swift | 344 +++++ GRDB/Record/PersistableRecord+Save.swift | 249 +++ GRDB/Record/PersistableRecord.swift | 911 +---------- GRDB/Record/Record.swift | 324 ++-- GRDB/Record/TableRecord.swift | 68 +- GRDBCustom.xcodeproj/project.pbxproj | 60 +- README.md | 313 +++- TODO.md | 9 +- .../GRDBTests/CompilationSubClassTests.swift | 52 +- Tests/GRDBTests/DatabaseCursorTests.swift | 4 +- Tests/GRDBTests/FTS3RecordTests.swift | 4 +- Tests/GRDBTests/FTS4RecordTests.swift | 4 +- Tests/GRDBTests/FTS5RecordTests.swift | 4 +- ...bleRecord+QueryInterfaceRequestTests.swift | 4 +- ...MutablePersistableRecordChangesTests.swift | 26 +- ...RecordPersistenceConflictPolicyTests.swift | 49 +- .../MutablePersistableRecordTests.swift | 1370 +++++++++++++++-- Tests/GRDBTests/PersistableRecordTests.swift | 937 ++++++++--- .../Record+QueryInterfaceRequestTests.swift | 5 +- Tests/GRDBTests/RecordEditedTests.swift | 24 +- .../RecordMinimalPrimaryKeyRowIDTests.swift | 5 +- .../RecordPrimaryKeyHiddenRowIDTests.swift | 11 +- .../GRDBTests/RecordPrimaryKeyNoneTests.swift | 5 +- .../RecordPrimaryKeyRowIDTests.swift | 11 +- Tests/GRDBTests/RecordSubClassTests.swift | 19 +- .../RecordWithColumnNameManglingTests.swift | 5 +- Tests/GRDBTests/TableRecordDeleteTests.swift | 297 +++- Tests/GRDBTests/TableRecordUpdateTests.swift | 90 +- .../GRDBTests/TransactionObserverTests.swift | 8 +- 50 files changed, 6819 insertions(+), 1667 deletions(-) create mode 100644 GRDB/Record/MutablePersistableRecord+DAO.swift create mode 100644 GRDB/Record/MutablePersistableRecord+Delete.swift create mode 100644 GRDB/Record/MutablePersistableRecord+Insert.swift create mode 100644 GRDB/Record/MutablePersistableRecord+Save.swift create mode 100644 GRDB/Record/MutablePersistableRecord+Update.swift create mode 100644 GRDB/Record/MutablePersistableRecord.swift create mode 100644 GRDB/Record/PersistableRecord+Insert.swift create mode 100644 GRDB/Record/PersistableRecord+Save.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index fa1e4a0a5..c0903f780 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -107,10 +107,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable. - **Breaking**: The `DatabaseRegionObservation.extent` property was removed. - **Breaking**: The `statement` property of database cursors was replaced with read-only properties such as `sql` or `columnNames`. +- **Breaking**: Record types can no longer override persistence methods. You use persistence callbacks instead. - **New**: 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). - **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`. - **New**: `ValueObservation.map` now accepts a throwing closure argument. - **New**: Value requests now throw an error when they find unexpected database values (they used to crash in GRDB 5). +- **New**: Persistence callbacks allow record types to customize persistence methods. +- **New**: All persistence methods now accept an explicit conflict policy: `player.insert(db, onConflict: .replace)`, etc. +- **New**: Support for 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): `player.insertAndFetch(db)`, `Player.deleteAndFetchAll(db)`, etc. ## 5.26.0 diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift index 609df14a0..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 } } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift index 609df14a0..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 } } diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift index cacb7112d..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 } } diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index 05bb3b87f..d303e66ca 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -110,7 +110,135 @@ The record protocols have been refactored. We tried to keep the amount of modifi +- **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 --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 284ce79af..817c2c8ea 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 diff --git a/Documentation/Playgrounds/Associations.playground/Contents.swift b/Documentation/Playgrounds/Associations.playground/Contents.swift index 66be6ed96..61040d563 100644 --- a/Documentation/Playgrounds/Associations.playground/Contents.swift +++ b/Documentation/Playgrounds/Associations.playground/Contents.swift @@ -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/MyPlayground.playground/Contents.swift b/Documentation/Playgrounds/MyPlayground.playground/Contents.swift index f815d8f1e..d02e45194 100644 --- a/Documentation/Playgrounds/MyPlayground.playground/Contents.swift +++ b/Documentation/Playgrounds/MyPlayground.playground/Contents.swift @@ -13,8 +13,8 @@ struct Player: Codable, FetchableRecord, MutablePersistableRecord { 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 c79f27742..e6f7e4f20 100644 --- a/Documentation/Playgrounds/Tour.playground/Contents.swift +++ b/Documentation/Playgrounds/Tour.playground/Contents.swift @@ -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/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index f75ca7afa..c382a4aae 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 */; }; @@ -397,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 */; }; @@ -791,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 */; }; @@ -1037,7 +1069,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 */; }; @@ -1314,7 +1346,7 @@ 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 = ""; }; @@ -1627,6 +1659,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 = ""; }; @@ -2405,7 +2445,15 @@ 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 */, + 56D110D228AFC81400E64463 /* PersistableRecord.swift */, + 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */, + 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, ); @@ -2935,6 +2983,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 */, @@ -2951,6 +3000,7 @@ 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 */, @@ -2958,8 +3008,10 @@ 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 */, @@ -3010,6 +3062,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 */, @@ -3037,10 +3090,11 @@ 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 */, @@ -3048,6 +3102,7 @@ 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 */, @@ -3070,6 +3125,7 @@ 565490CD1D5AE252005622CB /* Date.swift in Sources */, 5653EB0820944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */, 565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */, + 56D110CB28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -3111,6 +3167,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 */, @@ -3118,11 +3175,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 */, @@ -3142,6 +3201,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,10 +3219,12 @@ 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 */, @@ -3180,6 +3242,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 */, @@ -3206,9 +3269,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 */, @@ -3719,6 +3783,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 */, @@ -3726,11 +3791,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 */, @@ -3750,6 +3817,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 */, @@ -3767,10 +3835,12 @@ 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 */, @@ -3788,6 +3858,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 */, @@ -3814,9 +3885,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 */, @@ -4092,6 +4164,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 */, @@ -4099,11 +4172,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 */, @@ -4123,6 +4198,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 */, @@ -4140,10 +4216,12 @@ 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 */, @@ -4161,6 +4239,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 */, @@ -4187,6 +4266,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 */, @@ -4199,7 +4279,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 */, diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 71a09b25e..6753069ae 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -67,9 +67,37 @@ extension DatabaseUUIDEncodingStrategy { @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.") diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index e94aa77b4..65bf9c0b2 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -410,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 + /// 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 { @@ -438,13 +651,14 @@ extension QueryInterfaceRequest { } } - /// 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. @@ -460,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 @@ -471,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 + /// 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. diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 2169b7a17..b4b0b5518 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -1139,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 @@ -1220,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) @@ -1251,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 @@ -1285,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) @@ -1313,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 @@ -1346,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"]]) /// @@ -1364,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"]) /// @@ -1381,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: /// @@ -1405,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: /// @@ -1416,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/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 289decc5d..7b62a139d 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -205,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) @@ -233,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 @@ -247,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]) @@ -263,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) { @@ -281,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 @@ -322,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 @@ -336,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 @@ -378,9 +386,35 @@ 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 { + assert(sqlite3_libversion_number() >= 3035000) + 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 { diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index ab5fefb52..907510bf9 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -220,7 +220,7 @@ public struct PersistenceContainer { /// Column names are case insensitive, so defining both "name" and "NAME" /// is considered undefined behavior. public subscript(_ column: String) -> (any DatabaseValueConvertible)? { - get { storage[column] ?? nil } + get { self[caseInsensitive: column] } set { storage.updateValue(newValue, forKey: column) } } @@ -248,6 +248,15 @@ public struct PersistenceContainer { 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 + record.encode(to: &self) + } + /// Columns stored in the container, ordered like values. var columns: [String] { Array(storage.keys) } @@ -300,6 +309,7 @@ public struct PersistenceContainer { storage.makeIterator() } + @usableFromInline func changesIterator(from container: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> { var newValueIterator = makeIterator() return AnyIterator { diff --git a/GRDB/Record/MutablePersistableRecord+DAO.swift b/GRDB/Record/MutablePersistableRecord+DAO.swift new file mode 100644 index 000000000..baca79221 --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord+DAO.swift @@ -0,0 +1,273 @@ +/// 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) + } + + /// 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 { + assert(sqlite3_libversion_number() >= 3035000) + 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: - 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..13d3a67fe --- /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 + /// 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..fc4435da7 --- /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 + /// 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..bc272c3ce --- /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 + /// 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 + @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.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..924a5aaa5 --- /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 + /// 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..b33599474 --- /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 + /// 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.swift b/GRDB/Record/PersistableRecord.swift index df5408616..a5c6b3119 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -1,907 +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: some Sequence) throws { - 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: some Sequence) throws { - 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: some EncodableRecord & TableRecord) 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 a0006c135..d60ef25f4 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -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 { @@ -96,7 +91,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// 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. @@ -113,31 +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?) { - } + open func encode(to container: inout PersistenceContainer) { } // MARK: - Compare with Previous Versions @@ -199,80 +170,184 @@ 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() + + // Set hasDatabaseChanges to false + referenceRow = Row(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() + + // Set hasDatabaseChanges to false + referenceRow = Row(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() + hasDatabaseChanges = true + } + + /// 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. /// @@ -297,45 +372,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 944da1316..0ab4f951f 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -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,7 +171,7 @@ extension TableRecord { /// - parameters: /// - db: A database connection. /// - key: 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, key: some DatabaseValueConvertible) throws -> Bool { try !filter(key: key).isEmpty(db) } @@ -179,7 +179,7 @@ extension TableRecord { @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") @@ -192,7 +192,7 @@ 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 { if id.databaseValue.isNull { // Don't hit the database @@ -205,15 +205,15 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { // 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. + /// - 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) } @@ -223,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]) @@ -241,7 +241,7 @@ 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: some Sequence) throws -> Int @@ -254,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) @@ -272,7 +272,7 @@ 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: some DatabaseValueConvertible) throws -> Bool { if key.databaseValue.isNull { @@ -285,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]) @@ -303,7 +303,7 @@ 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: some Collection) throws -> Int { if ids.isEmpty { @@ -313,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) @@ -331,7 +331,7 @@ 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 @@ -342,14 +342,15 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { 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: (any DatabaseValueConvertible)?]]) throws -> Int { if keys.isEmpty { @@ -360,14 +361,15 @@ 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: (any DatabaseValueConvertible)?]) throws -> Bool { try deleteAll(db, keys: [key]) > 0 @@ -378,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: /// @@ -391,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( @@ -403,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: /// @@ -415,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/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3eb4a0ee5..ebf65f587 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -509,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 */; }; @@ -580,7 +598,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, ); }; }; @@ -619,7 +636,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, ); }; }; @@ -810,7 +826,6 @@ 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 = ""; }; @@ -1116,6 +1131,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 = ""; }; @@ -1849,7 +1873,15 @@ 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 */, + 56D110E528AFC90800E64463 /* PersistableRecord.swift */, + 56D110E328AFC90800E64463 /* PersistableRecord+Insert.swift */, + 56D110E428AFC90800E64463 /* PersistableRecord+Save.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, ); @@ -2321,6 +2353,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 */, @@ -2353,8 +2386,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 */, @@ -2407,7 +2443,6 @@ 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 */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, @@ -2415,9 +2450,13 @@ 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 */, @@ -2428,6 +2467,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 */, @@ -2693,6 +2733,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 */, @@ -2725,8 +2766,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 */, @@ -2779,7 +2823,6 @@ 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 */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, @@ -2787,9 +2830,13 @@ 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 */, @@ -2800,6 +2847,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 */, diff --git a/README.md b/README.md index cf7eccb9e..342e8f509 100644 --- a/README.md +++ b/README.md @@ -2473,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) @@ -2807,23 +2808,23 @@ protocol EncodableRecord { 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. @@ -2842,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 } } @@ -2883,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 } } ``` @@ -2892,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 @@ -2919,7 +2920,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 @@ -2943,56 +2944,203 @@ try Place.deleteOne(db, key:...) **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: **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. -> -> :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`. +#### 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` 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/5.26/Protocols/MutablePersistableRecord.html). + +In the `MutablePersistableRecord` protocol, `willInsert` and `didInsert` are mutating methods. In `PersistableRecord`, they are not mutating. + +> :point_up: **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. +> +> :warning: **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: **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 committed changes, use the [After Commit Hook](#after-commit-hook). ## Identifiable Records @@ -3354,8 +3502,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 } } ``` @@ -3392,7 +3541,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: @@ -3501,7 +3650,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)`. @@ -3560,7 +3709,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 { @@ -3583,10 +3732,17 @@ 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: -> -> - 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**: 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 +> } +> ``` > > :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). @@ -3672,7 +3828,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 { @@ -3685,8 +3841,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 } } ``` @@ -3784,8 +3940,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 } } ``` @@ -3838,8 +3994,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 } } ``` @@ -3912,8 +4068,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 } } ``` @@ -3969,8 +4125,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 } } ``` @@ -3990,16 +4147,27 @@ 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) | | `Type.updateAll(db, ...)` | [TableRecord] | | | `Type.filter(...).updateAll(db, ...)` | [TableRecord] | ² | @@ -4011,6 +4179,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] | ¹ | @@ -8432,6 +8613,10 @@ 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]. + #### ValueObservation and DatabaseRegionObservation This chapter has been superseded by [ValueObservation] and [DatabaseRegionObservation]. @@ -8480,7 +8665,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 @@ -8495,6 +8679,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 @@ -8516,3 +8701,5 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests]. [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/TODO.md b/TODO.md index ce48515ae..2c939485a 100644 --- a/TODO.md +++ b/TODO.md @@ -35,6 +35,9 @@ - [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 +- [ ] GRDB 6: afterNextTransactionCommit -> afterNextTransaction(onCommit:onRollback:) - [ ] GRDB 6: encoding errors for record (`EncodableRecord.encode(to:)`) - [ ] throwing EncodableRecord.encode FIRST - [?] GRDB 6: protocol-based record container? This could avoid computing & encoding values we do not need. @@ -45,10 +48,10 @@ - [X] GRDB 6: primary associated types (cursor, requests, ...) - [X] GRDB 6: remove existential/generic duplicated methods - [ ] GRDB 6: remove useless AnyXXX Type erasers -- [ ] GRDB 6: conflict resolution in persistence methods +- [X] GRDB 6: conflict resolution in persistence methods - [ ] GRDB 6: UPSERT -- [ ] GRDB 6: support for RETURNING - - [ ] Support for default values: `Player.insert(db, returning: FullPlayer.self)` ? +- [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) diff --git a/Tests/GRDBTests/CompilationSubClassTests.swift b/Tests/GRDBTests/CompilationSubClassTests.swift index 5e5a2a485..c722356a1 100644 --- a/Tests/GRDBTests/CompilationSubClassTests.swift +++ b/Tests/GRDBTests/CompilationSubClassTests.swift @@ -12,8 +12,52 @@ private class UserRecord : Record { override class var persistenceConflictPolicy: PersistenceConflictPolicy { super.persistenceConflictPolicy } override class var databaseSelection: [any 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 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 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/DatabaseCursorTests.swift b/Tests/GRDBTests/DatabaseCursorTests.swift index 4faf542cd..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 } } diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index 6baea9ffd..036fb5da4 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -28,8 +28,8 @@ extension Book : MutablePersistableRecord { container["body"] = body } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index f23a989b7..f6c2eb6f0 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -28,8 +28,8 @@ extension Book : MutablePersistableRecord { container["body"] = body } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index 8ebc2804a..eac65c0a2 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -29,8 +29,8 @@ extension Book : MutablePersistableRecord { container["body"] = body } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } diff --git a/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift index 4d19279bf..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 } } diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index d1a4f6e74..e6f2a249e 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -16,15 +16,14 @@ 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 } } @@ -302,8 +301,9 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { 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/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 fd7e0708c..6660e8d83 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,33 +84,219 @@ 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 } } @@ -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, + 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 @@ -319,7 +538,7 @@ class MutablePersistableRecordTests: GRDBTestCase { let dict = 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,752 @@ 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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) + } } } diff --git a/Tests/GRDBTests/PersistableRecordTests.swift b/Tests/GRDBTests/PersistableRecordTests.swift index deb80f7ef..f1dbc73c3 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,6 +173,79 @@ 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: Decodable, TableRecord, FetchableRecord { + var id: Int64 + var name: String + var score: Int +} + class PersistableRecordTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { @@ -120,12 +262,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, + score INTEGER NOT NULL DEFAULT 1000); """) } try migrator.migrate(dbWriter) } - // MARK: - PersistableRecordPerson func testInsertPersistableRecordPerson() throws { @@ -139,7 +284,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 +296,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "Arthur") } } - - + // MARK: - PersistableRecordPersonClass func testInsertPersistableRecordPersonClass() throws { @@ -167,7 +311,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 +325,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 +335,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 +391,7 @@ class PersistableRecordTests: GRDBTestCase { } } } - + func testSavePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -283,7 +427,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 +447,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 +459,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertFalse(try person.exists(db)) } } - - + // MARK: - PersistableRecordCountry func testInsertPersistableRecordCountry() throws { @@ -331,7 +474,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 +495,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 +531,7 @@ class PersistableRecordTests: GRDBTestCase { } } } - + func testSavePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -424,7 +567,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 +587,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 +599,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 +636,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 +681,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 +760,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 +796,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 +832,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 +860,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 +878,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 +904,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 +999,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 +1067,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 +1138,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 +1158,7 @@ extension PersistableRecordTests { XCTFail(error.localizedDescription) } } else { - XCTFail("Failed to convert " + string) + XCTFail("Failed to convert " + string) } } } @@ -1036,3 +1259,339 @@ extension PersistableRecordTests { } } + +// MARK: - Insert and Fetch + +extension PersistableRecordTests { + func test_insertAndFetch_as() throws { +#if !GRDBCUSTOMSQLITE + 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 + 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 + 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 + 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) + } + } + } +} diff --git a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift index 1ee400cb6..76589e4b6 100644 --- a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift @@ -30,8 +30,9 @@ private class Reader : Record { 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 } } diff --git a/Tests/GRDBTests/RecordEditedTests.swift b/Tests/GRDBTests/RecordEditedTests.swift index 94d2de96a..6fed21b8f 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -46,17 +46,16 @@ private class Person : Record { 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 } } @@ -115,17 +114,16 @@ private class PersonWithModifiedCaseColumns: Record { 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 } } @@ -672,7 +670,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) diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index beae0f620..c1fe278f8 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -31,8 +31,9 @@ class MinimalRowID : Record, Hashable { 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 { diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index d293a6838..195122336 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -50,17 +50,16 @@ private class Person : Record, Hashable { 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 { diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index 5581cca55..7e757b0d2 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -39,8 +39,9 @@ private class Item : Record, Hashable { 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 { diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index ebdc8891b..50a2911d6 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -47,17 +47,16 @@ private class Person : Record, Hashable { 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 { diff --git a/Tests/GRDBTests/RecordSubClassTests.swift b/Tests/GRDBTests/RecordSubClassTests.swift index e75187f62..8de07ca0b 100644 --- a/Tests/GRDBTests/RecordSubClassTests.swift +++ b/Tests/GRDBTests/RecordSubClassTests.swift @@ -46,17 +46,16 @@ private class Person : Record { 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 } } @@ -91,14 +90,14 @@ private class PersonWithOverrides : Person { 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) } } diff --git a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift index e5dd27106..03f95a3e2 100644 --- a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift +++ b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift @@ -38,8 +38,9 @@ class BadlyMangledStuff : Record { 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 } } diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index 167f95dae..948a84366 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, *) @@ -172,7 +174,7 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testRequestDelete() throws { + func testRequestDeleteAll() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -227,7 +229,118 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testJoinedRequestDelete() throws { + func testRequestDeleteAndFetchStatement() throws { +#if !GRDBCUSTOMSQLITE + 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 + 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 + 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 + 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) @@ -287,7 +400,105 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testGroupedRequestDelete() throws { + func testJoinedRequestDeleteAndFetch() throws { +#if !GRDBCUSTOMSQLITE + 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") } @@ -351,4 +562,82 @@ class TableRecordDeleteTests: GRDBTestCase { } } } + + func testGroupedRequestDeleteAndFetchCursor() throws { +#if !GRDBCUSTOMSQLITE + 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 c61353e6a..69ee86938 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 @@ -117,6 +117,94 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testRequestUpdateAndFetchStatement() throws { +#if !GRDBCUSTOMSQLITE + 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 + 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 + 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 + 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/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 } } From 8f562d3e115a919670a5995a4764b61490fd52ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Aug 2022 09:01:48 +0200 Subject: [PATCH 67/73] NEW: Upsert --- CHANGELOG.md | 1 + GRDB.xcodeproj/project.pbxproj | 20 ++ .../Record/MutablePersistableRecord+DAO.swift | 75 ++++++ .../MutablePersistableRecord+Upsert.swift | 241 +++++++++++++++++ GRDB/Record/PersistableRecord+Upsert.swift | 194 +++++++++++++ GRDBCustom.xcodeproj/project.pbxproj | 12 + README.md | 15 +- TODO.md | 2 +- .../MutablePersistableRecordTests.swift | 200 +++++++++++++- Tests/GRDBTests/PersistableRecordTests.swift | 254 +++++++++++++++++- 10 files changed, 1007 insertions(+), 7 deletions(-) create mode 100644 GRDB/Record/MutablePersistableRecord+Upsert.swift create mode 100644 GRDB/Record/PersistableRecord+Upsert.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index c0903f780..35790c25a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,6 +115,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: Persistence callbacks allow record types to customize persistence methods. - **New**: All persistence methods now accept an explicit conflict policy: `player.insert(db, onConflict: .replace)`, etc. - **New**: Support for 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): `player.insertAndFetch(db)`, `Player.deleteAndFetchAll(db)`, etc. +- **New**: Support for [`UPSERT`](https://www.sqlite.org/lang_UPSERT.html) (available from iOS 15.0+, macOS 12.0+, tvOS 15.0+, watchOS 8.0+, or with a custom SQLite build): `player.upsert(db)`, etc. ## 5.26.0 diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index c382a4aae..1b0b2c892 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -966,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 */; }; @@ -1698,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 = ""; }; @@ -2451,9 +2461,11 @@ 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 */, ); @@ -3020,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 */, @@ -3098,6 +3111,7 @@ 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 */, @@ -3191,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 */, @@ -3215,6 +3230,7 @@ 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 */, @@ -3807,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 */, @@ -3831,6 +3848,7 @@ 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 */, @@ -4188,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 */, @@ -4212,6 +4231,7 @@ 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 */, diff --git a/GRDB/Record/MutablePersistableRecord+DAO.swift b/GRDB/Record/MutablePersistableRecord+DAO.swift index baca79221..e4e4cc19f 100644 --- a/GRDB/Record/MutablePersistableRecord+DAO.swift +++ b/GRDB/Record/MutablePersistableRecord+DAO.swift @@ -39,6 +39,40 @@ final class DAO { 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, @@ -207,6 +241,47 @@ extension InsertQuery { } } +// 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 { diff --git a/GRDB/Record/MutablePersistableRecord+Upsert.swift b/GRDB/Record/MutablePersistableRecord+Upsert.swift new file mode 100644 index 000000000..f53bf6304 --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord+Upsert.swift @@ -0,0 +1,241 @@ +// MARK: - Upsert + +extension MutablePersistableRecord { +#if GRDBCUSTOMSQLITE + /// 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/PersistableRecord+Upsert.swift b/GRDB/Record/PersistableRecord+Upsert.swift new file mode 100644 index 000000000..e3ab46fa6 --- /dev/null +++ b/GRDB/Record/PersistableRecord+Upsert.swift @@ -0,0 +1,194 @@ +// MARK: - Upsert + +extension PersistableRecord { +#if GRDBCUSTOMSQLITE + /// 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/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index ebf65f587..06c22ce01 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -559,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 */; }; @@ -1164,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 = ""; }; @@ -1879,9 +1885,11 @@ 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 */, ); @@ -2377,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 */, @@ -2401,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 */, @@ -2757,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 */, @@ -2781,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 */, diff --git a/README.md b/README.md index 342e8f509..c68eb34a7 100644 --- a/README.md +++ b/README.md @@ -2913,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) @@ -2934,12 +2938,16 @@ 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). @@ -3111,7 +3119,7 @@ try link.upsert(db) // Calls the willSave callback 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` methods) +- Inserting a record (all `record.insert` and `record.upsert` methods) - `willSave` - `aroundSave` - `willInsert` @@ -4169,6 +4177,9 @@ This is the list of record methods, along with their required protocols. The [Re | `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** | | | diff --git a/TODO.md b/TODO.md index 2c939485a..0025b2e71 100644 --- a/TODO.md +++ b/TODO.md @@ -49,7 +49,7 @@ - [X] GRDB 6: remove existential/generic duplicated methods - [ ] GRDB 6: remove useless AnyXXX Type erasers - [X] GRDB 6: conflict resolution in persistence methods -- [ ] GRDB 6: UPSERT +- [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) diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index 6660e8d83..c671efa7a 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -315,7 +315,7 @@ class MutablePersistableRecordTests: GRDBTestCase { name TEXT NOT NULL); CREATE TABLE player( id INTEGER PRIMARY KEY, - name NOT NULL, + name NOT NULL UNIQUE, -- UNIQUE for upsert tests score INTEGER NOT NULL DEFAULT 1000); """) } @@ -1904,3 +1904,201 @@ extension MutablePersistableRecordTests { } } } + +// MARK: - Upsert + +extension MutablePersistableRecordTests { + func test_upsert() throws { +#if !GRDBCUSTOMSQLITE + 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 + 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 f1dbc73c3..91b82d5b7 100644 --- a/Tests/GRDBTests/PersistableRecordTests.swift +++ b/Tests/GRDBTests/PersistableRecordTests.swift @@ -240,10 +240,73 @@ private struct PartialPlayer: Codable, PersistableRecord, FetchableRecord { } } -private struct FullPlayer: Decodable, TableRecord, FetchableRecord { - var id: Int64 +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 { @@ -264,7 +327,7 @@ class PersistableRecordTests: GRDBTestCase { personID INTEGER NOT NULL REFERENCES persons(id)); CREATE TABLE player( id INTEGER PRIMARY KEY, - name NOT NULL, + name NOT NULL UNIQUE, -- UNIQUE for upsert tests score INTEGER NOT NULL DEFAULT 1000); """) } @@ -1595,3 +1658,188 @@ extension PersistableRecordTests { } } } + +// MARK: - Upsert + +extension PersistableRecordTests { + func test_upsert() throws { +#if !GRDBCUSTOMSQLITE + 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 + 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) + } + } + } +} From 422e0ae85a3510d01ccde3f079e40091d6282d7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Aug 2022 09:43:20 +0200 Subject: [PATCH 68/73] BREAKING: Handles both commits and rollbacks Replace afterNextTransactionCommit(_:) with afterNextTransaction(onCommit:onRollback:) --- CHANGELOG.md | 1 + Documentation/GRDB6MigrationGuide.md | 9 ++++ GRDB/Core/TransactionObserver.swift | 50 +++++++++++------- GRDB/Fixits.swift | 3 ++ README.md | 39 +++++++++----- TODO.md | 2 +- ...abaseAfterNextTransactionCommitTests.swift | 51 ++++++++++++------- 7 files changed, 104 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 35790c25a..2e2111453 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -107,6 +107,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable. - **Breaking**: The `DatabaseRegionObservation.extent` property was removed. - **Breaking**: The `statement` property of database cursors was replaced with read-only properties such as `sql` or `columnNames`. +- **Breaking**: The `Database.afterNextTransactionCommit(_:)` method was renamed `Database.afterNextTransaction(onCommit:onRollback:)`, and is now able to report rollbacks as well as commits. - **Breaking**: Record types can no longer override persistence methods. You use persistence callbacks instead. - **New**: 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). - **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`. diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index d303e66ca..bd752473c 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -315,3 +315,12 @@ The record protocols have been refactored. We tried to keep the amount of modifi +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/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index f222e965a..2d1a41e99 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -39,40 +39,54 @@ extension Database { 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. @@ -497,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 diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 6753069ae..1de2ffb34 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -36,6 +36,9 @@ extension Database { @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 { diff --git a/README.md b/README.md index c68eb34a7..537b863c9 100644 --- a/README.md +++ b/README.md @@ -3148,7 +3148,20 @@ In the `MutablePersistableRecord` protocol, `willInsert` and `didInsert` are mut > > :warning: **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: **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 committed changes, use the [After Commit Hook](#after-commit-hook). +> :warning: **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 @@ -6122,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. @@ -6132,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: @@ -6165,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) @@ -8628,6 +8637,10 @@ This protocol has been renamed [TableRecord] in GRDB 3.0. 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]. diff --git a/TODO.md b/TODO.md index 0025b2e71..32622c950 100644 --- a/TODO.md +++ b/TODO.md @@ -37,7 +37,7 @@ - [?] 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 -- [ ] GRDB 6: afterNextTransactionCommit -> afterNextTransaction(onCommit:onRollback:) +- [X] GRDB 6: afterNextTransactionCommit -> afterNextTransaction(onCommit:onRollback:) - [ ] GRDB 6: encoding errors for record (`EncodableRecord.encode(to:)`) - [ ] throwing EncodableRecord.encode FIRST - [?] GRDB 6: protocol-based record container? This could avoid computing & encoding values we do not need. 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)") } } } From d2dd18b3e5f6b7f0df170d2513348a8e3040d85d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Aug 2022 14:55:58 +0200 Subject: [PATCH 69/73] Remove note and warning icons Those are handled by Github now: https://github.com/community/community/discussions/16925 --- Documentation/AssociationsBasics.md | 14 +-- Documentation/CommonTableExpressions.md | 14 +-- Documentation/Concurrency.md | 2 +- .../DemoApps/GRDBAsyncDemo/README.md | 2 +- .../DemoApps/GRDBCombineDemo/README.md | 2 +- Documentation/DemoApps/GRDBDemoiOS/README.md | 2 +- Documentation/FullTextSearch.md | 8 +- .../GoodPracticesForDesigningRecordTypes.md | 4 +- Documentation/Migrations.md | 6 +- README.md | 118 +++++++++--------- 10 files changed, 86 insertions(+), 86 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 5242404c6..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 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/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/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/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/FullTextSearch.md b/Documentation/FullTextSearch.md index 48652ad86..7fc072795 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 @@ -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)): @@ -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/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 817c2c8ea..8c2942efe 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -428,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: > @@ -751,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 72915c0bf..d3cc848b1 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -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 diff --git a/README.md b/README.md index 537b863c9..dacaab100 100644 --- a/README.md +++ b/README.md @@ -403,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 @@ -520,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: @@ -614,7 +614,7 @@ 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**: 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. @@ -1014,7 +1014,7 @@ See [Values](#values) for more information on supported arguments types (Bool, I 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 @@ -1052,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 @@ -1417,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 @@ -1435,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: @@ -1482,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): @@ -1550,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: > @@ -1660,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 @@ -1982,7 +1982,7 @@ 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). @@ -1993,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: @@ -2008,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 @@ -2426,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. @@ -2453,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. > @@ -2730,9 +2730,9 @@ 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. -> :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 @@ -3030,7 +3030,7 @@ let savedPlayer = try player.saveAndFetch(db) **Batch operations** can return updated or deleted values: -> :warning: **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. +> **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(...)... @@ -3144,11 +3144,11 @@ Make sure you provide implementations that match the exact callback signatures. In the `MutablePersistableRecord` protocol, `willInsert` and `didInsert` are mutating methods. In `PersistableRecord`, they are not mutating. -> :point_up: **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. +> **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. > -> :warning: **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**: 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: **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: +> **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 { @@ -3189,7 +3189,7 @@ 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 @@ -3447,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 @@ -3608,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 @@ -3753,7 +3753,7 @@ struct Player : MutablePersistableRecord { try player.insert(db) ``` -> :point_up: **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`: +> **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`: @@ -3765,7 +3765,7 @@ try player.insert(db) > } > ``` > -> :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 @@ -4393,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) @@ -4460,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): @@ -4587,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 @@ -4651,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: @@ -4972,7 +4972,7 @@ let request = RestrictedPlayer.all() let request = ExtendedPlayer.all() ``` -> :point_up: **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. +> **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 @@ -5014,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. - `*`, `/`, `+`, `-` @@ -5025,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:)`: @@ -5132,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` @@ -5189,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` @@ -5285,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 = ... @@ -5652,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 { ... } @@ -5735,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 { ... } @@ -6038,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: @@ -6206,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. @@ -6634,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) @@ -6785,7 +6785,7 @@ When needed, you can help GRDB optimize observations and reduce database content 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. @@ -6943,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: @@ -7009,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. @@ -7225,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. @@ -7317,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 @@ -7335,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 @@ -7527,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 @@ -7719,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 @@ -7864,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. @@ -7929,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): @@ -7972,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: @@ -8178,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 From 37f0a0bb9ad25edc0dc18531768528dd49cbe5c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Aug 2022 16:39:21 +0200 Subject: [PATCH 70/73] BREAKING: throwing EncodableRecord.encode(to:) --- CHANGELOG.md | 4 ++ Documentation/GRDB6MigrationGuide.md | 27 ++++++++ .../Tour.playground/Contents.swift | 2 +- GRDB/Record/EncodableRecord+Encodable.swift | 4 +- GRDB/Record/EncodableRecord.swift | 38 ++++++++--- GRDB/Record/Record.swift | 50 +++++++++----- README.md | 20 +++--- TODO.md | 2 +- Tests/Crash/RecordCrashTests.swift | 8 +-- .../GRDBTests/CompilationSubClassTests.swift | 2 +- .../DatabaseColumnEncodingStrategyTests.swift | 8 +-- .../DatabaseDateEncodingStrategyTests.swift | 59 +++++++++-------- .../DatabaseUUIDEncodingStrategyTests.swift | 39 +++++------ Tests/GRDBTests/GRDBTestCase.swift | 4 +- ...MutablePersistableRecordChangesTests.swift | 26 ++++---- ...tablePersistableRecordEncodableTests.swift | 30 ++++----- .../MutablePersistableRecordTests.swift | 4 +- .../Record+QueryInterfaceRequestTests.swift | 2 +- Tests/GRDBTests/RecordEditedTests.swift | 66 ++++++++++--------- ...imalNonOptionalPrimaryKeySingleTests.swift | 14 ++-- .../RecordMinimalPrimaryKeyRowIDTests.swift | 18 ++--- .../RecordMinimalPrimaryKeySingleTests.swift | 14 ++-- .../RecordPrimaryKeyHiddenRowIDTests.swift | 20 +++--- .../RecordPrimaryKeyMultipleTests.swift | 14 ++-- .../GRDBTests/RecordPrimaryKeyNoneTests.swift | 2 +- .../RecordPrimaryKeyRowIDTests.swift | 20 +++--- .../RecordPrimaryKeySingleTests.swift | 14 ++-- ...leWithReplaceConflictResolutionTests.swift | 16 ++--- Tests/GRDBTests/RecordSubClassTests.swift | 2 +- .../RecordWithColumnNameManglingTests.swift | 2 +- .../InsertRecordClassTests.swift | 2 +- .../GRDBProfiling/AppDelegate.swift | 2 +- 32 files changed, 306 insertions(+), 229 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e2111453..b01f74810 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -109,6 +109,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: The `statement` property of database cursors was replaced with read-only properties such as `sql` or `columnNames`. - **Breaking**: The `Database.afterNextTransactionCommit(_:)` method was renamed `Database.afterNextTransaction(onCommit:onRollback:)`, and is now able to report rollbacks as well as commits. - **Breaking**: Record types can no longer override persistence methods. You use persistence callbacks instead. +- **Breaking**: The `EncodableRecord.encode(tp:)` method can now throw errors, with various consequences: + - `EncodableRecord.databaseDictionary` can throw + - `EncodableRecord.databaseChanges(from:)` can throw + - `Record.databaseChanges` can throw - **New**: 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). - **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`. - **New**: `ValueObservation.map` now accepts a throwing closure argument. diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index bd752473c..d8b812f12 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -110,6 +110,33 @@ The record protocols have been refactored. We tried to keep the amount of modifi +- **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 --git a/Documentation/Playgrounds/Tour.playground/Contents.swift b/Documentation/Playgrounds/Tour.playground/Contents.swift index e6f7e4f20..56cec233d 100644 --- a/Documentation/Playgrounds/Tour.playground/Contents.swift +++ b/Documentation/Playgrounds/Tour.playground/Contents.swift @@ -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 diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index a9f052a67..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 } } diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 907510bf9..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 @@ -165,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 } + } } } @@ -177,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. @@ -188,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) } } @@ -243,9 +261,9 @@ 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 @@ -254,7 +272,7 @@ public struct PersistenceContainer { let databaseTableName = type(of: record).databaseTableName let columnCount = try db.columns(in: databaseTableName).count self.init(minimumCapacity: columnCount) // Optimization - record.encode(to: &self) + try record.encode(to: &self) } /// Columns stored in the container, ordered like values. @@ -328,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) { diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index d60ef25f4..be2b873bb 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -100,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 /// } @@ -108,7 +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) { } + open func encode(to container: inout PersistenceContainer) throws { } // MARK: - Compare with Previous Versions @@ -129,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. @@ -142,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() { @@ -200,9 +224,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// information about the inserted row. open func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { let inserted = try insert() - - // Set hasDatabaseChanges to false - referenceRow = Row(inserted.persistenceContainer) + resetDatabaseChanges(with: inserted.persistenceContainer) } /// Called upon successful insertion. @@ -255,9 +277,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// reserved for GRDB usage. open func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { let updated = try update() - - // Set hasDatabaseChanges to false - referenceRow = Row(updated.persistenceContainer) + resetDatabaseChanges(with: updated.persistenceContainer) } // swiftlint:enable line_length @@ -335,7 +355,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// whether a row was deleted in the database. open func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { _ = try delete() - hasDatabaseChanges = true + setHasDatabaseChanges() } /// Called upon successful deletion. @@ -364,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 { diff --git a/README.md b/README.md index dacaab100..08aab0321 100644 --- a/README.md +++ b/README.md @@ -2801,7 +2801,7 @@ 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 @@ -3514,7 +3514,7 @@ class Place: Record { } /// 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 @@ -3618,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" @@ -3631,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" @@ -3651,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). @@ -4137,7 +4137,7 @@ class Place: Record { } /// 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 diff --git a/TODO.md b/TODO.md index 32622c950..b8fbe3ff3 100644 --- a/TODO.md +++ b/TODO.md @@ -39,7 +39,7 @@ - [ ] 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:)`) - - [ ] throwing EncodableRecord.encode FIRST + - [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 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/GRDBTests/CompilationSubClassTests.swift b/Tests/GRDBTests/CompilationSubClassTests.swift index c722356a1..4dfe564dc 100644 --- a/Tests/GRDBTests/CompilationSubClassTests.swift +++ b/Tests/GRDBTests/CompilationSubClassTests.swift @@ -11,7 +11,7 @@ private class UserRecord : Record { override class var databaseTableName: String { super.databaseTableName } override class var persistenceConflictPolicy: PersistenceConflictPolicy { super.persistenceConflictPolicy } override class var databaseSelection: [any SQLSelectable] { super.databaseSelection } - override func encode(to container: inout PersistenceContainer) { super.encode(to: &container) } + override func encode(to container: inout PersistenceContainer) throws { try super.encode(to: &container) } override func willInsert(_ db: Database) throws { try super.willInsert(db) 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/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index 035318b16..322310e7e 100644 --- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -76,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 { @@ -86,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) } } } @@ -175,44 +176,44 @@ extension DatabaseDateEncodingStrategyTests { extension DatabaseDateEncodingStrategyTests { func testIso8601() throws { - 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) } } } diff --git a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift index 5963b00ac..80686cfc5 100644 --- a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift @@ -42,9 +42,10 @@ 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 { @@ -52,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)!) @@ -78,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 @@ -102,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 diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index cbba5c64a..6ea977a0d 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -133,8 +133,8 @@ class GRDBTestCase: XCTestCase { XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)", file: file, line: line) } - func assert(_ record: some EncodableRecord, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) { - 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) } diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index e6f2a249e..bc974114b 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -47,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 @@ -65,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 @@ -77,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 @@ -101,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) @@ -118,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) @@ -135,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) @@ -153,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) @@ -183,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) @@ -201,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) @@ -222,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 @@ -237,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 @@ -252,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) @@ -295,7 +295,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { 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 diff --git a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift index 507e3cd01..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")! diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index c671efa7a..ebdcb77ba 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -533,9 +533,9 @@ 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]) } diff --git a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift index 76589e4b6..86a610e17 100644 --- a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift @@ -24,7 +24,7 @@ private class Reader : Record { "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 diff --git a/Tests/GRDBTests/RecordEditedTests.swift b/Tests/GRDBTests/RecordEditedTests.swift index 6fed21b8f..d74431534 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -39,7 +39,7 @@ private class Person : Record { 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 @@ -74,7 +74,7 @@ private class IntegerPropertyOnRealAffinityColumn : Record { try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["value"] = value } } @@ -107,7 +107,7 @@ private class PersonWithModifiedCaseColumns: Record { 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 @@ -376,9 +376,9 @@ class RecordEditedTests: GRDBTestCase { } } - 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 { @@ -398,7 +398,7 @@ class RecordEditedTests: GRDBTestCase { func testChangesAfterInitFromRow() throws { let person = try Person(row: Row(["name": "Arthur", "age": 41])) - let changes = person.databaseChanges + let changes = try person.databaseChanges XCTAssertEqual(changes.count, 4) for (column, old) in changes { switch column { @@ -426,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 { @@ -441,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) } } @@ -462,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 { @@ -480,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 { @@ -503,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) } } @@ -525,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 { @@ -547,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 { @@ -572,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) } } @@ -589,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 { @@ -603,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 { @@ -622,7 +627,8 @@ class RecordEditedTests: GRDBTestCase { } } try person.save(db) - XCTAssertEqual(person.databaseChanges.count, 0) + XCTAssertFalse(person.hasDatabaseChanges) + try XCTAssert(person.databaseChanges.isEmpty) } } @@ -633,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 { @@ -648,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 { @@ -688,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") @@ -696,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/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 64f1ed9a5..305f53d4b 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -28,7 +28,7 @@ private class MinimalNonOptionalPrimaryKeySingle: Record, Hashable { try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["id"] = id } @@ -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) } } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index c1fe278f8..6534179bc 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -27,7 +27,7 @@ class MinimalRowID : Record, Hashable { try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["id"] = id } @@ -68,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) } } @@ -80,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) } } @@ -107,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) } } @@ -138,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) } } @@ -171,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) } } @@ -183,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) } } @@ -195,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) } } @@ -208,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) } } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 69e1f7c8d..04247d476 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -26,7 +26,7 @@ class MinimalSingle: Record, Hashable { try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["UUID"] = UUID } @@ -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) } } diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 195122336..a15436b09 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -43,7 +43,7 @@ private class Person : Record, Hashable { try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container[.rowID] = id container["name"] = name container["age"] = age @@ -100,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) } } @@ -113,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. @@ -127,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) } } @@ -165,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) } } @@ -211,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) } } @@ -244,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) } } @@ -255,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) } } @@ -270,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) } } @@ -283,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) } } diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index 0ce7a45d7..cd42ee4e3 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -37,7 +37,7 @@ private class Citizenship : Record, Hashable { 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 @@ -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 7e757b0d2..cfe0b7dfe 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -34,7 +34,7 @@ private class Item : Record, Hashable { 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 } diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index 50a2911d6..90b2be317 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -40,7 +40,7 @@ private class Person : Record, Hashable { 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 @@ -94,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) } } @@ -107,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. @@ -121,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) } } @@ -159,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) } } @@ -205,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) } } @@ -238,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) } } @@ -249,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) } } @@ -263,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) } } @@ -276,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 26d27929a..70eaf248d 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -32,7 +32,7 @@ class Pet : Record, Hashable { 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 } @@ -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 977d5f1d1..90c70b105 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -31,7 +31,7 @@ class Email : Record, Hashable { 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 } @@ -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 8de07ca0b..fc3d8dc3f 100644 --- a/Tests/GRDBTests/RecordSubClassTests.swift +++ b/Tests/GRDBTests/RecordSubClassTests.swift @@ -39,7 +39,7 @@ private class Person : Record { 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 diff --git a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift index 03f95a3e2..0ce7021e0 100644 --- a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift +++ b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift @@ -31,7 +31,7 @@ class BadlyMangledStuff : Record { 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 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/AppDelegate.swift b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift index ad7fa84ea..b778f3f9b 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift @@ -375,7 +375,7 @@ class ItemRecord : Record { try super.init(row: row) } - override func encode(to container: inout PersistenceContainer) { + override func encode(to container: inout PersistenceContainer) throws { container["i0"] = i0 container["i1"] = i1 container["i2"] = i2 From 8f8b273424be65b89b41301d887164f53422a08f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Aug 2022 17:39:03 +0200 Subject: [PATCH 71/73] CHANGELOG organization --- CHANGELOG.md | 76 ++++++++++++++++++++++++++++++++++------------------ 1 file changed, 50 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b01f74810..59d459cc3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -95,32 +95,56 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## 6.0.0 -- **Breaking**: Swift 5.7+ and Xcode 14+ are required. -- **Breaking**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ / SQLite 3.19.3+ are required. -- **Breaking**: Removed deprecated methods -- **Breaking**: The in-memory `DatabaseQueue()` initializer can now throw errors. -- **Breaking**: The `selectID()` method is replaced with `selectPrimaryKey(as:)`. -- **Breaking**: `Cursor.isEmpty` is now a throwing property, instead of a method. -- **Breaking**: The `Record.copy()` method was removed, without replacement. -- **Breaking**: The `FetchableRecord.init(row:)` initializer can now throw errors. -- **Breaking**: The `DerivableRequest.limit(_:offset_:)` method was removed, without replacement. -- **Breaking**: `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable. -- **Breaking**: The `DatabaseRegionObservation.extent` property was removed. -- **Breaking**: The `statement` property of database cursors was replaced with read-only properties such as `sql` or `columnNames`. -- **Breaking**: The `Database.afterNextTransactionCommit(_:)` method was renamed `Database.afterNextTransaction(onCommit:onRollback:)`, and is now able to report rollbacks as well as commits. -- **Breaking**: Record types can no longer override persistence methods. You use persistence callbacks instead. -- **Breaking**: The `EncodableRecord.encode(tp:)` method can now throw errors, with various consequences: - - `EncodableRecord.databaseDictionary` can throw - - `EncodableRecord.databaseChanges(from:)` can throw - - `Record.databaseChanges` can throw -- **New**: 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). -- **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`. -- **New**: `ValueObservation.map` now accepts a throwing closure argument. -- **New**: Value requests now throw an error when they find unexpected database values (they used to crash in GRDB 5). -- **New**: Persistence callbacks allow record types to customize persistence methods. -- **New**: All persistence methods now accept an explicit conflict policy: `player.insert(db, onConflict: .replace)`, etc. -- **New**: Support for 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): `player.insertAndFetch(db)`, `Player.deleteAndFetchAll(db)`, etc. -- **New**: Support for [`UPSERT`](https://www.sqlite.org/lang_UPSERT.html) (available from iOS 15.0+, macOS 12.0+, tvOS 15.0+, watchOS 8.0+, or with a custom SQLite build): `player.upsert(db)`, etc. +### 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 From 2789444acd0f5729040d48827ee06b880bb58e2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Aug 2022 20:41:42 +0200 Subject: [PATCH 72/73] Enable UPSERT and RETURNING with SQLCipher --- .../Request/QueryInterfaceRequest.swift | 4 +- .../SQLGeneration/SQLQueryGenerator.swift | 1 - .../Record/MutablePersistableRecord+DAO.swift | 1 - .../MutablePersistableRecord+Insert.swift | 2 +- .../MutablePersistableRecord+Save.swift | 2 +- .../MutablePersistableRecord+Update.swift | 4 +- .../MutablePersistableRecord+Upsert.swift | 2 +- GRDB/Record/PersistableRecord+Insert.swift | 2 +- GRDB/Record/PersistableRecord+Save.swift | 2 +- GRDB/Record/PersistableRecord+Upsert.swift | 2 +- .../MutablePersistableRecordTests.swift | 90 +++++++++++++++---- Tests/GRDBTests/PersistableRecordTests.swift | 36 ++++++-- Tests/GRDBTests/TableRecordDeleteTests.swift | 36 ++++++-- Tests/GRDBTests/TableRecordUpdateTests.swift | 24 ++++- 14 files changed, 165 insertions(+), 43 deletions(-) diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 65bf9c0b2..d7d7663ec 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -426,7 +426,7 @@ extension QueryInterfaceRequest { // MARK: - Batch Delete and Fetch extension QueryInterfaceRequest { -#if GRDBCUSTOMSQLITE +#if GRDBCUSTOMSQLITE || GRDBCIPHER /// Returns a `DELETE ... RETURNING ...` prepared statement. /// /// For example: @@ -714,7 +714,7 @@ extension QueryInterfaceRequest { // MARK: - Batch Update and Fetch extension QueryInterfaceRequest { -#if GRDBCUSTOMSQLITE +#if GRDBCUSTOMSQLITE || GRDBCIPHER /// Returns an `UPDATE ... RETURNING ...` prepared statement. /// /// For example: diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 7b62a139d..1455793e8 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -402,7 +402,6 @@ struct SQLQueryGenerator: Refinable { statement.arguments = arguments return statement } else { - assert(sqlite3_libversion_number() >= 3035000) let context = SQLGenerationContext(db) var sql = sql var arguments = arguments diff --git a/GRDB/Record/MutablePersistableRecord+DAO.swift b/GRDB/Record/MutablePersistableRecord+DAO.swift index e4e4cc19f..e86a0fdd1 100644 --- a/GRDB/Record/MutablePersistableRecord+DAO.swift +++ b/GRDB/Record/MutablePersistableRecord+DAO.swift @@ -190,7 +190,6 @@ final class DAO { statement.setUncheckedArguments(arguments) return statement } else { - assert(sqlite3_libversion_number() >= 3035000) let context = SQLGenerationContext(db) var sql = sql var arguments = arguments diff --git a/GRDB/Record/MutablePersistableRecord+Insert.swift b/GRDB/Record/MutablePersistableRecord+Insert.swift index 13d3a67fe..16f15d334 100644 --- a/GRDB/Record/MutablePersistableRecord+Insert.swift +++ b/GRDB/Record/MutablePersistableRecord+Insert.swift @@ -72,7 +72,7 @@ extension MutablePersistableRecord { // MARK: - Insert and Fetch extension MutablePersistableRecord { -#if GRDBCUSTOMSQLITE +#if GRDBCUSTOMSQLITE || GRDBCIPHER /// Executes an `INSERT ... RETURNING ...` statement, and returns the /// inserted record. /// diff --git a/GRDB/Record/MutablePersistableRecord+Save.swift b/GRDB/Record/MutablePersistableRecord+Save.swift index fc4435da7..23e0a4b34 100644 --- a/GRDB/Record/MutablePersistableRecord+Save.swift +++ b/GRDB/Record/MutablePersistableRecord+Save.swift @@ -77,7 +77,7 @@ extension MutablePersistableRecord { // MARK: - Save and Fetch extension MutablePersistableRecord { -#if GRDBCUSTOMSQLITE +#if GRDBCUSTOMSQLITE || GRDBCIPHER /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` /// statement, and returns the saved row. /// diff --git a/GRDB/Record/MutablePersistableRecord+Update.swift b/GRDB/Record/MutablePersistableRecord+Update.swift index bc272c3ce..a8c14d009 100644 --- a/GRDB/Record/MutablePersistableRecord+Update.swift +++ b/GRDB/Record/MutablePersistableRecord+Update.swift @@ -150,7 +150,7 @@ extension MutablePersistableRecord { // MARK: - Update and Fetch extension MutablePersistableRecord { -#if GRDBCUSTOMSQLITE +#if GRDBCUSTOMSQLITE || GRDBCIPHER /// Executes an `UPDATE ... RETURNING ...` statement, and returns the /// updated record. /// @@ -700,7 +700,7 @@ extension MutablePersistableRecord { // MARK: - Internals extension MutablePersistableRecord { -#if GRDBCUSTOMSQLITE +#if GRDBCUSTOMSQLITE || GRDBCIPHER @inlinable // allow specialization so that empty callbacks are removed func updateChangesAndFetch( _ db: Database, diff --git a/GRDB/Record/MutablePersistableRecord+Upsert.swift b/GRDB/Record/MutablePersistableRecord+Upsert.swift index f53bf6304..ea3022ecd 100644 --- a/GRDB/Record/MutablePersistableRecord+Upsert.swift +++ b/GRDB/Record/MutablePersistableRecord+Upsert.swift @@ -1,7 +1,7 @@ // MARK: - Upsert extension MutablePersistableRecord { -#if GRDBCUSTOMSQLITE +#if GRDBCUSTOMSQLITE || GRDBCIPHER /// Executes an `INSERT ... ON CONFLICT DO UPDATE` statement. /// /// - parameter db: A database connection. diff --git a/GRDB/Record/PersistableRecord+Insert.swift b/GRDB/Record/PersistableRecord+Insert.swift index 924a5aaa5..504cb3c0f 100644 --- a/GRDB/Record/PersistableRecord+Insert.swift +++ b/GRDB/Record/PersistableRecord+Insert.swift @@ -36,7 +36,7 @@ extension PersistableRecord { // MARK: - Insert and Fetch extension PersistableRecord { -#if GRDBCUSTOMSQLITE +#if GRDBCUSTOMSQLITE || GRDBCIPHER /// Executes an `INSERT ... RETURNING ...` statement, and returns a new /// record built from the inserted row. /// diff --git a/GRDB/Record/PersistableRecord+Save.swift b/GRDB/Record/PersistableRecord+Save.swift index b33599474..125985627 100644 --- a/GRDB/Record/PersistableRecord+Save.swift +++ b/GRDB/Record/PersistableRecord+Save.swift @@ -32,7 +32,7 @@ extension PersistableRecord { // MARK: - Save and Fetch extension PersistableRecord { -#if GRDBCUSTOMSQLITE +#if GRDBCUSTOMSQLITE || GRDBCIPHER /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` /// statement, and returns a new record built from the saved row. /// diff --git a/GRDB/Record/PersistableRecord+Upsert.swift b/GRDB/Record/PersistableRecord+Upsert.swift index e3ab46fa6..cfb02b060 100644 --- a/GRDB/Record/PersistableRecord+Upsert.swift +++ b/GRDB/Record/PersistableRecord+Upsert.swift @@ -1,7 +1,7 @@ // MARK: - Upsert extension PersistableRecord { -#if GRDBCUSTOMSQLITE +#if GRDBCUSTOMSQLITE || GRDBCIPHER /// Executes an `INSERT ... ON CONFLICT DO UPDATE` statement. /// /// - parameter db: A database connection. diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index ebdcb77ba..93e415ba1 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -1163,7 +1163,11 @@ class MutablePersistableRecordTests: GRDBTestCase { extension MutablePersistableRecordTests { func test_insertAndFetch() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1180,7 +1184,11 @@ extension MutablePersistableRecordTests { } func test_insertAndFetch_as() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1226,7 +1234,11 @@ extension MutablePersistableRecordTests { } func test_insertAndFetch_selection_fetch() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1276,7 +1288,11 @@ extension MutablePersistableRecordTests { extension MutablePersistableRecordTests { func test_saveAndFetch() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1293,7 +1309,11 @@ extension MutablePersistableRecordTests { } func test_saveAndFetch_as() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1415,7 +1435,11 @@ extension MutablePersistableRecordTests { } func test_saveAndFetch_selection_fetch() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1541,7 +1565,11 @@ extension MutablePersistableRecordTests { extension MutablePersistableRecordTests { func test_updateAndFetch() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1588,7 +1616,11 @@ extension MutablePersistableRecordTests { } func test_updateAndFetch_as() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1634,7 +1666,11 @@ extension MutablePersistableRecordTests { } func test_updateAndFetch_selection_fetch() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1684,7 +1720,11 @@ extension MutablePersistableRecordTests { } func test_updateAndFetch_columns_selection_fetch() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1734,7 +1774,11 @@ extension MutablePersistableRecordTests { } func test_updateChangesAndFetch_modify() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1791,7 +1835,11 @@ extension MutablePersistableRecordTests { } func test_updateChangesAndFetch_as_modify() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1847,7 +1895,11 @@ extension MutablePersistableRecordTests { } func test_updateChangesAndFetch_selection_fetch_modify() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1909,7 +1961,11 @@ extension MutablePersistableRecordTests { extension MutablePersistableRecordTests { func test_upsert() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -2054,7 +2110,11 @@ extension MutablePersistableRecordTests { } func test_upsertAndFetch_as() throws { -#if !GRDBCUSTOMSQLITE +#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") } diff --git a/Tests/GRDBTests/PersistableRecordTests.swift b/Tests/GRDBTests/PersistableRecordTests.swift index 91b82d5b7..65536d49e 100644 --- a/Tests/GRDBTests/PersistableRecordTests.swift +++ b/Tests/GRDBTests/PersistableRecordTests.swift @@ -1327,7 +1327,11 @@ extension PersistableRecordTests { extension PersistableRecordTests { func test_insertAndFetch_as() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1372,7 +1376,11 @@ extension PersistableRecordTests { } func test_insertAndFetch_selection_fetch() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1421,7 +1429,11 @@ extension PersistableRecordTests { extension PersistableRecordTests { func test_saveAndFetch_as() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1540,7 +1552,11 @@ extension PersistableRecordTests { } func test_saveAndFetch_selection_fetch() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1663,7 +1679,11 @@ extension PersistableRecordTests { extension PersistableRecordTests { func test_upsert() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -1796,7 +1816,11 @@ extension PersistableRecordTests { } func test_upsertAndFetch_as() throws { -#if !GRDBCUSTOMSQLITE +#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") } diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index 948a84366..ee8f21011 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -230,7 +230,11 @@ class TableRecordDeleteTests: GRDBTestCase { } func testRequestDeleteAndFetchStatement() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -246,7 +250,11 @@ class TableRecordDeleteTests: GRDBTestCase { } func testRequestDeleteAndFetchCursor() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -295,7 +303,11 @@ class TableRecordDeleteTests: GRDBTestCase { } func testRequestDeleteAndFetchArray() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -319,7 +331,11 @@ class TableRecordDeleteTests: GRDBTestCase { } func testRequestDeleteAndFetchSet() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -401,7 +417,11 @@ class TableRecordDeleteTests: GRDBTestCase { } func testJoinedRequestDeleteAndFetch() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -564,7 +584,11 @@ class TableRecordDeleteTests: GRDBTestCase { } func testGroupedRequestDeleteAndFetchCursor() throws { -#if !GRDBCUSTOMSQLITE +#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") } diff --git a/Tests/GRDBTests/TableRecordUpdateTests.swift b/Tests/GRDBTests/TableRecordUpdateTests.swift index 69ee86938..eeabd3bfc 100644 --- a/Tests/GRDBTests/TableRecordUpdateTests.swift +++ b/Tests/GRDBTests/TableRecordUpdateTests.swift @@ -118,7 +118,11 @@ class TableRecordUpdateTests: GRDBTestCase { } func testRequestUpdateAndFetchStatement() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -137,7 +141,11 @@ class TableRecordUpdateTests: GRDBTestCase { } func testRequestUpdateAndFetchCursor() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -160,7 +168,11 @@ class TableRecordUpdateTests: GRDBTestCase { } func testRequestUpdateAndFetchAll() throws { -#if !GRDBCUSTOMSQLITE +#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") } @@ -184,7 +196,11 @@ class TableRecordUpdateTests: GRDBTestCase { } func testRequestUpdateAndFetchSet() throws { -#if !GRDBCUSTOMSQLITE +#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") } From 1036dd4d6e76ffb58444bef9c7f5ca02a0958e26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Aug 2022 21:56:51 +0200 Subject: [PATCH 73/73] v6.0.0-beta --- CHANGELOG.md | 8 ++++++- Documentation/FullTextSearch.md | 4 ++-- Documentation/Migrations.md | 2 +- GRDB.swift.podspec | 2 +- Makefile | 6 ++--- README.md | 42 ++++++++++++++++----------------- Support/Info.plist | 2 +- 7 files changed, 36 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 59d459cc3..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,7 +97,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- -## 6.0.0 +## 6.0.0-beta + +Released August 21, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.26.0...v6.0.0-beta) ### New diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 7fc072795..53eeb3771 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -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, @@ -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, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index d3cc848b1..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 diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 36bf19774..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.' diff --git a/Makefile b/Makefile index dc724ad20..21bd899c0 100644 --- a/Makefile +++ b/Makefile @@ -496,10 +496,10 @@ ifdef JAZZY --author 'Gwendal Roué' \ --author_url https://github.com/groue \ --github_url https://github.com/groue/GRDB.swift \ - --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.26.0 \ - --module-version 5.26.0 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v6.0.0-beta \ + --module-version 6.0.0-beta \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/5.26/ \ + --root-url http://groue.github.io/GRDB.swift/docs/6.0.0-beta/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index 08aab0321..353754485 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**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 5 to GRDB 6](Documentation/GRDB6MigrationGuide.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.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.7+** | **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) | @@ -322,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 @@ -616,7 +616,7 @@ do { > **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 @@ -673,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. @@ -931,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 @@ -1010,7 +1010,7 @@ let rows = try Row.fetchAll(db, arguments: ["name": "Arthur"]) ``` -See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.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: @@ -1318,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 = ... @@ -1789,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 @@ -1901,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] @@ -1984,7 +1984,7 @@ See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates) > **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 @@ -2728,7 +2728,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.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. > **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()`. @@ -3140,7 +3140,7 @@ Here is a list with all the available callbacks, listed in the same order in whi - `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/5.26/Protocols/MutablePersistableRecord.html). +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. @@ -3333,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 @@ -3355,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). @@ -4915,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) @@ -5821,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 @@ -7154,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 @@ -8518,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). @@ -8667,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 @@ -8720,7 +8720,7 @@ 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 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