From b14ef2112c5c2a5814fae23da3eb6c14ab85db15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Nov 2022 12:55:35 +0100 Subject: [PATCH 01/69] Fix documentation typo --- 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 219aad488..842d0edc3 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -1603,7 +1603,7 @@ public final class ColumnDefinition { } } -/// Table creation options +/// Index creation options public struct IndexOptions: OptionSet { public let rawValue: Int From 8ffceb49c8fb3cc0c956ee9908161d2555d3cdf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Nov 2022 15:14:59 +0100 Subject: [PATCH 02/69] Document SPI_BUILDER --- Package.swift | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index cfcd74ed6..84fd49f6c 100644 --- a/Package.swift +++ b/Package.swift @@ -16,8 +16,12 @@ if ProcessInfo.processInfo.environment["SQLITE_ENABLE_PREUPDATE_HOOK"] == "1" { cSettings.append(.define("GRDB_SQLITE_ENABLE_PREUPDATE_HOOK")) } -// Don't rely on this environment variable. It is only a convenience: -// $ make docs-localhost +// The SPI_BUILDER environment variable enables documentation building +// on . See +// +// for more information. +// +// SPI_BUILDER also enables the `make docs-localhost` command. var dependencies: [PackageDescription.Package.Dependency] = [] if ProcessInfo.processInfo.environment["SPI_BUILDER"] == "1" { dependencies.append(.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0")) From 981d42aed62531bc52c71becd2fb128932837958 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Nov 2022 11:32:56 +0100 Subject: [PATCH 03/69] Execute SPM tests in parallel --- .gitignore | 1 - .../contents.xcworkspacedata | 7 + .../xcschemes/GRDB-Package.xcscheme | 134 ++++++++++++++++++ 3 files changed, 141 insertions(+), 1 deletion(-) create mode 100644 .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata create mode 100644 .swiftpm/xcode/xcshareddata/xcschemes/GRDB-Package.xcscheme diff --git a/.gitignore b/.gitignore index 6d0da4123..cd1383aee 100644 --- a/.gitignore +++ b/.gitignore @@ -106,7 +106,6 @@ Podfile.lock # SPM .build -.swiftpm/ GRDB.xcworkspace/xcshareddata/swiftpm #Package.resolved Tests/SPM/Packages diff --git a/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..919434a62 --- /dev/null +++ b/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/GRDB-Package.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/GRDB-Package.xcscheme new file mode 100644 index 000000000..b60345c20 --- /dev/null +++ b/.swiftpm/xcode/xcshareddata/xcschemes/GRDB-Package.xcscheme @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 5d50e396c14620fb5afc660b6bb1a7ee45d1f1b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Nov 2022 11:19:56 +0100 Subject: [PATCH 04/69] Enhance Configuration documentation --- GRDB/Core/Configuration.swift | 124 +++++++++++++++++++++++----------- GRDB/Core/Database.swift | 7 ++ README.md | 2 +- 3 files changed, 91 insertions(+), 42 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 6c139d36e..bf3d17f03 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -19,6 +19,35 @@ import Foundation /// ``` /// /// See . +/// +/// ## Topics +/// +/// ### Creating a Configuration +/// +/// - ``init()`` +/// +/// ### Configuring SQLite Connections +/// +/// - ``acceptsDoubleQuotedStringLiterals`` +/// - ``busyMode`` +/// - ``foreignKeysEnabled`` +/// - ``readonly`` +/// +/// ### Configuring GRDB Connections +/// +/// - ``allowsUnsafeTransactions`` +/// - ``defaultTransactionKind`` +/// - ``label`` +/// - ``maximumReaderCount`` +/// - ``observesSuspensionNotifications`` +/// - ``prepareDatabase(_:)`` +/// - ``publicStatementArguments`` +/// +/// ### Configuring the Quality of Service +/// +/// - ``qos`` +/// - ``targetQueue`` +/// - ``writeTargetQueue`` public struct Configuration { // MARK: - Misc options @@ -40,9 +69,9 @@ public struct Configuration { /// You can query this label at runtime: /// /// ```swift - /// var configuration = Configuration() - /// configuration.label = "MyDatabase" - /// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration) + /// var config = Configuration() + /// config.label = "MyDatabase" + /// let dbQueue = try DatabaseQueue(configuration: config) /// /// try dbQueue.read { db in /// print(db.configuration.label) // Prints "MyDatabase" @@ -90,25 +119,24 @@ public struct Configuration { /// double-quoted strings as string literals when they does not match any /// valid identifier. /// - /// The default and recommended value is false. - /// - /// For example: + /// The default and recommended value is false: /// /// ```swift - /// // Error: no such column: foo + /// // Error: no such column: missingColumn /// let name = try String.fetchOne(db, sql: """ - /// SELECT "foo" FROM "player" + /// SELECT "missingColumn" FROM "player" /// """) /// ``` /// - /// When true, or before SQLite version 3.29.0, such strings are interpreted - /// as string literals, as in the example below. This is a well known SQLite - /// [misfeature](https://sqlite.org/quirks.html#dblquote): + /// When true, or before SQLite version 3.29.0, double-quoted strings that + /// do not match any valid identifier are interpreted as string literals, + /// as in the example below. This is an SQLite + /// [misfeature](https://sqlite.org/quirks.html#double_quoted_string_literals_are_accepted): /// /// ```swift - /// // Success: "foo" + /// // MISFEATURE: This query succeeds with result "missingColumn" /// let name = try String.fetchOne(db, sql: """ - /// SELECT "foo" FROM "player" + /// SELECT "missingColumn" FROM "player" /// """) /// ``` public var acceptsDoubleQuotedStringLiterals = false @@ -119,13 +147,10 @@ public struct Configuration { /// /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// - /// Database suspension helps avoiding the - /// [`0xdead10cc` exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report). - /// - /// During suspension, all database accesses but reads in WAL mode may throw - /// a ``DatabaseError`` of code `SQLITE_INTERRUPT` or `SQLITE_ABORT`. You - /// can check for those error codes with the - /// ``DatabaseError/isInterruptionError`` property. + /// Set this flag to true when you apply the technique described in + /// . See + /// ``Database/suspendNotification`` for more informations about + /// suspended databases. public var observesSuspensionNotifications = false /// A boolean value indicating whether statement arguments are visible in @@ -133,25 +158,24 @@ public struct Configuration { /// /// The default and recommended value is false: statement arguments are not /// visible in database errors and trace events, preventing sensitive - /// information from leaking in unexpected places. - /// - /// For example: + /// information from leaking in unexpected places. For example: /// /// ```swift - /// // Error: sensitive information is not printed when an error occurs: - /// do { - /// let email = "..." // sensitive information - /// let player = try Player.filter(Column("email") == email).fetchOne(db) - /// } catch { - /// print(error) - /// } - /// - /// // Trace: sensitive information is not printed when a statement is traced: /// db.trace { event in + /// // By default, sensitive information is NOT printed + /// // when a statement is traced: /// print(event) /// } - /// let email = "..." // sensitive information - /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// + /// do { + /// // The sensitive information to protect + /// let email = "..." + /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// } catch { + /// // By default, sensitive information is NOT printed + /// // when an error occurs: + /// print(error) + /// } /// ``` /// /// For debugging purpose, you can set this flag to true, and get more @@ -163,19 +187,21 @@ public struct Configuration { /// ```swift /// var config = Configuration() /// #if DEBUG - /// // Protect sensitive information by enabling verbose debugging in DEBUG builds only + /// // Enable verbose debugging in DEBUG builds only /// config.publicStatementArguments = true /// #endif /// - /// // The descriptions of trace events and errors now contain the - /// // sensitive information: /// db.trace { event in + /// // Sensitive information is printed in DEBUG builds: /// print(event) /// } + /// /// do { + /// // The sensitive information to protect /// let email = "..." /// let player = try Player.filter(Column("email") == email).fetchOne(db) /// } catch { + /// // Sensitive information is printed in DEBUG builds: /// print(error) /// } /// ``` @@ -198,7 +224,8 @@ public struct Configuration { /// ```swift /// var config = Configuration() /// config.prepareDatabase { db in - /// try db.execute(sql: "PRAGMA kdf_iter = 10000") + /// // Prints all SQL statements + /// db.trace { print("SQL >", $0) } /// } /// ``` /// @@ -225,10 +252,25 @@ public struct Configuration { // MARK: - Transactions - /// The default kind of transaction. + /// The default kind of write transactions. /// /// The default is ``Database/TransactionKind/deferred``. /// + /// You can change the default transaction kind. For example, you can force + /// all write transactions to be `IMMEDIATE`: + /// + /// ```swift + /// var config = Configuration() + /// config.defaultTransactionKind = .immediate + /// let dbQueue = try DatabaseQueue(configuration: config) + /// + /// // BEGIN IMMEDIATE TRANSACTION; ...; COMMIT TRANSACTION; + /// try dbQueue.write { db in ... } + /// ``` + /// + /// This property is ignored for read-only transactions. Those always open + /// `DEFERRED` SQLite transactions. + /// /// Related SQLite documentation: public var defaultTransactionKind: Database.TransactionKind = .deferred @@ -288,7 +330,7 @@ public struct Configuration { /// is 5. public var maximumReaderCount: Int = 5 - /// The quality of service, or the execution priority, or database accesses. + /// The quality of service of database accesses. /// /// The quality of service is ignored if you supply a ``targetQueue``. /// @@ -316,7 +358,7 @@ public struct Configuration { /// The default is nil. public var targetQueue: DispatchQueue? = nil - /// The target dispatch queue for database accesses which are not read-only. + /// The target dispatch queue for write database accesses. /// /// If this queue is nil, writer connections are controlled /// by ``targetQueue``. diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 780ecd549..cd053a86b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -878,6 +878,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// are suspended. /// /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// A suspended database makes everything to avoid acquiring a lock on the + /// database. All database operations may throw a ``DatabaseError`` of code + /// `SQLITE_INTERRUPT` or `SQLITE_ABORT`, except reads in WAL mode. + /// + /// See for + /// more information. public static let suspendNotification = Notification.Name("GRDB.Database.Suspend") /// When this notification is posted, databases which were opened with the diff --git a/README.md b/README.md index 157225250..267bea9c9 100644 --- a/README.md +++ b/README.md @@ -8616,7 +8616,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](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/acceptsdoublequotedstringliterals). +For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#double_quoted_string_literals_are_accepted), and [Configuration.acceptsDoubleQuotedStringLiterals](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/acceptsdoublequotedstringliterals). From 6dc4d50e001260cfab0ef5c28376abcd97d7b852 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Nov 2022 11:20:40 +0100 Subject: [PATCH 05/69] Expose Configuration.readQoS and writeQoS This helps tools that perform their own asynchronous jobs that depend on database scheduling. By using the same QoS as the database, they won't create priority inversion or similar scheduling misuses. --- GRDB/Core/Configuration.swift | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index bf3d17f03..f604890f5 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -46,6 +46,8 @@ import Foundation /// ### Configuring the Quality of Service /// /// - ``qos`` +/// - ``readQoS`` +/// - ``writeQoS`` /// - ``targetQueue`` /// - ``writeTargetQueue`` public struct Configuration { @@ -337,11 +339,16 @@ public struct Configuration { /// The default is `userInitiated`. public var qos: DispatchQoS = .userInitiated - /// The quality of service of read accesses - var readQoS: DispatchQoS { + /// The effective quality of service of read-only database accesses. + public var readQoS: DispatchQoS { targetQueue?.qos ?? self.qos } + /// The effective quality of service of write database accesses. + public var writeQoS: DispatchQoS { + writeTargetQueue?.qos ?? targetQueue?.qos ?? self.qos + } + /// The target dispatch queue for database accesses. /// /// Database connections which are not read-only will prefer From 638e586dbcdbc60c9f2af605f2cedc5a8d1efba9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Sep 2022 14:46:55 +0200 Subject: [PATCH 06/69] Expose Database.registerAccess(to:) This helps tools that intend to declare an observed region without directly accessing it. This will be necessary for (future) snapshot-based observations that postpone actual database access. --- GRDB/Core/Database+Statements.swift | 4 +- GRDB/Core/Database.swift | 75 +++++++++++++++----- GRDB/ValueObservation/ValueObservation.swift | 39 +++++++++- 3 files changed, 97 insertions(+), 21 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 25993284b..6a8d52f01 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -431,9 +431,7 @@ extension Database { try checkForSuspensionViolation(from: statement) // Record the database region selected by the statement execution. - if isRecordingSelectedRegion { - selectedRegion.formUnion(statement.databaseRegion) - } + try registerAccess(to: statement.databaseRegion) // Database observation: prepare transaction observers. observationBroker?.statementWillExecute(statement) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index cd053a86b..013d682f8 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -64,11 +64,12 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// - ``TransactionCompletion`` /// - ``TransactionKind`` /// -/// ### Observing Database Transactions +/// ### Database Observation /// /// - ``add(transactionObserver:extent:)`` /// - ``afterNextTransaction(onCommit:onRollback:)`` /// - ``remove(transactionObserver:)`` +/// - ``registerAccess(to:)`` /// /// ### Collations /// @@ -259,9 +260,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } /// Whether the database region selected by statement execution is - /// recorded into `selectedRegion`. + /// recorded into `selectedRegion` by `track(_:)`. /// - /// To record the selected region, use `recordingSelection(_:_:)`. + /// To start recording the selected region, use `recordingSelection(_:_:)`. private(set) var isRecordingSelectedRegion = false /// The database region selected by statement execution, when @@ -686,27 +687,67 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib readOnlyDepth > 0 || configuration.readonly } - // MARK: - Recording of the selected region + // MARK: - Database Observation - /// Extends the `region` argument with the database region selected by all - /// statements executed by the closure. + /// Reports the region to ``ValueObservation``. /// /// 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] + /// ```swift + /// let observation = ValueObservation.tracking { db in + /// // All changes to the 'player' and 'team' tables + /// // will trigger the observation. + /// try db.registerAccess(to: Table("player")) + /// try db.registerAccess(to: Table("team")) + /// } + /// ``` + /// + /// See ``ValueObservation/trackingConstantRegion(_:)`` for some examples + /// of such explicit region tracking. + /// + /// This method only has an effect if and only if the ``ValueObservation`` + /// is inferring the observed region from the database access. In the + /// example below, the observation explicitly tracks the `player` table + /// only. All calls to the `registerAccess` method are ignored: + /// + /// ```swift + /// // Observes the 'player' table only + /// let observation = ValueObservation.tracking(region: Table("player")) { db in + /// // Ignored + /// try db.registerAccess(to: Table("team")) + /// } + /// ``` + public func registerAccess(to region: @autoclosure () -> some DatabaseRegionConvertible) throws { + if isRecordingSelectedRegion { + try selectedRegion.formUnion(region().databaseRegion(self)) + } + } + + /// Extends the `region` argument with the database region selected by all + /// statements executed by the closure, and all regions explicitly tracked + /// with the ``registerAccess(to:)`` method. + /// + /// For example: + /// + /// ```swift + /// var region = DatabaseRegion() + /// try db.recordingSelection(®ion) { + /// let players = try Player.fetchAll(db) + /// let team = try Team.fetchOne(db, id: 42) + /// try db.registerAccess(to: Table("awards")) + /// } + /// print(region) // awards,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) - /// } + /// ```swift + /// 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() diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 13dac99cc..31208226a 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -31,7 +31,7 @@ import Foundation /// - ``tracking(region:fetch:)`` /// - ``tracking(regions:fetch:)`` /// -/// ### Creating A Shared Observation +/// ### Creating a Shared Observation /// /// - ``shared(in:scheduling:extent:)`` /// - ``SharedValueObservationExtent`` @@ -693,6 +693,43 @@ extension ValueObservation where Reducer == ValueReducers.Auto { /// } /// ``` /// + /// You can turn them into optimized observations of a constant region with + /// the ``Database/registerAccess(to:)`` method: + /// + /// ```swift + /// let observation = ValueObservation.trackingConstantRegion { db -> Player? in + /// // Track all players so that the observed region does not depend on + /// // the rowid of the favorite player. + /// try db.registerAccess(to: Player.all()) + /// + /// let pref = try Preference.fetchOne(db) ?? .default + /// return try Player.fetchOne(db, id: pref.favoritePlayerId) + /// } + /// + /// let observation = ValueObservation.trackingConstantRegion { db -> [User] in + /// // Track all players so that the observed region does not change + /// // even if there is no favorite player at all. + /// try db.registerAccess(to: Player.all()) + /// + /// let pref = try Preference.fetchOne(db) ?? .default + /// let playerIds: [Int64] = pref.favoritePlayerIds // may be empty + /// return try Player.fetchAll(db, ids: playerIds) + /// } + /// + /// let observation = ValueObservation.trackingConstantRegion { db -> Int in + /// // Track foods and beverages so that the observed region does not + /// // depend on preferences. + /// try db.registerAccess(to: Food.all()) + /// try db.registerAccess(to: Beverage.all()) + /// + /// let pref = try Preference.fetchOne(db) ?? .default + /// switch pref.selection { + /// case .food: return try Food.fetchCount(db) + /// case .beverage: return try Beverage.fetchCount(db) + /// } + /// } + /// ``` + /// /// - parameter fetch: The closure that fetches the observed value. public static func trackingConstantRegion( _ fetch: @escaping (Database) throws -> Value) From 51230834c8fe9a5e118d55ca3859a8c79ff1d2eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Sep 2022 11:37:58 +0200 Subject: [PATCH 07/69] Configuration.maximumReaderCount can be queried This is useful for tools that adapt their own inner scheduling to the actual capacity for concurrent reads. --- GRDB/Core/Configuration.swift | 16 ++++++++++++++++ GRDB/Core/DatabaseQueue.swift | 4 ++++ GRDB/Core/DatabaseSnapshot.swift | 5 ++++- 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index f604890f5..ae2e1cb02 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -330,6 +330,22 @@ public struct Configuration { /// /// This configuration applies to ``DatabasePool`` only. The default value /// is 5. + /// + /// You can query this value at runtime in order to get the actual capacity + /// for concurrent reads of any ``DatabaseReader``. For example: + /// + /// ```swift + /// var config = Configuration() + /// config.maximumReaderCount = 5 + /// + /// let path = "/path/to/database.sqlite" + /// let dbQueue = try DatabaseQueue(path: path, configuration: config) + /// let dbPool = try DatabasePool(path: path, configuration: config) + /// let dbSnapshot = try dbPool.makeSnapshot() + /// + /// print(dbQueue.configuration.maximumReaderCount) // 1 + /// print(dbPool.configuration.maximumReaderCount) // 5 + /// print(dbSnapshot.configuration.maximumReaderCount) // 1 public var maximumReaderCount: Int = 5 /// The quality of service of database accesses. diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index e2d38695b..a7a6bba45 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -83,6 +83,10 @@ public final class DatabaseQueue { /// - configuration: A configuration. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public init(path: String, configuration: Configuration = Configuration()) throws { + // DatabaseQueue can't perform parallel reads + var configuration = configuration + configuration.maximumReaderCount = 1 + writer = try SerializedDatabase( path: path, configuration: configuration, diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index c4a36b361..ccf462077 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -71,7 +71,10 @@ public final class DatabaseSnapshot { init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws { var configuration = DatabasePool.readerConfiguration(configuration) - configuration.allowsUnsafeTransactions = true // Snapshot keeps a long-lived transaction + // DatabaseSnapshot can't perform parallel reads + configuration.maximumReaderCount = 1 + // Snapshot keeps a long-lived transaction + configuration.allowsUnsafeTransactions = true serializedDatabase = try SerializedDatabase( path: path, From 997d6cb6774ceb1743a00d08987a11aa80028a13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Nov 2022 12:44:23 +0100 Subject: [PATCH 08/69] DatabaseSnapshot does not require the WAL mode One can create a snapshot from a read-only pool on a non-WAL database, and that's OK. The snaphost still sees an unchanging database content (but other connections can't write). --- GRDB/Core/DatabasePool.swift | 2 +- GRDB/Core/DatabaseSnapshot.swift | 62 ++++++++++++++++---------------- 2 files changed, 33 insertions(+), 31 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 8dabe85ea..e40ebf400 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -876,7 +876,7 @@ extension DatabasePool { return try DatabaseSnapshot( path: path, - configuration: writer.configuration, + configuration: DatabasePool.readerConfiguration(writer.configuration), defaultLabel: "GRDB.DatabasePool", purpose: "snapshot.\($databaseSnapshotCount.increment())") } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index ccf462077..3a9e66efa 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -9,17 +9,21 @@ import Dispatch /// accesses are executed in a serial **reader dispatch queue**. The SQLite /// connection is closed when the `DatabaseSnapshot` is deallocated. /// -/// `DatabaseSnapshot` never sees any database modification during all its -/// lifetime, and yet it doesn't prevent database updates. This "magic" is made -/// possible by SQLite's WAL mode. See -/// [Isolation In SQLite](https://sqlite.org/isolation.html) for -/// more information. +/// A snapshot never sees any database modification during all its lifetime. All +/// database accesses performed from a snapshot always see the same identical +/// database content. +/// +/// In the [WAL mode](https://sqlite.org/wal.html), a snapshot doesn't prevent +/// database modifications performed by other connections (but it won't see +/// them). Refer to [Isolation In SQLite](https://sqlite.org/isolation.html) for +/// more information. Otherwise, a snapshot prevents all writes to the database +/// as long as it exists, due to the +/// [SHARED lock](https://www.sqlite.org/lockingv3.html) it holds. /// /// ## Usage /// -/// You create instances of `DatabaseSnapshot` from a ``DatabasePool``, with -/// ``DatabasePool/makeSnapshot()``. The number of snapshots is unlimited, -/// regardless of the ``Configuration/maximumReaderCount`` configuration: +/// You create instances of `DatabaseSnapshot` from a ``DatabasePool``, +/// with ``DatabasePool/makeSnapshot()``: /// /// ```swift /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") @@ -62,44 +66,42 @@ import Dispatch /// `DatabaseSnapshot` inherits its database access methods from the /// ``DatabaseReader`` protocols. public final class DatabaseSnapshot { - private let serializedDatabase: SerializedDatabase + private let reader: SerializedDatabase - /// The database configuration public var configuration: Configuration { - serializedDatabase.configuration + reader.configuration } - init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws { - var configuration = DatabasePool.readerConfiguration(configuration) + /// The path to the database file. + public var path: String { + reader.path + } + + init(path: String, configuration: Configuration, defaultLabel: String, purpose: String? = nil) throws { + var configuration = configuration // DatabaseSnapshot can't perform parallel reads configuration.maximumReaderCount = 1 // Snapshot keeps a long-lived transaction configuration.allowsUnsafeTransactions = true - serializedDatabase = try SerializedDatabase( + reader = try SerializedDatabase( path: path, configuration: configuration, defaultLabel: defaultLabel, purpose: purpose) - try serializedDatabase.sync { db in - // Assert WAL mode - let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode") - guard journalMode == "wal" else { - throw DatabaseError(message: "WAL mode is not activated at path: \(path)") - } - + try reader.sync { db in // Open transaction try db.beginTransaction(.deferred) // Acquire snapshot isolation - try db.internalCachedStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next() + try db.makeStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next() } } deinit { // Leave snapshot isolation - serializedDatabase.reentrantSync { db in + reader.reentrantSync { db in try? db.commit() } } @@ -107,35 +109,35 @@ public final class DatabaseSnapshot { extension DatabaseSnapshot: DatabaseReader { public func close() throws { - try serializedDatabase.sync { try $0.close() } + try reader.sync { try $0.close() } } // MARK: - Interrupting Database Operations public func interrupt() { - serializedDatabase.interrupt() + reader.interrupt() } // MARK: - Reading from Database public func read(_ block: (Database) throws -> T) rethrows -> T { - try serializedDatabase.sync(block) + try reader.sync(block) } public func asyncRead(_ value: @escaping (Result) -> Void) { - serializedDatabase.async { value(.success($0)) } + reader.async { value(.success($0)) } } public func unsafeRead(_ value: (Database) throws -> T) rethrows -> T { - try serializedDatabase.sync(value) + try reader.sync(value) } public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { - serializedDatabase.async { value(.success($0)) } + reader.async { value(.success($0)) } } public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { - try serializedDatabase.reentrantSync(value) + try reader.reentrantSync(value) } // MARK: - Database Observation From cbac0e7286aeefd9a223a0744d9c958218dc25c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Nov 2022 13:48:04 +0100 Subject: [PATCH 09/69] Enhance Configuration.threadingMode documentation --- GRDB/Core/Configuration.swift | 8 +++++++- GRDB/Core/Database.swift | 4 ++++ GRDB/Core/SerializedDatabase.swift | 2 +- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index ae2e1cb02..174e96965 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -405,7 +405,13 @@ public struct Configuration { // MARK: - Not Public - var threadingMode: Database.ThreadingMode = .`default` + /// The SQLite [threading mode](https://www.sqlite.org/threadsafe.html). + /// + /// - Note: Only the multi-thread mode (`SQLITE_OPEN_NOMUTEX`) is currently + /// supported, since all access SQLite connections + /// through a `SerializedDatabase`. + var threadingMode = Database.ThreadingMode.default + var SQLiteConnectionDidOpen: (() -> Void)? var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)? var SQLiteConnectionDidClose: (() -> Void)? diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 013d682f8..7c0b289a8 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -2016,6 +2016,10 @@ extension Database { } /// An SQLite threading mode. See . + /// + /// - Note: Only the multi-thread mode (`SQLITE_OPEN_NOMUTEX`) is currently + /// supported, since all access SQLite connections + /// through a `SerializedDatabase`. enum ThreadingMode { case `default` case multiThread diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 0927f9fc1..bcec3e9f7 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -1,6 +1,6 @@ import Foundation -/// A class that serializes accesses to a database. +/// A class that serializes accesses to an SQLite connection. final class SerializedDatabase { /// The database connection private let db: Database From a6f9b1c4b7606937bac3cf6c9e01cc0c69fc158b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Nov 2022 13:57:44 +0100 Subject: [PATCH 10/69] CHANGELOG --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 45a2bfdf6..cacdbced4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -101,6 +101,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## Next Version + +- **New**: The `Configuration.readQoS` and `writeQoS` properties return the effective quality of service of read-only and write database accesses. This helps application code avoid priority inversion and similar scheduling misuses when needed. +- **New**: `DatabaseReader.configuration.maximumReaderCount` returns the effective capacity for concurrent reads, so that application code can adapt when needed. +- **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime. +- **New**: `Database.registerAccess(to:)` has `ValueObservation` track a region. This helps building optimized observations of a constant database region with `ValueObservation.trackingConstantRegion(_:)`. + ## 6.3.1 Released November 11, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.3.0...v6.3.1) From 4871304c60eda2d41024e56889cea8cc80c75785 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 13 Nov 2022 15:29:01 +0100 Subject: [PATCH 11/69] Enable WALSnapshot on macOS (Xcode 14.1+) --- GRDB/Core/WALSnapshot.swift | 46 +++++++++++-------- .../ValueConcurrentObserver.swift | 10 ++-- Tests/GRDBTests/ValueObservationTests.swift | 4 +- 3 files changed, 33 insertions(+), 27 deletions(-) diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index 29c811b51..6ee1ddaf6 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -20,39 +20,45 @@ /// /// See . final class WALSnapshot { - // Xcode 14 RC ships with a macOS SDK that misses snapshot support. - // TODO: when Xcode ships with a macOS SDK that exposes snapshots, replace - // the `os(macOS) || targetEnvironment(macCatalyst)` check with a compiler - // version check. + // Xcode 14 ships with a macOS SDK that misses snapshot support. + // Xcode 14.1 ships with a macOS SDK that has snapshot support. + // This is the meaning of (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) // - // We can't enable snapshots for SQLCipher, since we don't know if they - // are enabled. -#if os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) - init?(_ db: Database) { - return nil + // We can't provide snapshots api for SQLCipher, since we'd have linker + // errors if they are not enabled. +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) + static let available = false + + init(_ db: Database) throws { + throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "snapshots are not available") } - + func compare(_ other: WALSnapshot) -> CInt { preconditionFailure("snapshots are not available") } #else - private let snapshot: UnsafeMutablePointer? + static let available = true + + let sqliteSnapshot: UnsafeMutablePointer /// Returns nil if `SQLITE_ENABLE_SNAPSHOT` is not enabled, or if an /// error occurs. - init?(_ db: Database) { - var snapshot: UnsafeMutablePointer? - let code = withUnsafeMutablePointer(to: &snapshot) { + init(_ db: Database) throws { + var sqliteSnapshot: UnsafeMutablePointer? + let code = withUnsafeMutablePointer(to: &sqliteSnapshot) { return sqlite3_snapshot_get(db.sqliteConnection, "main", $0) } - guard code == SQLITE_OK, let snapshot else { - return nil + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code) } - self.snapshot = snapshot + guard let sqliteSnapshot else { + throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite? + } + self.sqliteSnapshot = sqliteSnapshot } deinit { - sqlite3_snapshot_free(snapshot) + sqlite3_snapshot_free(sqliteSnapshot) } /// Compares two WAL snapshots. @@ -61,7 +67,7 @@ final class WALSnapshot { /// /// See . func compare(_ other: WALSnapshot) -> CInt { - return sqlite3_snapshot_cmp(snapshot, other.snapshot) + return sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot) } -#endif // os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#endif // (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) } diff --git a/GRDB/ValueObservation/ValueConcurrentObserver.swift b/GRDB/ValueObservation/ValueConcurrentObserver.swift index 5ccbfb6ab..dc3c3daa1 100644 --- a/GRDB/ValueObservation/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/ValueConcurrentObserver.swift @@ -286,12 +286,12 @@ extension ValueConcurrentObserver { let fetchedValue = try databaseAccess.fetch(db) let region = try DatabaseRegion.union(regions)(db) let initialRegion = try region.observableRegion(db) - return (fetchedValue, initialRegion, WALSnapshot(db)) + return (fetchedValue, initialRegion, try? WALSnapshot(db)) case .constantRegionRecordedFromSelection, .nonConstantRegionRecordedFromSelection: let (fetchedValue, initialRegion) = try databaseAccess.fetchRecordingObservedRegion(db) - return (fetchedValue, initialRegion, WALSnapshot(db)) + return (fetchedValue, initialRegion, try? WALSnapshot(db)) } } @@ -377,7 +377,7 @@ extension ValueConcurrentObserver { self.asyncStartObservation( from: databaseAccess, initialSnapshot: initialSnapshot, - initialWALSnapshot: WALSnapshot(db), + initialWALSnapshot: try? WALSnapshot(db), initialRegion: initialRegion) } catch { self.notifyError(error) @@ -403,13 +403,13 @@ extension ValueConcurrentObserver { // Transaction is needed for comparing version snapshots try writerDB.isolated(readOnly: true) { - // Keep DatabaseSnaphot alive until we have compared + // Keep initialSnapshot alive until we have compared // database versions. It prevents database checkpointing, // and keeps WAL snapshots (`sqlite3_snapshot`) valid // and comparable. let isModified = withExtendedLifetime(initialSnapshot) { guard let initialWALSnapshot, - let currentWALSnapshot = WALSnapshot(writerDB) + let currentWALSnapshot = try? WALSnapshot(writerDB) else { return true } diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index d540d6839..35abb25d1 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -421,7 +421,7 @@ class ValueObservationTests: GRDBTestCase { } let expectedCounts: [Int] - #if os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) + #if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) // Optimization not available expectedCounts = [0, 0, 1] #else @@ -471,7 +471,7 @@ class ValueObservationTests: GRDBTestCase { } let expectedCounts: [Int] - #if os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) + #if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) // Optimization not available expectedCounts = [0, 0, 1] #else From dffe56f8a9dace2dea53d7ae45eccefe337a1f67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 13 Nov 2022 11:50:33 +0100 Subject: [PATCH 12/69] Simplify ValueReducer definition --- GRDB/ValueObservation/ValueReducer/Map.swift | 2 +- .../ValueReducer/RemoveDuplicates.swift | 2 +- GRDB/ValueObservation/ValueReducer/Trace.swift | 2 +- .../ValueReducer/ValueReducer.swift | 16 ++++++---------- 4 files changed, 9 insertions(+), 13 deletions(-) diff --git a/GRDB/ValueObservation/ValueReducer/Map.swift b/GRDB/ValueObservation/ValueReducer/Map.swift index 453f84db0..c8f1debb7 100644 --- a/GRDB/ValueObservation/ValueReducer/Map.swift +++ b/GRDB/ValueObservation/ValueReducer/Map.swift @@ -32,7 +32,7 @@ extension ValueReducers { } } -extension ValueReducers.Map: _DatabaseValueReducer where Base: _DatabaseValueReducer { +extension ValueReducers.Map: ValueReducer where Base: ValueReducer { public func _fetch(_ db: Database) throws -> Base.Fetched { try base._fetch(db) } diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift index 31ac711f9..8311458a5 100644 --- a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift @@ -50,7 +50,7 @@ extension ValueReducers { } } -extension ValueReducers.RemoveDuplicates: _DatabaseValueReducer where Base: _DatabaseValueReducer { +extension ValueReducers.RemoveDuplicates: ValueReducer where Base: ValueReducer { public func _fetch(_ db: Database) throws -> Base.Fetched { try base._fetch(db) } diff --git a/GRDB/ValueObservation/ValueReducer/Trace.swift b/GRDB/ValueObservation/ValueReducer/Trace.swift index da41cfd73..bb2db4f62 100644 --- a/GRDB/ValueObservation/ValueReducer/Trace.swift +++ b/GRDB/ValueObservation/ValueReducer/Trace.swift @@ -20,7 +20,7 @@ extension ValueReducers { // swiftlint:enable line_length } -extension ValueReducers.Trace: _DatabaseValueReducer where Base: _DatabaseValueReducer { +extension ValueReducers.Trace: ValueReducer where Base: ValueReducer { public func _fetch(_ db: Database) throws -> Base.Fetched { willFetch() return try base._fetch(db) diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index d26f544c7..261d62b98 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -21,15 +21,6 @@ public protocol _ValueReducer { mutating func _value(_ fetched: Fetched) throws -> Value? } -/// Implementation details of `ValueReducer`, able to observe from any database -/// reader (``DatabaseQueue``, ``DatabasePool``). -public protocol _DatabaseValueReducer: _ValueReducer { - /// Fetches database values upon changes in an observed database region. - /// - /// This method must does not depend on the state of the reducer. - func _fetch(_ db: Database) throws -> Fetched -} - /// `ValueReducer` supports ``ValueObservation``. /// /// A `ValueReducer` fetches and transforms the database values @@ -40,7 +31,12 @@ public protocol _DatabaseValueReducer: _ValueReducer { /// ### Support /// /// - ``ValueReducers`` -public typealias ValueReducer = _ValueReducer & _DatabaseValueReducer +public protocol ValueReducer: _ValueReducer { + /// Fetches database values upon changes in an observed database region. + /// + /// This method must does not depend on the state of the reducer. + func _fetch(_ db: Database) throws -> Fetched +} /// A namespace for concrete types that adopt the ``ValueReducer`` protocol. public enum ValueReducers { From a71eb3d662c6edd0610222db807d01333ed0fcd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 13 Nov 2022 17:58:01 +0100 Subject: [PATCH 13/69] Introduce WALSnapshotToken --- GRDB.xcodeproj/project.pbxproj | 8 + GRDB/Core/Database+Schema.swift | 39 ++- GRDB/Core/DatabasePool.swift | 23 +- GRDB/Core/DatabaseSchemaCache.swift | 20 ++ GRDB/Core/DatabaseSnapshot.swift | 7 +- GRDB/Core/WALSnapshot.swift | 3 + GRDB/Core/WALSnapshotToken.swift | 327 ++++++++++++++++++++ GRDB/Documentation.docc/DatabaseSchema.md | 1 + GRDBCustom.xcodeproj/project.pbxproj | 8 + Tests/GRDBTests/DatabaseSnapshotTests.swift | 7 +- Tests/GRDBTests/WALSnapshotTokenTests.swift | 163 ++++++++++ 11 files changed, 586 insertions(+), 20 deletions(-) create mode 100644 GRDB/Core/WALSnapshotToken.swift create mode 100644 Tests/GRDBTests/WALSnapshotTokenTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 06012b132..a6e0c8ea8 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -202,6 +202,8 @@ 56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; }; 56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; }; 568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; }; + 568EB71929211E0800E59445 /* WALSnapshotToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71829211E0700E59445 /* WALSnapshotToken.swift */; }; + 568EB71E2921234800E59445 /* WALSnapshotTokenTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71D2921234800E59445 /* WALSnapshotTokenTests.swift */; }; 568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; }; 568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; }; 568ECB1825D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; }; @@ -616,6 +618,8 @@ 56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; }; 56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = ""; }; 568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = ""; }; + 568EB71829211E0700E59445 /* WALSnapshotToken.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotToken.swift; sourceTree = ""; }; + 568EB71D2921234800E59445 /* WALSnapshotTokenTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTokenTests.swift; sourceTree = ""; }; 568ECA8925D7013000B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = ""; }; 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = ""; }; 568ECB1725D9161500B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = ""; }; @@ -1356,6 +1360,7 @@ 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, + 568EB71D2921234800E59445 /* WALSnapshotTokenTests.swift */, ); name = Core; sourceTree = ""; @@ -1455,6 +1460,7 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 56B7EE822863781300C0525F /* WALSnapshot.swift */, + 568EB71829211E0700E59445 /* WALSnapshotToken.swift */, 5605F1471C672E4000235C62 /* Support */, ); path = Core; @@ -1785,6 +1791,7 @@ 56D496B01D813385008276D7 /* DatabaseErrorTests.swift in Sources */, 56176C5C1EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */, 562206061E420EA4005860AC /* DatabasePoolBackupTests.swift in Sources */, + 568EB71E2921234800E59445 /* WALSnapshotTokenTests.swift in Sources */, 56D496B51D813413008276D7 /* DatabaseCollationTests.swift in Sources */, 563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */, 56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */, @@ -2035,6 +2042,7 @@ 566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 5605F1591C672E4000235C62 /* CGFloat.swift in Sources */, 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, + 568EB71929211E0800E59445 /* WALSnapshotToken.swift in Sources */, 5605F1631C672E4000235C62 /* Date.swift in Sources */, 5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */, diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 8a66e2585..63ccaf628 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -22,6 +22,20 @@ extension Database { schemaIdentifiers = nil schemas.removeAll() } + + mutating func formUnion(_ other: SchemaCache) { + let schemaIdentifiers = Set(schemas.keys).union(other.schemas.keys) + for schemaIdentifier in schemaIdentifiers { + switch (schemas[schemaIdentifier], other.schemas[schemaIdentifier]) { + case let (nil, schema): + schemas[schemaIdentifier] = schema + case let (lhs?, rhs?): + schemas[schemaIdentifier] = lhs.union(rhs) + default: + break + } + } + } } /// An SQLite schema. See @@ -79,6 +93,13 @@ extension Database { // MARK: - Database Schema + /// Returns the current schema version. + /// + /// Related SQLite documentation: + public func schemaVersion() throws -> Int32 { + try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version"))! + } + /// Clears the database schema cache. /// /// If the database schema is modified by another SQLite connection to the @@ -106,7 +127,7 @@ extension Database { // at offset 40 of the database header: // // - let schemaVersion = try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version")) + let schemaVersion = try self.schemaVersion() if lastSchemaVersion != schemaVersion { lastSchemaVersion = schemaVersion clearSchemaCache() @@ -1317,11 +1338,8 @@ enum SchemaObjectType: String { struct SchemaInfo: Equatable { private var objects: Set - /// - parameter masterTable: "sqlite_master" or "sqlite_temp_master" - init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language - objects = try SchemaObject.fetchSet(db, sql: """ - SELECT type, name, tbl_name, sql FROM \(masterTableName) - """) + func union(_ other: SchemaInfo) -> SchemaInfo { + SchemaInfo(objects: objects.union(other.objects)) } /// Returns whether there exists a object of given type with this name @@ -1352,3 +1370,12 @@ struct SchemaInfo: Equatable { var sql: String? } } + +extension SchemaInfo { + /// - parameter masterTable: "sqlite_master" or "sqlite_temp_master" + init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language + objects = try SchemaObject.fetchSet(db, sql: """ + SELECT type, name, tbl_name, sql FROM \(masterTableName) + """) + } +} diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index e40ebf400..b2ccad1a0 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -46,10 +46,6 @@ import UIKit /// /// - ``init(path:configuration:)`` /// -/// ### Creating a DatabaseSnapshot -/// -/// - ``makeSnapshot()`` -/// /// ### Accessing the Database /// /// See ``DatabaseReader`` and ``DatabaseWriter`` for more database @@ -58,6 +54,16 @@ import UIKit /// - ``asyncConcurrentRead(_:)`` /// - ``writeInTransaction(_:_:)`` /// +/// ### Creating and Reading WAL Snapshots +/// +/// - ``makeSnapshot()`` +/// - ``currentSnapshotToken()`` +/// - ``read(from:_:)-7wtr2`` +/// - ``read(from:_:)-8bwfe`` +/// - ``readPublisher(from:receiveOn:value:)`` +/// - ``asyncRead(from:_:)`` +/// - ``WALSnapshotToken`` +/// /// ### Managing SQLite Connections /// /// - ``invalidateReadOnlyConnections()`` @@ -851,9 +857,10 @@ extension DatabasePool { /// the transaction: /// /// ```swift + /// let snapshot = try dbPool.makeSnapshot() // OK + /// /// try dbPool.writeWithoutTransaction { db in - /// // OK - /// let snapshot = try dbPool.makeSnapshot() + /// let snapshot = try dbPool.makeSnapshot() // OK /// /// try db.inTransaction { /// try Player.deleteAll() @@ -861,8 +868,10 @@ extension DatabasePool { /// } /// /// // OK - /// let snapshot = try dbPool.makeSnapshot() + /// let snapshot = try dbPool.makeSnapshot() // OK /// } + /// + /// let snapshot = try dbPool.makeSnapshot() // OK /// ``` public func makeSnapshot() throws -> DatabaseSnapshot { // Sanity check diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index 9acaae267..eed828e97 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -36,6 +36,26 @@ struct DatabaseSchemaCache { schemaInfo = nil } + func union(_ other: DatabaseSchemaCache) -> DatabaseSchemaCache { + let mergedSchemaInfo: SchemaInfo? + switch (schemaInfo, other.schemaInfo) { + case (nil, nil): + mergedSchemaInfo = nil + case let (nil, info?), let (info?, nil): + mergedSchemaInfo = info + case let (lhs?, rhs?): + mergedSchemaInfo = lhs.union(rhs) + } + + return DatabaseSchemaCache( + schemaInfo: mergedSchemaInfo, + tables: tables.merging(other.tables) { (current, _) in current }, + primaryKeys: primaryKeys.merging(other.primaryKeys) { (current, _) in current }, + columns: columns.merging(other.columns) { (current, _) in current }, + indexes: indexes.merging(other.indexes) { (current, _) in current }, + foreignKeys: foreignKeys.merging(other.foreignKeys) { (current, _) in current }) + } + func table(_ table: String) -> Presence? { tables[table] } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 3a9e66efa..9dfb2250c 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -33,8 +33,8 @@ import Dispatch /// } /// ``` /// -/// When you want to control the database state seen by a snapshot, -/// create the snapshot from within a write access, outside of any transaction. +/// When you want to control the database state seen by a snapshot, create the +/// snapshot from within a write access, outside of any transaction. /// /// For example, compare the two snapshots below. The first one is guaranteed to /// see an empty table of players, because is is created after all players have @@ -65,6 +65,9 @@ import Dispatch /// /// `DatabaseSnapshot` inherits its database access methods from the /// ``DatabaseReader`` protocols. +/// +/// `DatabaseSnapshot` serializes database accesses and can't perform concurrent +/// reads. For concurrent reads, see ``WALSnapshotToken``. public final class DatabaseSnapshot { private let reader: SerializedDatabase diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index 6ee1ddaf6..c3a7b1dcc 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -26,6 +26,7 @@ final class WALSnapshot { // // We can't provide snapshots api for SQLCipher, since we'd have linker // errors if they are not enabled. + // swiftlint:disable:next line_length #if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) static let available = false @@ -69,5 +70,7 @@ final class WALSnapshot { func compare(_ other: WALSnapshot) -> CInt { return sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot) } + + // swiftlint:disable:next line_length #endif // (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) } diff --git a/GRDB/Core/WALSnapshotToken.swift b/GRDB/Core/WALSnapshotToken.swift new file mode 100644 index 000000000..f72782125 --- /dev/null +++ b/GRDB/Core/WALSnapshotToken.swift @@ -0,0 +1,327 @@ +// swiftlint:disable:next line_length +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + +#if canImport(Combine) +import Combine +import Dispatch +#endif + +/// A token that indicates which WAL snapshot is being accessed. +/// +/// ## Overview +/// +/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) +/// +/// All database accesses performed from a `WALSnapshotToken` see the database +/// content as it existed at the moment the token was created. +/// +/// ## Usage +/// +/// You create a `WALSnapshotToken` from a ``DatabasePool``, +/// with ``DatabasePool/currentSnapshotToken()``: +/// +/// ```swift +/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") +/// let token = try dbPool.currentSnapshotToken() +/// let playerCount = try dbPool.read(from: token) { db in +/// try Player.fetchCount(db) +/// } +/// ``` +/// +/// When you want to control the database state seen by a token, create the +/// token from within a write access, outside of any transaction. +/// +/// For example, compare the two tokens below. The first one is guaranteed to +/// see an empty table of players, because is is created after all players have +/// been deleted, and from the serialized writer dispatch queue which prevents +/// any concurrent write. The second is created without this concurrency +/// protection, which means that some other threads may already have created +/// some players: +/// +/// ```swift +/// let token1 = try dbPool.writeWithoutTransaction { db -> WALSnapshotToken in +/// try db.inTransaction { +/// try Player.deleteAll() +/// return .commit +/// } +/// +/// return dbPool.currentSnapshotToken() +/// } +/// +/// // <- Other threads may have created some players here +/// let token2 = try dbPool.currentSnapshotToken() +/// +/// // Guaranteed to be zero +/// let count1 = try dbPool.read(from: token1, Player.fetchCount) +/// +/// // Could be anything +/// let count2 = try dbPool.read(from: token2, Player.fetchCount) +/// ``` +/// +/// - +/// - +public struct WALSnapshotToken { + let walSnapshot: WALSnapshot + + /// The connection that holds a transaction and prevents checkpointing in + /// order to keep `walSnapshot` valid. + let snapshot: DatabaseSnapshot + + let schemaVersion: Int32 + + // Protected by a lock because a token can be used in multiple + // database connections. + @LockedBox var schemaCache: Database.SchemaCache +} + +extension DatabaseSnapshot { + func currentSnapshotToken() throws -> WALSnapshotToken { + try unsafeReentrantRead { db in + let walSnapshot = try WALSnapshot(db) + let schemaVersion = try db.schemaVersion() + return WALSnapshotToken( + walSnapshot: walSnapshot, + snapshot: self, + schemaVersion: schemaVersion, + schemaCache: db.schemaCache) + } + } +} + +extension DatabasePool { + /// Returns a token associated with the WAL snapshot of the current state of + /// the database. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// The returned token makes it possible to see the database content as it + /// existed at the moment the token was created. + /// + /// It is a programmer error to get a WAL snapshot token from the writer + /// dispatch queue when a transaction is opened: + /// + /// ```swift + /// try dbPool.write { db in + /// try Player.deleteAll() + /// + /// // fatal error: currentSnapshotToken() must not be called from inside a transaction + /// let token = try dbPool.currentSnapshotToken() + /// } + /// ``` + /// + /// To avoid this fatal error, create the token *before* or *after* + /// the transaction: + /// + /// ```swift + /// let token = try dbPool.currentSnapshotToken() // OK + /// + /// try dbPool.writeWithoutTransaction { db in + /// let token = try dbPool.currentSnapshotToken() // OK + /// + /// try db.inTransaction { + /// try Player.deleteAll() + /// return .commit + /// } + /// + /// let token = try dbPool.currentSnapshotToken() // OK + /// } + /// + /// let token = try dbPool.currentSnapshotToken() // OK + /// ``` + public func currentSnapshotToken() throws -> WALSnapshotToken { + try makeSnapshot().currentSnapshotToken() + } + + /// Executes read-only database operations from the given WAL snapshot, and + /// returns their result after they have finished executing. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// For example: + /// + /// ```swift + /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") + /// let token = try dbPool.currentSnapshotToken() + /// let count = try reader.read(from: token) { db in + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations see the database content as it existed at the moment + /// the token was created. + /// + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. + /// + /// It is a programmer error to call this method from another database + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. + /// + /// - parameter value: A closure which accesses the database. + /// - throws: The error thrown by `value`, or any ``DatabaseError`` that + /// would happen while establishing the database access. + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails + public func read(from token: WALSnapshotToken, _ value: (Database) throws -> T) throws -> T { + try read { db in + try db.read(from: token) { + try value(db) + } + } + } + + /// Executes read-only database operations from the given WAL snapshot, and + /// returns their result after they have finished executing. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// For example: + /// + /// ```swift + /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") + /// let token = try dbPool.currentSnapshotToken() + /// let count = try await reader.read(from: token) { db in + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations see the database content as it existed at the moment + /// the token was created. + /// + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. + /// + /// - parameter value: A closure which accesses the database. + /// - throws: The error thrown by `value`, or any ``DatabaseError`` that + /// would happen while establishing the database access. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func read( + from token: WALSnapshotToken, + _ value: @Sendable @escaping (Database) throws -> T) + async throws -> T + { + try await read { db in + try db.read(from: token) { + try value(db) + } + } + } + + /// Schedules read-only database operations for execution, from the given + /// WAL snapshot, and returns immediately. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// For example: + /// + /// ```swift + /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") + /// let token = try dbPool.currentSnapshotToken() + /// try reader.asyncRead(from: token) { dbResult in + /// do { + /// let db = try dbResult.get() + /// let count = try Player.fetchCount(db) + /// } catch { + /// // Handle error + /// } + /// } + /// ``` + /// + /// Database operations see the database content as it existed at the moment + /// the token was created. + /// + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. + /// + /// - parameter value: A closure which accesses the database. Its argument + /// is a `Result` that provides the database connection, or the failure + /// that would prevent establishing the read access to the database. + public func asyncRead(from token: WALSnapshotToken, _ value: @escaping (Result) -> Void) { + asyncRead { dbResult in + do { + let db = try dbResult.get() + try db.read(from: token) { + value(.success(db)) + } + } catch { + value(.failure(error)) + } + } + } + +#if canImport(Combine) + /// Returns a publisher that publishes one value fetched from the given WAL + /// snapshot, and completes. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// The database is not accessed until subscription. Value and completion + /// are published on `scheduler` (the main dispatch queue by default). + /// + /// For example: + /// + /// ```swift + /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") + /// let token = try dbPool.currentSnapshotToken() + /// let countPublisher = reader.readPublisher(from: token) { db in + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations are isolated in a transaction: they do not see + /// changes performed by eventual concurrent writes (even writes performed + /// by other processes). + /// + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. + /// + /// - parameter scheduler: A Combine Scheduler. + /// - parameter value: A closure which accesses the database. + @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func readPublisher( + from token: WALSnapshotToken, + receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, + value: @escaping (Database) throws -> Output) + -> DatabasePublishers.Read + { + readPublisher(receiveOn: scheduler) { db in + try db.read(from: token) { + try value(db) + } + } + } +#endif +} + +extension Database { + fileprivate func open(_ token: WALSnapshotToken) throws { + let code = sqlite3_snapshot_open(sqliteConnection, "main", token.walSnapshot.sqliteSnapshot) + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code) + } + lastSchemaVersion = token.schemaVersion + schemaCache = token.schemaCache + } + + fileprivate func read(from token: WALSnapshotToken, _ value: () throws -> T) throws -> T { + try open(token) + defer { + token.$schemaCache.update { $0.formUnion(schemaCache) } + } + + return try value() + } +} +#endif diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index c187cff9d..de824bb0e 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -62,6 +62,7 @@ But you should prefer wrapping your schema changes in when you - ``Database/isGRDBInternalTable(_:)`` - ``Database/isSQLiteInternalTable(_:)`` - ``Database/primaryKey(_:)`` +- ``Database/schemaVersion()`` - ``Database/table(_:hasUniqueKey:)`` - ``Database/tableExists(_:)`` - ``Database/triggerExists(_:)`` diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index ffef388ad..b1f4dd214 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -199,6 +199,8 @@ 56894F332604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; }; 56894FE3260658A400268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; }; 56894FF2260658E600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */; }; + 568EB71C2921232200E59445 /* WALSnapshotToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71A2921232200E59445 /* WALSnapshotToken.swift */; }; + 568EB7202921235E00E59445 /* WALSnapshotTokenTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71F2921235E00E59445 /* WALSnapshotTokenTests.swift */; }; 568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB0C25D904CA00B71526 /* SQLSelection.swift */; }; 568ECB3525D91CEF00B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */; }; 5690C3291D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; }; @@ -639,6 +641,8 @@ 56894F322604FC1E00268F4D /* Table.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = ""; }; 56894FA0260657F600268F4D /* Decimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = ""; }; 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; }; + 568EB71A2921232200E59445 /* WALSnapshotToken.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotToken.swift; sourceTree = ""; }; + 568EB71F2921235E00E59445 /* WALSnapshotTokenTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTokenTests.swift; sourceTree = ""; }; 568ECB0C25D904CA00B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = ""; }; 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; @@ -1352,6 +1356,7 @@ 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, + 568EB71F2921235E00E59445 /* WALSnapshotTokenTests.swift */, ); name = Core; sourceTree = ""; @@ -1451,6 +1456,7 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 56564F3828637C9900A19E9F /* WALSnapshot.swift */, + 568EB71A2921232200E59445 /* WALSnapshotToken.swift */, 5605F1471C672E4000235C62 /* Support */, ); path = Core; @@ -1861,6 +1867,7 @@ F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */, 56C0539322ACEECD0029D27D /* Fetch.swift in Sources */, 56E9FAC42210468500C703A8 /* SQLInterpolation.swift in Sources */, + 568EB71C2921232200E59445 /* WALSnapshotToken.swift in Sources */, 563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */, F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */, 569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */, @@ -2080,6 +2087,7 @@ F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, 5691D96F27256C490021D540 /* AvailableElements.swift in Sources */, 56419C7F24A51D6E004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */, + 568EB7202921235E00E59445 /* WALSnapshotTokenTests.swift in Sources */, 56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */, F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */, 5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index 874c57a6d..6730a8984 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -2,12 +2,9 @@ import XCTest @testable import GRDB class DatabaseSnapshotTests: GRDBTestCase { - - /// A helper class - private class Counter { - let dbPool: DatabasePool + /// A helper type + private struct Counter { init(dbPool: DatabasePool) throws { - self.dbPool = dbPool try dbPool.write { db in try db.execute(sql: "CREATE TABLE counter(id INTEGER PRIMARY KEY)") } diff --git a/Tests/GRDBTests/WALSnapshotTokenTests.swift b/Tests/GRDBTests/WALSnapshotTokenTests.swift new file mode 100644 index 000000000..0fd0dcbd4 --- /dev/null +++ b/Tests/GRDBTests/WALSnapshotTokenTests.swift @@ -0,0 +1,163 @@ +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else +import XCTest +import GRDB + +// test create from non-wal (read-only) snapshot +final class WALSnapshotTokenTests: GRDBTestCase { + /// A helper type + private struct Counter { + init(dbPool: DatabasePool) throws { + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE counter(id INTEGER PRIMARY KEY)") + } + } + + func increment(_ db: Database) throws { + try db.execute(sql: "INSERT INTO counter DEFAULT VALUES") + } + + func value(_ db: Database) throws -> Int { + try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM counter")! + } + } + + func testWALSnapshotTokenCreationFromNewDatabase() throws { + _ = try makeDatabasePool().currentSnapshotToken() + } + + func testWALSnapshotTokenCreationFromNonWALDatabase() throws { + let dbQueue = try makeDatabaseQueue() + + var config = Configuration() + config.readonly = true + let dbPool = try DatabasePool(path: dbQueue.path, configuration: config) + + do { + _ = try dbPool.currentSnapshotToken() + XCTFail("Expected error") + } catch DatabaseError.SQLITE_ERROR { } + } + + func testWALSnapshotToken() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + + try dbPool.write(counter.increment) + let token = try dbPool.currentSnapshotToken() + try dbPool.write(counter.increment) + + try XCTAssertEqual(dbPool.read(counter.value), 2) + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + // Reuse the last connection + try XCTAssertEqual(dbPool.read(counter.value), 2) + } + + func testPassiveCheckpointDoesNotInvalidateWALSnapshotToken() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + try dbPool.write(counter.increment) + let token = try dbPool.currentSnapshotToken() + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.passive) } // ignore if error or not, that's not the point + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try dbPool.write(counter.increment) + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + } + + func testFullCheckpointDoesNotInvalidateWALSnapshotToken() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + try dbPool.write(counter.increment) + let token = try dbPool.currentSnapshotToken() + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.full) } // ignore if error or not, that's not the point + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try dbPool.write(counter.increment) + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + } + + func testRestartCheckpointDoesNotInvalidateWALSnapshotToken() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + try dbPool.write(counter.increment) + let token = try dbPool.currentSnapshotToken() + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.restart) } // ignore if error or not, that's not the point + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try dbPool.write(counter.increment) + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + } + + func testTruncateCheckpointDoesNotInvalidateWALSnapshotToken() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + try dbPool.write(counter.increment) + let token = try dbPool.currentSnapshotToken() + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.truncate) } // ignore if error or not, that's not the point + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try dbPool.write(counter.increment) + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + } + + func testWALSnapshotTokenAndSchemaCache() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: """ + CREATE TABLE player(id INTEGER PRIMARY KEY, name, score); + """) + } + + let token = try dbPool.currentSnapshotToken() + + try dbPool.write { db in + try db.execute(sql: """ + CREATE TABLE team(id INTEGER PRIMARY KEY, name, color); + """) + } + + do { + let exists = try dbPool.read { try $0.tableExists("team") } + XCTAssertTrue(exists) + } + + do { + let exists = try dbPool.read(from: token) { try $0.tableExists("team") } + XCTAssertFalse(exists) + } + + do { + let exists = try dbPool.read { try $0.tableExists("team") } + XCTAssertTrue(exists) + } + } + + func testWALSnapshotTokenAndStatementCache() throws { + let dbPool = try makeDatabasePool() + let request = SQLRequest(sql: "SELECT COUNT(*) FROM player", cached: true) + try dbPool.write { db in + try db.execute(sql: """ + CREATE TABLE player(id INTEGER PRIMARY KEY, name, score); + """) + } + + let token = try dbPool.currentSnapshotToken() + + try dbPool.write { db in + try db.execute(sql: "DROP TABLE player") + } + + do { + let count = try dbPool.read(from: token) { try request.fetchOne($0) } + XCTAssertEqual(count, 0) + } + + do { + _ = try dbPool.read { try request.fetchOne($0) } + XCTFail("Expected error") + } catch DatabaseError.SQLITE_ERROR { } + + do { + let count = try dbPool.read(from: token) { try request.fetchOne($0) } + XCTAssertEqual(count, 0) + } + } +} +#endif From 4b217042587d58f9a6cd138ed41f545795d4ae4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 13 Nov 2022 18:35:59 +0100 Subject: [PATCH 14/69] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cacdbced4..9e15ce28a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -107,6 +107,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: `DatabaseReader.configuration.maximumReaderCount` returns the effective capacity for concurrent reads, so that application code can adapt when needed. - **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime. - **New**: `Database.registerAccess(to:)` has `ValueObservation` track a region. This helps building optimized observations of a constant database region with `ValueObservation.trackingConstantRegion(_:)`. +- **New**: [#1293](https://github.com/groue/GRDB.swift/pull/1293) by [@groue](https://github.com/groue): Enable concurrent reads from a WAL snapshot; ## 6.3.1 From 6864e6b2fba8cbe713685c95f2f07385bbbb232f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 14 Nov 2022 08:47:58 +0100 Subject: [PATCH 15/69] Enhance registerAccess(to:) documentation --- GRDB/Core/Database.swift | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 7c0b289a8..30081aeb9 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -67,8 +67,8 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// ### Database Observation /// /// - ``add(transactionObserver:extent:)`` -/// - ``afterNextTransaction(onCommit:onRollback:)`` /// - ``remove(transactionObserver:)`` +/// - ``afterNextTransaction(onCommit:onRollback:)`` /// - ``registerAccess(to:)`` /// /// ### Collations @@ -689,7 +689,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Database Observation - /// Reports the region to ``ValueObservation``. + /// Reports the database region to ``ValueObservation``. /// /// For example: /// @@ -697,24 +697,23 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// let observation = ValueObservation.tracking { db in /// // All changes to the 'player' and 'team' tables /// // will trigger the observation. - /// try db.registerAccess(to: Table("player")) - /// try db.registerAccess(to: Table("team")) + /// try db.registerAccess(to: Player.all()) + /// try db.registerAccess(to: Team.all()) /// } /// ``` /// /// See ``ValueObservation/trackingConstantRegion(_:)`` for some examples - /// of such explicit region tracking. + /// of region reporting. /// - /// This method only has an effect if and only if the ``ValueObservation`` - /// is inferring the observed region from the database access. In the - /// example below, the observation explicitly tracks the `player` table - /// only. All calls to the `registerAccess` method are ignored: + /// This method has no effect on a ``ValueObservation`` created with an + /// explicit list of tracked regions. In the example below, only the + /// `player` table is tracked: /// /// ```swift /// // Observes the 'player' table only - /// let observation = ValueObservation.tracking(region: Table("player")) { db in + /// let observation = ValueObservation.tracking(region: Player.all()) { db in /// // Ignored - /// try db.registerAccess(to: Table("team")) + /// try db.registerAccess(to: Team.all()) /// } /// ``` public func registerAccess(to region: @autoclosure () -> some DatabaseRegionConvertible) throws { From eaf8dc239a9f9ce02515731ad3609460d26429e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Mon, 14 Nov 2022 10:39:48 +0100 Subject: [PATCH 16/69] Simplify WALSnapshotToken creation --- GRDB/Core/DatabasePool.swift | 2 +- GRDB/Core/WALSnapshotToken.swift | 23 ++++++++--------------- 2 files changed, 9 insertions(+), 16 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index b2ccad1a0..7f9378746 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -54,7 +54,7 @@ import UIKit /// - ``asyncConcurrentRead(_:)`` /// - ``writeInTransaction(_:_:)`` /// -/// ### Creating and Reading WAL Snapshots +/// ### Accessing WAL Snapshots /// /// - ``makeSnapshot()`` /// - ``currentSnapshotToken()`` diff --git a/GRDB/Core/WALSnapshotToken.swift b/GRDB/Core/WALSnapshotToken.swift index f72782125..b2e32f92d 100644 --- a/GRDB/Core/WALSnapshotToken.swift +++ b/GRDB/Core/WALSnapshotToken.swift @@ -75,20 +75,6 @@ public struct WALSnapshotToken { @LockedBox var schemaCache: Database.SchemaCache } -extension DatabaseSnapshot { - func currentSnapshotToken() throws -> WALSnapshotToken { - try unsafeReentrantRead { db in - let walSnapshot = try WALSnapshot(db) - let schemaVersion = try db.schemaVersion() - return WALSnapshotToken( - walSnapshot: walSnapshot, - snapshot: self, - schemaVersion: schemaVersion, - schemaCache: db.schemaCache) - } - } -} - extension DatabasePool { /// Returns a token associated with the WAL snapshot of the current state of /// the database. @@ -130,7 +116,14 @@ extension DatabasePool { /// let token = try dbPool.currentSnapshotToken() // OK /// ``` public func currentSnapshotToken() throws -> WALSnapshotToken { - try makeSnapshot().currentSnapshotToken() + let snapshot = try makeSnapshot() + return try snapshot.read { db in + try WALSnapshotToken( + walSnapshot: WALSnapshot(db), + snapshot: snapshot, + schemaVersion: db.schemaVersion(), + schemaCache: db.schemaCache) + } } /// Executes read-only database operations from the given WAL snapshot, and From bcb70855d5e438e1af1b632ad8ccbd70a8aa0e97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Mon, 14 Nov 2022 10:42:09 +0100 Subject: [PATCH 17/69] Enhance WALSnapshotToken documentation --- GRDB/Core/WALSnapshotToken.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GRDB/Core/WALSnapshotToken.swift b/GRDB/Core/WALSnapshotToken.swift index b2e32f92d..a171b2cc1 100644 --- a/GRDB/Core/WALSnapshotToken.swift +++ b/GRDB/Core/WALSnapshotToken.swift @@ -59,6 +59,8 @@ import Dispatch /// let count2 = try dbPool.read(from: token2, Player.fetchCount) /// ``` /// +/// Related SQLite documentation: +/// /// - /// - public struct WALSnapshotToken { From b8bc8273a9ebc6fbb696c413e8e803addba6d625 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Mon, 14 Nov 2022 13:51:22 +0100 Subject: [PATCH 18/69] Turn snapshot tokens into a proper reader: DatabaseSnapshotPool --- GRDB.xcodeproj/project.pbxproj | 16 +- GRDB/Core/DatabasePool.swift | 12 +- GRDB/Core/DatabaseReader.swift | 16 +- GRDB/Core/DatabaseSnapshot.swift | 26 +- GRDB/Core/DatabaseSnapshotPool.swift | 253 ++++++++++++++ GRDB/Core/WALSnapshot.swift | 2 +- GRDB/Core/WALSnapshotToken.swift | 322 ------------------ .../Documentation.docc/DatabaseConnections.md | 1 + GRDB/Utils/LockedBox.swift | 2 + GRDBCustom.xcodeproj/project.pbxproj | 16 +- ....swift => DatabaseSnapshotPoolTests.swift} | 62 ++-- 11 files changed, 329 insertions(+), 399 deletions(-) create mode 100644 GRDB/Core/DatabaseSnapshotPool.swift delete mode 100644 GRDB/Core/WALSnapshotToken.swift rename Tests/GRDBTests/{WALSnapshotTokenTests.swift => DatabaseSnapshotPoolTests.swift} (67%) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index a6e0c8ea8..f62751351 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -202,8 +202,8 @@ 56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; }; 56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; }; 568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; }; - 568EB71929211E0800E59445 /* WALSnapshotToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71829211E0700E59445 /* WALSnapshotToken.swift */; }; - 568EB71E2921234800E59445 /* WALSnapshotTokenTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71D2921234800E59445 /* WALSnapshotTokenTests.swift */; }; + 568EB71929211E0800E59445 /* DatabaseSnapshotPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */; }; + 568EB71E2921234800E59445 /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */; }; 568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; }; 568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; }; 568ECB1825D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; }; @@ -618,8 +618,8 @@ 56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; }; 56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = ""; }; 568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = ""; }; - 568EB71829211E0700E59445 /* WALSnapshotToken.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotToken.swift; sourceTree = ""; }; - 568EB71D2921234800E59445 /* WALSnapshotTokenTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTokenTests.swift; sourceTree = ""; }; + 568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPool.swift; sourceTree = ""; }; + 568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = ""; }; 568ECA8925D7013000B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = ""; }; 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = ""; }; 568ECB1725D9161500B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = ""; }; @@ -1338,6 +1338,7 @@ 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, + 568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */, 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */, 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */, 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, @@ -1360,7 +1361,6 @@ 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, - 568EB71D2921234800E59445 /* WALSnapshotTokenTests.swift */, ); name = Core; sourceTree = ""; @@ -1443,6 +1443,7 @@ 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 566A84192041146100E50BFD /* DatabaseSnapshot.swift */, + 568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, @@ -1460,7 +1461,6 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 56B7EE822863781300C0525F /* WALSnapshot.swift */, - 568EB71829211E0700E59445 /* WALSnapshotToken.swift */, 5605F1471C672E4000235C62 /* Support */, ); path = Core; @@ -1791,7 +1791,7 @@ 56D496B01D813385008276D7 /* DatabaseErrorTests.swift in Sources */, 56176C5C1EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */, 562206061E420EA4005860AC /* DatabasePoolBackupTests.swift in Sources */, - 568EB71E2921234800E59445 /* WALSnapshotTokenTests.swift in Sources */, + 568EB71E2921234800E59445 /* DatabaseSnapshotPoolTests.swift in Sources */, 56D496B51D813413008276D7 /* DatabaseCollationTests.swift in Sources */, 563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */, 56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */, @@ -2042,7 +2042,7 @@ 566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 5605F1591C672E4000235C62 /* CGFloat.swift in Sources */, 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, - 568EB71929211E0800E59445 /* WALSnapshotToken.swift in Sources */, + 568EB71929211E0800E59445 /* DatabaseSnapshotPool.swift in Sources */, 5605F1631C672E4000235C62 /* Date.swift in Sources */, 5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */, diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 7f9378746..be8503d6c 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -54,15 +54,10 @@ import UIKit /// - ``asyncConcurrentRead(_:)`` /// - ``writeInTransaction(_:_:)`` /// -/// ### Accessing WAL Snapshots +/// ### Creating Database Snapshots /// /// - ``makeSnapshot()`` -/// - ``currentSnapshotToken()`` -/// - ``read(from:_:)-7wtr2`` -/// - ``read(from:_:)-8bwfe`` -/// - ``readPublisher(from:receiveOn:value:)`` -/// - ``asyncRead(from:_:)`` -/// - ``WALSnapshotToken`` +/// - ``makeSnapshotPool()`` /// /// ### Managing SQLite Connections /// @@ -483,7 +478,6 @@ extension DatabasePool: DatabaseReader { releaseReader() } do { - // The block isolation comes from the DEFERRED transaction. try db.clearSchemaCacheIfNeeded() value(.success(db)) } catch { @@ -836,7 +830,7 @@ extension DatabasePool { // MARK: - Snapshots - /// Creates a database snapshot. + /// Creates an independent database snapshot. /// /// The returned snapshot sees an unchanging database content, as it existed /// at the moment it was created. diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index ae0f3663a..f59fd93ba 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -224,8 +224,8 @@ public protocol DatabaseReader: AnyObject, Sendable { /// access method. Doing so raises a "Database methods are not reentrant" /// fatal error at runtime. /// - /// - warning: Database operations are not wrapped in a transaction. They - /// can see changes performed by concurrent writes or writes performed by + /// - warning: Database operations may not be wrapped in a transaction. They + /// may see changes performed by concurrent writes or writes performed by /// other processes: two identical requests performed by the `value` /// closure may not return the same value. /// - warning: Attempts to write in the database may succeed. @@ -256,8 +256,8 @@ public protocol DatabaseReader: AnyObject, Sendable { /// } /// ``` /// - /// - warning: Database operations are not wrapped in a transaction. They - /// can see changes performed by concurrent writes or writes performed by + /// - warning: Database operations may not be wrapped in a transaction. They + /// may see changes performed by concurrent writes or writes performed by /// other processes: two identical requests performed by the `value` /// closure may not return the same value. /// - warning: Attempts to write in the database may succeed. @@ -293,8 +293,8 @@ public protocol DatabaseReader: AnyObject, Sendable { /// of the closure. Do not store or return the database connection for /// later use. /// - /// - warning: Database operations are not wrapped in a transaction. They - /// can see changes performed by concurrent writes or writes performed by + /// - warning: Database operations may not be wrapped in a transaction. They + /// may see changes performed by concurrent writes or writes performed by /// other processes: two identical requests performed by the `value` /// closure may not return the same value. /// - warning: Attempts to write in the database may succeed. @@ -467,8 +467,8 @@ extension DatabaseReader { /// of the closure. Do not store or return the database connection for /// later use. /// - /// - warning: Database operations are not wrapped in a transaction. They - /// can see changes performed by concurrent writes or writes performed by + /// - warning: Database operations may not be wrapped in a transaction. They + /// may see changes performed by concurrent writes or writes performed by /// other processes: two identical requests performed by the `value` /// closure may not return the same value. /// - warning: Attempts to write in the database may succeed. diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 9dfb2250c..997bb10e5 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -1,23 +1,25 @@ import Dispatch -/// A database connection that sees an unchanging database content, as it -/// existed at the moment it was created. +/// A database connection that serializes accesses to an unchanging +/// database content, as it existed at the moment the snapshot was created. /// /// ## Overview /// -/// A `DatabaseSnapshot` creates one single SQLite connection. All database +/// A `DatabaseSnapshot` never sees any database modification during all its +/// lifetime. All database accesses performed from a snapshot always see the +/// same identical database content. +/// +/// A snapshot creates one single SQLite connection. All database /// accesses are executed in a serial **reader dispatch queue**. The SQLite /// connection is closed when the `DatabaseSnapshot` is deallocated. /// -/// A snapshot never sees any database modification during all its lifetime. All -/// database accesses performed from a snapshot always see the same identical -/// database content. +/// A snapshot created on a [WAL](https://sqlite.org/wal.html) database doesn't +/// prevent database modifications performed by other connections (but it won't +/// see them). Refer to [Isolation In SQLite](https://sqlite.org/isolation.html) +/// for more information. /// -/// In the [WAL mode](https://sqlite.org/wal.html), a snapshot doesn't prevent -/// database modifications performed by other connections (but it won't see -/// them). Refer to [Isolation In SQLite](https://sqlite.org/isolation.html) for -/// more information. Otherwise, a snapshot prevents all writes to the database -/// as long as it exists, due to the +/// On non-WAL databases, a snapshot prevents all database modifications as long +/// as it exists, because of the /// [SHARED lock](https://www.sqlite.org/lockingv3.html) it holds. /// /// ## Usage @@ -67,7 +69,7 @@ import Dispatch /// ``DatabaseReader`` protocols. /// /// `DatabaseSnapshot` serializes database accesses and can't perform concurrent -/// reads. For concurrent reads, see ``WALSnapshotToken``. +/// reads. For concurrent reads, see ``DatabaseSnapshotPool``. public final class DatabaseSnapshot { private let reader: SerializedDatabase diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift new file mode 100644 index 000000000..bf389a2bc --- /dev/null +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -0,0 +1,253 @@ +// swiftlint:disable:next line_length +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + +#if canImport(Combine) +import Combine +import Dispatch +#endif + +/// A database connection that allows concurrent accesses to an unchanging +/// database content, as it existed at the moment the snapshot was created. +/// +/// ## Overview +/// +/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) +/// +/// A `DatabaseSnapshotPool` never sees any database modification during all its +/// lifetime. All database accesses performed from a snapshot always see the +/// same identical database content. +/// +/// A `DatabaseSnapshotPool` instance shares the same pool of reader SQLite +/// connections as a ``DatabasePool``. It requires an SQLite database in the +/// [WAL mode](https://www.sqlite.org/wal.html). +/// +/// ## Usage +/// +/// You create a `DatabaseSnapshotPool` from a ``DatabasePool``, +/// with ``DatabasePool/makeSnapshotPool()``: +/// +/// ```swift +/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") +/// let snapshot = try dbPool.makeSnapshotPool() +/// let playerCount = try snapshot.read { db in +/// try Player.fetchCount(db) +/// } +/// ``` +/// +/// When you want to control the database state seen by a snapshot, create the +/// snapshot from within a write access, outside of any transaction. +/// +/// For example, compare the two snapshots below. The first one is guaranteed to +/// see an empty table of players, because is is created after all players have +/// been deleted, and from the serialized writer dispatch queue which prevents +/// any concurrent write. The second is created without this concurrency +/// protection, which means that some other threads may already have created +/// some players: +/// +/// ```swift +/// let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in +/// try db.inTransaction { +/// try Player.deleteAll() +/// return .commit +/// } +/// +/// return dbPool.makeSnapshotPool() +/// } +/// +/// // <- Other threads may have created some players here +/// let snapshot2 = try dbPool.makeSnapshotPool() +/// +/// // Guaranteed to be zero +/// let count1 = try snapshot1.read(Player.fetchCount) +/// +/// // Could be anything +/// let count2 = try snapshot2.read(Player.fetchCount) +/// ``` +/// +/// `DatabaseSnapshotPool` inherits its database access methods from the +/// ``DatabaseReader`` protocols. +/// +/// Related SQLite documentation: +/// +/// - +/// - +public final class DatabaseSnapshotPool { + /// The DatabasePool that provides reader connections. + let dbPool: DatabasePool + + /// The connection that holds a transaction and prevents checkpointing in + /// order to keep `walSnapshot` valid. + let dbSnapshot: DatabaseSnapshot + + /// The WAL snapshot + let walSnapshot: WALSnapshot + + /// The version of the schema cache. + let schemaVersion: Int32 + + // Protected by a lock because the cache can be used by multiple + // database connections. + @LockedBox var schemaCache: Database.SchemaCache + + init( + dbPool: DatabasePool, + dbSnapshot: DatabaseSnapshot, + walSnapshot: WALSnapshot, + schemaVersion: Int32, + schemaCache: Database.SchemaCache) + { + self.dbPool = dbPool + self.dbSnapshot = dbSnapshot + self.walSnapshot = walSnapshot + self.schemaVersion = schemaVersion + self.schemaCache = schemaCache + } +} + +extension DatabaseSnapshotPool: @unchecked Sendable { } + +extension DatabaseSnapshotPool: DatabaseReader { + public var configuration: Configuration { + DatabasePool.readerConfiguration(dbPool.configuration) + } + + /// Throws a ``DatabaseError`` of code `SQLITE_MISUSE`. Close the source + /// ``DatabasePool`` instead. + public func close() throws { + throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "") + } + + public func interrupt() { + dbPool.interrupt() + } + + public func read(_ value: (Database) throws -> T) throws -> T { + try dbPool.read { db in + try db.read(from: self) { + try value(db) + } + } + } + + public func unsafeRead(_ value: (Database) throws -> T) throws -> T { + /// There is no unsafe access to a snapshot. + try read(value) + } + + public func asyncRead(_ value: @escaping (Result) -> Void) { + dbPool.asyncRead { dbResult in + do { + let db = try dbResult.get() + try db.read(from: self) { + value(.success(db)) + } + } catch { + value(.failure(error)) + } + } + } + + public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + /// There is no unsafe access to a snapshot. + dbPool.asyncRead(value) + } + + public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { + try dbPool.unsafeReentrantRead { db in + try db.isolated { + try db.read(from: self) { + try value(db) + } + } + } + } + + public func _add( + observation: ValueObservation, + scheduling scheduler: ValueObservationScheduler, + onChange: @escaping (Reducer.Value) -> Void) + -> AnyDatabaseCancellable where Reducer: ValueReducer + { + _addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange) + } +} + +extension DatabasePool { + /// Creates a database snapshot that uses the reader connections of + /// the pool. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// The returned snapshot sees an unchanging database content, as it existed + /// at the moment it was created. It shares the same reader SQLite + /// connections as the `DatabasePool`. + /// + /// An error is thrown unless the SQLite database is in the + /// [WAL mode](https://www.sqlite.org/wal.html). + /// + /// It is a programmer error to create a snapshot from the writer dispatch + /// queue when a transaction is opened: + /// + /// ```swift + /// try dbPool.write { db in + /// try Player.deleteAll() + /// + /// // fatal error: makeSnapshot() must not be called from inside a transaction + /// let snapshot = try dbPool.makeSnapshot() + /// } + /// ``` + /// + /// To avoid this fatal error, create the snapshot *before* or *after* + /// the transaction: + /// + /// ```swift + /// let snapshot = try dbPool.makeSnapshot() // OK + /// + /// try dbPool.writeWithoutTransaction { db in + /// let snapshot = try dbPool.makeSnapshot() // OK + /// + /// try db.inTransaction { + /// try Player.deleteAll() + /// return .commit + /// } + /// + /// // OK + /// let snapshot = try dbPool.makeSnapshot() // OK + /// } + /// + /// let snapshot = try dbPool.makeSnapshot() // OK + /// ``` + public func makeSnapshotPool() throws -> DatabaseSnapshotPool { + let dbSnapshot = try makeSnapshot() + return try dbSnapshot.read { db in + try DatabaseSnapshotPool( + dbPool: self, + dbSnapshot: dbSnapshot, + walSnapshot: WALSnapshot(db), + schemaVersion: db.schemaVersion(), + schemaCache: db.schemaCache) + } + } +} + +extension Database { + fileprivate func open(_ snapshot: DatabaseSnapshotPool) throws { + let code = sqlite3_snapshot_open(sqliteConnection, "main", snapshot.walSnapshot.sqliteSnapshot) + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code) + } + lastSchemaVersion = snapshot.schemaVersion + schemaCache = snapshot.schemaCache + } + + fileprivate func read(from snapshot: DatabaseSnapshotPool, _ value: () throws -> T) throws -> T { + try open(snapshot) + defer { + snapshot.$schemaCache.update { $0.formUnion(schemaCache) } + } + + return try value() + } +} +#endif diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index c3a7b1dcc..6ec2d7e48 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -19,7 +19,7 @@ /// Yes, this is an awfully complex logic. /// /// See . -final class WALSnapshot { +final class WALSnapshot: Sendable { // Xcode 14 ships with a macOS SDK that misses snapshot support. // Xcode 14.1 ships with a macOS SDK that has snapshot support. // This is the meaning of (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) diff --git a/GRDB/Core/WALSnapshotToken.swift b/GRDB/Core/WALSnapshotToken.swift deleted file mode 100644 index a171b2cc1..000000000 --- a/GRDB/Core/WALSnapshotToken.swift +++ /dev/null @@ -1,322 +0,0 @@ -// swiftlint:disable:next line_length -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else - -#if canImport(Combine) -import Combine -import Dispatch -#endif - -/// A token that indicates which WAL snapshot is being accessed. -/// -/// ## Overview -/// -/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) -/// -/// All database accesses performed from a `WALSnapshotToken` see the database -/// content as it existed at the moment the token was created. -/// -/// ## Usage -/// -/// You create a `WALSnapshotToken` from a ``DatabasePool``, -/// with ``DatabasePool/currentSnapshotToken()``: -/// -/// ```swift -/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") -/// let token = try dbPool.currentSnapshotToken() -/// let playerCount = try dbPool.read(from: token) { db in -/// try Player.fetchCount(db) -/// } -/// ``` -/// -/// When you want to control the database state seen by a token, create the -/// token from within a write access, outside of any transaction. -/// -/// For example, compare the two tokens below. The first one is guaranteed to -/// see an empty table of players, because is is created after all players have -/// been deleted, and from the serialized writer dispatch queue which prevents -/// any concurrent write. The second is created without this concurrency -/// protection, which means that some other threads may already have created -/// some players: -/// -/// ```swift -/// let token1 = try dbPool.writeWithoutTransaction { db -> WALSnapshotToken in -/// try db.inTransaction { -/// try Player.deleteAll() -/// return .commit -/// } -/// -/// return dbPool.currentSnapshotToken() -/// } -/// -/// // <- Other threads may have created some players here -/// let token2 = try dbPool.currentSnapshotToken() -/// -/// // Guaranteed to be zero -/// let count1 = try dbPool.read(from: token1, Player.fetchCount) -/// -/// // Could be anything -/// let count2 = try dbPool.read(from: token2, Player.fetchCount) -/// ``` -/// -/// Related SQLite documentation: -/// -/// - -/// - -public struct WALSnapshotToken { - let walSnapshot: WALSnapshot - - /// The connection that holds a transaction and prevents checkpointing in - /// order to keep `walSnapshot` valid. - let snapshot: DatabaseSnapshot - - let schemaVersion: Int32 - - // Protected by a lock because a token can be used in multiple - // database connections. - @LockedBox var schemaCache: Database.SchemaCache -} - -extension DatabasePool { - /// Returns a token associated with the WAL snapshot of the current state of - /// the database. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// The returned token makes it possible to see the database content as it - /// existed at the moment the token was created. - /// - /// It is a programmer error to get a WAL snapshot token from the writer - /// dispatch queue when a transaction is opened: - /// - /// ```swift - /// try dbPool.write { db in - /// try Player.deleteAll() - /// - /// // fatal error: currentSnapshotToken() must not be called from inside a transaction - /// let token = try dbPool.currentSnapshotToken() - /// } - /// ``` - /// - /// To avoid this fatal error, create the token *before* or *after* - /// the transaction: - /// - /// ```swift - /// let token = try dbPool.currentSnapshotToken() // OK - /// - /// try dbPool.writeWithoutTransaction { db in - /// let token = try dbPool.currentSnapshotToken() // OK - /// - /// try db.inTransaction { - /// try Player.deleteAll() - /// return .commit - /// } - /// - /// let token = try dbPool.currentSnapshotToken() // OK - /// } - /// - /// let token = try dbPool.currentSnapshotToken() // OK - /// ``` - public func currentSnapshotToken() throws -> WALSnapshotToken { - let snapshot = try makeSnapshot() - return try snapshot.read { db in - try WALSnapshotToken( - walSnapshot: WALSnapshot(db), - snapshot: snapshot, - schemaVersion: db.schemaVersion(), - schemaCache: db.schemaCache) - } - } - - /// Executes read-only database operations from the given WAL snapshot, and - /// returns their result after they have finished executing. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// For example: - /// - /// ```swift - /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") - /// let token = try dbPool.currentSnapshotToken() - /// let count = try reader.read(from: token) { db in - /// try Player.fetchCount(db) - /// } - /// ``` - /// - /// Database operations see the database content as it existed at the moment - /// the token was created. - /// - /// The database connection is read-only: attempts to write throw a - /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. - /// - /// The ``Database`` argument to `value` is valid only during the execution - /// of the closure. Do not store or return the database connection for - /// later use. - /// - /// It is a programmer error to call this method from another database - /// access method. Doing so raises a "Database methods are not reentrant" - /// fatal error at runtime. - /// - /// - parameter value: A closure which accesses the database. - /// - throws: The error thrown by `value`, or any ``DatabaseError`` that - /// would happen while establishing the database access. - @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func read(from token: WALSnapshotToken, _ value: (Database) throws -> T) throws -> T { - try read { db in - try db.read(from: token) { - try value(db) - } - } - } - - /// Executes read-only database operations from the given WAL snapshot, and - /// returns their result after they have finished executing. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// For example: - /// - /// ```swift - /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") - /// let token = try dbPool.currentSnapshotToken() - /// let count = try await reader.read(from: token) { db in - /// try Player.fetchCount(db) - /// } - /// ``` - /// - /// Database operations see the database content as it existed at the moment - /// the token was created. - /// - /// The database connection is read-only: attempts to write throw a - /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. - /// - /// The ``Database`` argument to `value` is valid only during the execution - /// of the closure. Do not store or return the database connection for - /// later use. - /// - /// - parameter value: A closure which accesses the database. - /// - throws: The error thrown by `value`, or any ``DatabaseError`` that - /// would happen while establishing the database access. - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func read( - from token: WALSnapshotToken, - _ value: @Sendable @escaping (Database) throws -> T) - async throws -> T - { - try await read { db in - try db.read(from: token) { - try value(db) - } - } - } - - /// Schedules read-only database operations for execution, from the given - /// WAL snapshot, and returns immediately. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// For example: - /// - /// ```swift - /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") - /// let token = try dbPool.currentSnapshotToken() - /// try reader.asyncRead(from: token) { dbResult in - /// do { - /// let db = try dbResult.get() - /// let count = try Player.fetchCount(db) - /// } catch { - /// // Handle error - /// } - /// } - /// ``` - /// - /// Database operations see the database content as it existed at the moment - /// the token was created. - /// - /// The database connection is read-only: attempts to write throw a - /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. - /// - /// - parameter value: A closure which accesses the database. Its argument - /// is a `Result` that provides the database connection, or the failure - /// that would prevent establishing the read access to the database. - public func asyncRead(from token: WALSnapshotToken, _ value: @escaping (Result) -> Void) { - asyncRead { dbResult in - do { - let db = try dbResult.get() - try db.read(from: token) { - value(.success(db)) - } - } catch { - value(.failure(error)) - } - } - } - -#if canImport(Combine) - /// Returns a publisher that publishes one value fetched from the given WAL - /// snapshot, and completes. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// The database is not accessed until subscription. Value and completion - /// are published on `scheduler` (the main dispatch queue by default). - /// - /// For example: - /// - /// ```swift - /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") - /// let token = try dbPool.currentSnapshotToken() - /// let countPublisher = reader.readPublisher(from: token) { db in - /// try Player.fetchCount(db) - /// } - /// ``` - /// - /// Database operations are isolated in a transaction: they do not see - /// changes performed by eventual concurrent writes (even writes performed - /// by other processes). - /// - /// The database connection is read-only: attempts to write throw a - /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. - /// - /// The ``Database`` argument to `value` is valid only during the execution - /// of the closure. Do not store or return the database connection for - /// later use. - /// - /// - parameter scheduler: A Combine Scheduler. - /// - parameter value: A closure which accesses the database. - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func readPublisher( - from token: WALSnapshotToken, - receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, - value: @escaping (Database) throws -> Output) - -> DatabasePublishers.Read - { - readPublisher(receiveOn: scheduler) { db in - try db.read(from: token) { - try value(db) - } - } - } -#endif -} - -extension Database { - fileprivate func open(_ token: WALSnapshotToken) throws { - let code = sqlite3_snapshot_open(sqliteConnection, "main", token.walSnapshot.sqliteSnapshot) - guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code) - } - lastSchemaVersion = token.schemaVersion - schemaCache = token.schemaCache - } - - fileprivate func read(from token: WALSnapshotToken, _ value: () throws -> T) throws -> T { - try open(token) - defer { - token.$schemaCache.update { $0.formUnion(schemaCache) } - } - - return try value() - } -} -#endif diff --git a/GRDB/Documentation.docc/DatabaseConnections.md b/GRDB/Documentation.docc/DatabaseConnections.md index 6e5f61819..0c959f199 100644 --- a/GRDB/Documentation.docc/DatabaseConnections.md +++ b/GRDB/Documentation.docc/DatabaseConnections.md @@ -33,6 +33,7 @@ The differences are: - ``DatabaseQueue`` - ``DatabasePool`` - ``DatabaseSnapshot`` +- ``DatabaseSnapshotPool`` ### Using Database Connections diff --git a/GRDB/Utils/LockedBox.swift b/GRDB/Utils/LockedBox.swift index f9c72785a..79388ae12 100644 --- a/GRDB/Utils/LockedBox.swift +++ b/GRDB/Utils/LockedBox.swift @@ -66,3 +66,5 @@ extension LockedBox where T: Numeric { } } } + +extension LockedBox: @unchecked Sendable where T: Sendable { } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index b1f4dd214..7c3bb40ed 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -199,8 +199,8 @@ 56894F332604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; }; 56894FE3260658A400268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; }; 56894FF2260658E600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */; }; - 568EB71C2921232200E59445 /* WALSnapshotToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71A2921232200E59445 /* WALSnapshotToken.swift */; }; - 568EB7202921235E00E59445 /* WALSnapshotTokenTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71F2921235E00E59445 /* WALSnapshotTokenTests.swift */; }; + 568EB71C2921232200E59445 /* DatabaseSnapshotPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */; }; + 568EB7202921235E00E59445 /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */; }; 568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB0C25D904CA00B71526 /* SQLSelection.swift */; }; 568ECB3525D91CEF00B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */; }; 5690C3291D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; }; @@ -641,8 +641,8 @@ 56894F322604FC1E00268F4D /* Table.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = ""; }; 56894FA0260657F600268F4D /* Decimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = ""; }; 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; }; - 568EB71A2921232200E59445 /* WALSnapshotToken.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotToken.swift; sourceTree = ""; }; - 568EB71F2921235E00E59445 /* WALSnapshotTokenTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTokenTests.swift; sourceTree = ""; }; + 568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPool.swift; sourceTree = ""; }; + 568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = ""; }; 568ECB0C25D904CA00B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = ""; }; 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; @@ -1334,6 +1334,7 @@ 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, + 568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */, 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */, 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */, 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, @@ -1356,7 +1357,6 @@ 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, - 568EB71F2921235E00E59445 /* WALSnapshotTokenTests.swift */, ); name = Core; sourceTree = ""; @@ -1439,6 +1439,7 @@ 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */, + 568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, @@ -1456,7 +1457,6 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 56564F3828637C9900A19E9F /* WALSnapshot.swift */, - 568EB71A2921232200E59445 /* WALSnapshotToken.swift */, 5605F1471C672E4000235C62 /* Support */, ); path = Core; @@ -1867,7 +1867,7 @@ F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */, 56C0539322ACEECD0029D27D /* Fetch.swift in Sources */, 56E9FAC42210468500C703A8 /* SQLInterpolation.swift in Sources */, - 568EB71C2921232200E59445 /* WALSnapshotToken.swift in Sources */, + 568EB71C2921232200E59445 /* DatabaseSnapshotPool.swift in Sources */, 563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */, F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */, 569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */, @@ -2087,7 +2087,7 @@ F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, 5691D96F27256C490021D540 /* AvailableElements.swift in Sources */, 56419C7F24A51D6E004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */, - 568EB7202921235E00E59445 /* WALSnapshotTokenTests.swift in Sources */, + 568EB7202921235E00E59445 /* DatabaseSnapshotPoolTests.swift in Sources */, 56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */, F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */, 5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, diff --git a/Tests/GRDBTests/WALSnapshotTokenTests.swift b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift similarity index 67% rename from Tests/GRDBTests/WALSnapshotTokenTests.swift rename to Tests/GRDBTests/DatabaseSnapshotPoolTests.swift index 0fd0dcbd4..7cea62e75 100644 --- a/Tests/GRDBTests/WALSnapshotTokenTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift @@ -4,7 +4,7 @@ import XCTest import GRDB // test create from non-wal (read-only) snapshot -final class WALSnapshotTokenTests: GRDBTestCase { +final class DatabaseSnapshotPoolTests: GRDBTestCase { /// A helper type private struct Counter { init(dbPool: DatabasePool) throws { @@ -22,11 +22,11 @@ final class WALSnapshotTokenTests: GRDBTestCase { } } - func testWALSnapshotTokenCreationFromNewDatabase() throws { - _ = try makeDatabasePool().currentSnapshotToken() + func testSnapshotPoolCreationFromNewDatabase() throws { + _ = try makeDatabasePool().makeSnapshotPool() } - func testWALSnapshotTokenCreationFromNonWALDatabase() throws { + func testSnapshotPoolCreationFromNonWALDatabase() throws { let dbQueue = try makeDatabaseQueue() var config = Configuration() @@ -34,70 +34,70 @@ final class WALSnapshotTokenTests: GRDBTestCase { let dbPool = try DatabasePool(path: dbQueue.path, configuration: config) do { - _ = try dbPool.currentSnapshotToken() + _ = try dbPool.makeSnapshotPool() XCTFail("Expected error") } catch DatabaseError.SQLITE_ERROR { } } - func testWALSnapshotToken() throws { + func testSnapshotPool() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) - let token = try dbPool.currentSnapshotToken() + let snapshot = try dbPool.makeSnapshotPool() try dbPool.write(counter.increment) try XCTAssertEqual(dbPool.read(counter.value), 2) - try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try XCTAssertEqual(snapshot.read(counter.value), 1) // Reuse the last connection try XCTAssertEqual(dbPool.read(counter.value), 2) } - func testPassiveCheckpointDoesNotInvalidateWALSnapshotToken() throws { + func testPassiveCheckpointDoesNotInvalidateSnapshotPool() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) - let token = try dbPool.currentSnapshotToken() + let snapshot = try dbPool.makeSnapshotPool() try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.passive) } // ignore if error or not, that's not the point - try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try XCTAssertEqual(snapshot.read(counter.value), 1) try dbPool.write(counter.increment) - try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try XCTAssertEqual(snapshot.read(counter.value), 1) } - func testFullCheckpointDoesNotInvalidateWALSnapshotToken() throws { + func testFullCheckpointDoesNotInvalidateSnapshotPool() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) - let token = try dbPool.currentSnapshotToken() + let snapshot = try dbPool.makeSnapshotPool() try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.full) } // ignore if error or not, that's not the point - try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try XCTAssertEqual(snapshot.read(counter.value), 1) try dbPool.write(counter.increment) - try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try XCTAssertEqual(snapshot.read(counter.value), 1) } - func testRestartCheckpointDoesNotInvalidateWALSnapshotToken() throws { + func testRestartCheckpointDoesNotInvalidateSnapshotPool() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) - let token = try dbPool.currentSnapshotToken() + let snapshot = try dbPool.makeSnapshotPool() try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.restart) } // ignore if error or not, that's not the point - try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try XCTAssertEqual(snapshot.read(counter.value), 1) try dbPool.write(counter.increment) - try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try XCTAssertEqual(snapshot.read(counter.value), 1) } - func testTruncateCheckpointDoesNotInvalidateWALSnapshotToken() throws { + func testTruncateCheckpointDoesNotInvalidateSnapshotPool() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) - let token = try dbPool.currentSnapshotToken() + let snapshot = try dbPool.makeSnapshotPool() try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.truncate) } // ignore if error or not, that's not the point - try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try XCTAssertEqual(snapshot.read(counter.value), 1) try dbPool.write(counter.increment) - try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try XCTAssertEqual(snapshot.read(counter.value), 1) } - func testWALSnapshotTokenAndSchemaCache() throws { + func testSnapshotPoolAndSchemaCache() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute(sql: """ @@ -105,7 +105,7 @@ final class WALSnapshotTokenTests: GRDBTestCase { """) } - let token = try dbPool.currentSnapshotToken() + let snapshot = try dbPool.makeSnapshotPool() try dbPool.write { db in try db.execute(sql: """ @@ -119,7 +119,7 @@ final class WALSnapshotTokenTests: GRDBTestCase { } do { - let exists = try dbPool.read(from: token) { try $0.tableExists("team") } + let exists = try snapshot.read { try $0.tableExists("team") } XCTAssertFalse(exists) } @@ -129,7 +129,7 @@ final class WALSnapshotTokenTests: GRDBTestCase { } } - func testWALSnapshotTokenAndStatementCache() throws { + func testSnapshotPoolAndStatementCache() throws { let dbPool = try makeDatabasePool() let request = SQLRequest(sql: "SELECT COUNT(*) FROM player", cached: true) try dbPool.write { db in @@ -138,14 +138,14 @@ final class WALSnapshotTokenTests: GRDBTestCase { """) } - let token = try dbPool.currentSnapshotToken() + let snapshot = try dbPool.makeSnapshotPool() try dbPool.write { db in try db.execute(sql: "DROP TABLE player") } do { - let count = try dbPool.read(from: token) { try request.fetchOne($0) } + let count = try snapshot.read { try request.fetchOne($0) } XCTAssertEqual(count, 0) } @@ -155,7 +155,7 @@ final class WALSnapshotTokenTests: GRDBTestCase { } catch DatabaseError.SQLITE_ERROR { } do { - let count = try dbPool.read(from: token) { try request.fetchOne($0) } + let count = try snapshot.read { try request.fetchOne($0) } XCTAssertEqual(count, 0) } } From c23b93d71b5dd747c206f8e7c7c5d0d5b7ca428c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 14 Nov 2022 18:38:33 +0100 Subject: [PATCH 19/69] Document that reentrant database accesses use the current database connection when possible --- GRDB/Core/DatabasePool.swift | 2 ++ GRDB/Core/DatabaseReader.swift | 8 +++++-- GRDB/Core/DatabaseWriter.swift | 5 ++-- Tests/GRDBTests/DatabaseReaderTests.swift | 29 +++++++++++++++++++++++ 4 files changed, 39 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index be8503d6c..5e3ef69ee 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -493,6 +493,8 @@ extension DatabasePool: DatabaseReader { public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { if let reader = currentReader { return try reader.reentrantSync(value) + } else if writer.onValidQueue { + return try writer.execute(value) } else { guard let readerPool else { throw DatabaseError.connectionIsClosed() diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index f59fd93ba..666753869 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -275,8 +275,12 @@ public protocol DatabaseReader: AnyObject, Sendable { /// become responsible for the thread-safety of your application, and /// responsible for database accesses performed by other processes. /// - /// This method can be called from other database access methods. Reentrant - /// database accesses are discouraged, though, because they muddle + /// This method can be called from other database access methods. If called + /// from the dispatch queue of a current database access (read or write), + /// the `Database` argument to `value` is the same as the current + /// database access. + /// + /// Reentrant database accesses are discouraged because they muddle /// transaction boundaries /// (see for /// more information). diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 927324f24..c628fd372 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -215,9 +215,8 @@ public protocol DatabaseWriter: DatabaseReader { /// finished executing. /// /// This method can be called from other database access methods. Reentrant - /// database accesses are discouraged, though, because they muddle - /// transaction boundaries. - /// (see for + /// database accesses are discouraged because they muddle transaction + /// boundaries. (see for /// more information). /// /// For example: diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index d2935629b..0bfa2fb73 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -28,6 +28,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue())) try test(setup(makeDatabasePool())) try test(setup(makeDatabasePool()).makeSnapshot()) + try test(setup(makeDatabasePool()).makeSnapshotPool()) } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @@ -48,6 +49,7 @@ class DatabaseReaderTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) try await test(setup(makeDatabasePool()).makeSnapshot()) + try await test(setup(makeDatabasePool()).makeSnapshotPool()) } func testReadPreventsDatabaseModification() throws { @@ -64,6 +66,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) + try test(makeDatabasePool().makeSnapshotPool()) } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @@ -81,6 +84,7 @@ class DatabaseReaderTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) try await test(makeDatabasePool().makeSnapshot()) + try await test(makeDatabasePool().makeSnapshotPool()) } // MARK: - UnsafeRead @@ -102,6 +106,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue())) try test(setup(makeDatabasePool())) try test(setup(makeDatabasePool()).makeSnapshot()) + try test(setup(makeDatabasePool()).makeSnapshotPool()) } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @@ -122,6 +127,7 @@ class DatabaseReaderTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) try await test(setup(makeDatabasePool()).makeSnapshot()) + try await test(setup(makeDatabasePool()).makeSnapshotPool()) } // MARK: - UnsafeReentrantRead @@ -143,6 +149,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue())) try test(setup(makeDatabasePool())) try test(setup(makeDatabasePool()).makeSnapshot()) + try test(setup(makeDatabasePool()).makeSnapshotPool()) } func testUnsafeReentrantReadIsReentrant() throws { @@ -160,6 +167,23 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) + try test(makeDatabasePool().makeSnapshotPool()) + } + + func testUnsafeReentrantReadIsReentrantFromWrite() throws { + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db1 in + try dbWriter.unsafeReentrantRead { db2 in + try dbWriter.unsafeReentrantRead { db3 in + XCTAssertTrue(db1 === db2) + XCTAssertTrue(db2 === db3) + } + } + } + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } // MARK: - AsyncRead @@ -188,6 +212,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) + try test(makeDatabasePool().makeSnapshotPool()) } func testAsyncReadPreventsDatabaseModification() throws { @@ -214,6 +239,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) + try test(makeDatabasePool().makeSnapshotPool()) } // MARK: - Function @@ -231,6 +257,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) + try test(makeDatabasePool().makeSnapshotPool()) } // MARK: - Collation @@ -248,6 +275,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) + try test(makeDatabasePool().makeSnapshotPool()) } // MARK: - Backup @@ -272,5 +300,6 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue(configuration: Configuration()))) try test(setup(makeDatabasePool(configuration: Configuration()))) try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshot()) + try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshotPool()) } } From 433ed36a4becb5926b73aa582d89663881ebd786 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 14 Nov 2022 18:51:39 +0100 Subject: [PATCH 20/69] More documentation about transactions --- GRDB/Core/DatabaseReader.swift | 16 ++++++++++++---- GRDB/Core/DatabaseWriter.swift | 24 ++++++++++++++---------- GRDB/Documentation.docc/Concurrency.md | 8 +++----- 3 files changed, 29 insertions(+), 19 deletions(-) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 666753869..ff667252c 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -206,7 +206,9 @@ public protocol DatabaseReader: AnyObject, Sendable { /// This method is "unsafe" because the database reader does nothing more /// than providing a database connection. When you use this method, you /// become responsible for the thread-safety of your application, and - /// responsible for database accesses performed by other processes. + /// responsible for database accesses performed by other processes. See + /// for + /// more information. /// /// For example: /// @@ -241,7 +243,9 @@ public protocol DatabaseReader: AnyObject, Sendable { /// This method is "unsafe" because the database reader does nothing more /// than providing a database connection. When you use this method, you /// become responsible for the thread-safety of your application, and - /// responsible for database accesses performed by other processes. + /// responsible for database accesses performed by other processes. See + /// for + /// more information. /// /// For example: /// @@ -273,7 +277,9 @@ public protocol DatabaseReader: AnyObject, Sendable { /// This method is "unsafe" because the database reader does nothing more /// than providing a database connection. When you use this method, you /// become responsible for the thread-safety of your application, and - /// responsible for database accesses performed by other processes. + /// responsible for database accesses performed by other processes. See + /// for + /// more information. /// /// This method can be called from other database access methods. If called /// from the dispatch queue of a current database access (read or write), @@ -457,7 +463,9 @@ extension DatabaseReader { /// This method is "unsafe" because the database reader does nothing more /// than providing a database connection. When you use this method, you /// become responsible for the thread-safety of your application, and - /// responsible for database accesses performed by other processes. + /// responsible for database accesses performed by other processes. See + /// for + /// more information. /// /// For example: /// diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index c628fd372..6322e7358 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -42,15 +42,15 @@ import Dispatch /// - ``spawnConcurrentRead(_:)`` /// - ``DatabaseFuture`` /// +/// ### Unsafe Methods +/// +/// - ``unsafeReentrantWrite(_:)`` +/// /// ### Observing Database Transactions /// /// - ``add(transactionObserver:extent:)`` /// - ``remove(transactionObserver:)`` /// -/// ### Unsafe Methods -/// -/// - ``unsafeReentrantWrite(_:)`` -/// /// ### Other Database Operations /// /// - ``erase()-w5n7`` @@ -94,7 +94,8 @@ public protocol DatabaseWriter: DatabaseReader { /// can see changes performed by concurrent writes or writes performed by /// other processes: two identical requests performed by the `updates` /// closure may not return the same value. Concurrent database accesses - /// can see partial updates performed by the `updates` closure. + /// can see partial updates performed by the `updates` closure. See + /// for more information. /// /// - parameter updates: A closure which accesses the database. /// - throws: The error thrown by `updates`. @@ -133,7 +134,8 @@ public protocol DatabaseWriter: DatabaseReader { /// can see changes performed by concurrent writes or writes performed by /// other processes: two identical requests performed by the `updates` /// closure may not return the same value. Concurrent database accesses - /// can see partial updates performed by the `updates` closure. + /// can see partial updates performed by the `updates` closure. See + /// for more information. /// /// - parameter updates: A closure which accesses the database. /// - throws: The error thrown by `updates`. @@ -173,7 +175,8 @@ public protocol DatabaseWriter: DatabaseReader { /// can see changes performed by concurrent writes or writes performed by /// other processes: two identical requests performed by the `updates` /// closure may not return the same value. Concurrent database accesses - /// can see partial updates performed by the `updates` closure. + /// can see partial updates performed by the `updates` closure. See + /// for more information. /// /// - parameter updates: A closure which accesses the database. Its argument /// is a `Result` that provides the database connection, or the failure @@ -206,7 +209,8 @@ public protocol DatabaseWriter: DatabaseReader { /// can see changes performed by concurrent writes or writes performed by /// other processes: two identical requests performed by the `updates` /// closure may not return the same value. Concurrent database accesses - /// can see partial updates performed by the `updates` closure. + /// can see partial updates performed by the `updates` closure. See + /// for more information. /// /// - parameter updates: A closure which accesses the database. func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) @@ -216,8 +220,8 @@ public protocol DatabaseWriter: DatabaseReader { /// /// This method can be called from other database access methods. Reentrant /// database accesses are discouraged because they muddle transaction - /// boundaries. (see for - /// more information). + /// boundaries. See for + /// more information. /// /// For example: /// diff --git a/GRDB/Documentation.docc/Concurrency.md b/GRDB/Documentation.docc/Concurrency.md index ec48c0623..fb40d98c4 100644 --- a/GRDB/Documentation.docc/Concurrency.md +++ b/GRDB/Documentation.docc/Concurrency.md @@ -43,13 +43,11 @@ try dbQueue.write { db in try dbQueue.read { db // Inside a transaction } - -let observation = ValueObservation.tracking { db - // Inside a transaction -} ``` -- *Why does this rule exist?* - Because GRDB and SQLite can not guess where to insert the transaction boundaries that protect the invariants of your database. This is your task. +Alternatively, you can open an explicit transaction or savepoint with ``Database/inTransaction(_:_:)`` and ``Database/inSavepoint(_:)``. + +- *Why does this rule exist?* - Because GRDB and SQLite can not guess where to insert the transaction boundaries that protect the invariants of your database. This is your task. Transactions also avoid concurrency problems, as described in the section below. - *Practical advice* - Take the time to identify the invariants of your database. Some of them can be enforced in the database schema itself, such as "all books must have a non-empty title", or "all books must have an author" (see ). Some invariants can only be enforced by transactions, such as "all account credits must have a matching debit", or "all authors must have at least one book". From 9ac8c0703d500dd3eff6f295d696e563799d5ddf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 14 Nov 2022 19:02:10 +0100 Subject: [PATCH 21/69] Remove dead code --- GRDB/Core/DatabaseSnapshotPool.swift | 5 ----- 1 file changed, 5 deletions(-) diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index bf389a2bc..9adeeff77 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -2,11 +2,6 @@ #if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) #else -#if canImport(Combine) -import Combine -import Dispatch -#endif - /// A database connection that allows concurrent accesses to an unchanging /// database content, as it existed at the moment the snapshot was created. /// From c4c0b1ce908cdf83d4c0a82fb6bd217848bed8bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 14 Nov 2022 19:10:52 +0100 Subject: [PATCH 22/69] Test and fix unsafe and async DatabaseSnapshotPool --- GRDB/Core/DatabaseSnapshotPool.swift | 3 +- .../GRDBTests/DatabaseSnapshotPoolTests.swift | 54 ++++++++++++++++++- 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 9adeeff77..d49663d8e 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -117,6 +117,7 @@ extension DatabaseSnapshotPool: DatabaseReader { dbPool.interrupt() } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func read(_ value: (Database) throws -> T) throws -> T { try dbPool.read { db in try db.read(from: self) { @@ -145,7 +146,7 @@ extension DatabaseSnapshotPool: DatabaseReader { public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { /// There is no unsafe access to a snapshot. - dbPool.asyncRead(value) + asyncRead(value) } public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { diff --git a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift index 7cea62e75..12fc35e20 100644 --- a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift @@ -39,7 +39,7 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { } catch DatabaseError.SQLITE_ERROR { } } - func testSnapshotPool() throws { + func testSnapshotPool_read() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) @@ -53,6 +53,58 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { try XCTAssertEqual(dbPool.read(counter.value), 2) } + func testSnapshotPool_unsafeRead() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + + try dbPool.write(counter.increment) + let snapshot = try dbPool.makeSnapshotPool() + try dbPool.write(counter.increment) + + try XCTAssertEqual(dbPool.read(counter.value), 2) + try XCTAssertEqual(snapshot.unsafeRead(counter.value), 1) + // Reuse the last connection + try XCTAssertEqual(dbPool.read(counter.value), 2) + } + + func testSnapshotPool_unsafeReentrantRead() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + + try dbPool.write(counter.increment) + let snapshot = try dbPool.makeSnapshotPool() + try dbPool.write(counter.increment) + + try XCTAssertEqual(dbPool.read(counter.value), 2) + try XCTAssertEqual(snapshot.unsafeReentrantRead { _ in try snapshot.unsafeReentrantRead(counter.value) }, 1) + // Reuse the last connection + try XCTAssertEqual(dbPool.read(counter.value), 2) + } + + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + func testSnapshotPool_read_async() async throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + + try await dbPool.write { try counter.increment($0) } + let snapshot = try dbPool.makeSnapshotPool() + try await dbPool.write { try counter.increment($0) } + + do { + let count = try await dbPool.read { try counter.value($0) } + XCTAssertEqual(count, 2) + } + do { + let count = try await snapshot.read { try counter.value($0) } + XCTAssertEqual(count, 1) + } + do { + // Reuse the last connection + let count = try await dbPool.read { try counter.value($0) } + XCTAssertEqual(count, 2) + } + } + func testPassiveCheckpointDoesNotInvalidateSnapshotPool() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) From e129df15dbc8552bdcd16f2808012ec686c7aaa8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 14 Nov 2022 19:29:17 +0100 Subject: [PATCH 23/69] Fix tests for Xcode 14.0 --- Tests/GRDBTests/DatabaseReaderTests.swift | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index 0bfa2fb73..eae59ecbc 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -28,7 +28,10 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue())) try test(setup(makeDatabasePool())) try test(setup(makeDatabasePool()).makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else try test(setup(makeDatabasePool()).makeSnapshotPool()) +#endif } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @@ -49,7 +52,10 @@ class DatabaseReaderTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) try await test(setup(makeDatabasePool()).makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else try await test(setup(makeDatabasePool()).makeSnapshotPool()) +#endif } func testReadPreventsDatabaseModification() throws { @@ -66,7 +72,10 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else try test(makeDatabasePool().makeSnapshotPool()) +#endif } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @@ -84,7 +93,10 @@ class DatabaseReaderTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) try await test(makeDatabasePool().makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else try await test(makeDatabasePool().makeSnapshotPool()) +#endif } // MARK: - UnsafeRead @@ -106,7 +118,10 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue())) try test(setup(makeDatabasePool())) try test(setup(makeDatabasePool()).makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else try test(setup(makeDatabasePool()).makeSnapshotPool()) +#endif } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @@ -127,7 +142,10 @@ class DatabaseReaderTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) try await test(setup(makeDatabasePool()).makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else try await test(setup(makeDatabasePool()).makeSnapshotPool()) +#endif } // MARK: - UnsafeReentrantRead @@ -149,7 +167,10 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue())) try test(setup(makeDatabasePool())) try test(setup(makeDatabasePool()).makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else try test(setup(makeDatabasePool()).makeSnapshotPool()) +#endif } func testUnsafeReentrantReadIsReentrant() throws { @@ -167,7 +188,10 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else try test(makeDatabasePool().makeSnapshotPool()) +#endif } func testUnsafeReentrantReadIsReentrantFromWrite() throws { @@ -212,7 +236,10 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else try test(makeDatabasePool().makeSnapshotPool()) +#endif } func testAsyncReadPreventsDatabaseModification() throws { @@ -239,7 +266,10 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else try test(makeDatabasePool().makeSnapshotPool()) +#endif } // MARK: - Function @@ -257,7 +287,10 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else try test(makeDatabasePool().makeSnapshotPool()) +#endif } // MARK: - Collation @@ -275,7 +308,10 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else try test(makeDatabasePool().makeSnapshotPool()) +#endif } // MARK: - Backup @@ -300,6 +336,9 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue(configuration: Configuration()))) try test(setup(makeDatabasePool(configuration: Configuration()))) try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshotPool()) +#endif } } From 0bc49460d7e430f541efeab4f6dc3ad19ce6323a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 16 Nov 2022 07:21:00 +0100 Subject: [PATCH 24/69] DatabaseSnapshotPool uses its own pool of connections In the previous implementation, the snapshot pool would use the same reader connections as the database pool. This would create problem with reentrant reads. Let's make things simple, and not share any database connection. --- GRDB/Core/Database+Schema.swift | 18 -- GRDB/Core/DatabasePool.swift | 60 +++++ GRDB/Core/DatabaseSchemaCache.swift | 20 -- GRDB/Core/DatabaseSnapshot.swift | 2 +- GRDB/Core/DatabaseSnapshotPool.swift | 237 +++++++++--------- .../GRDBTests/DatabaseSnapshotPoolTests.swift | 115 ++++----- 6 files changed, 221 insertions(+), 231 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 63ccaf628..a4350e39f 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -22,20 +22,6 @@ extension Database { schemaIdentifiers = nil schemas.removeAll() } - - mutating func formUnion(_ other: SchemaCache) { - let schemaIdentifiers = Set(schemas.keys).union(other.schemas.keys) - for schemaIdentifier in schemaIdentifiers { - switch (schemas[schemaIdentifier], other.schemas[schemaIdentifier]) { - case let (nil, schema): - schemas[schemaIdentifier] = schema - case let (lhs?, rhs?): - schemas[schemaIdentifier] = lhs.union(rhs) - default: - break - } - } - } } /// An SQLite schema. See @@ -1338,10 +1324,6 @@ enum SchemaObjectType: String { struct SchemaInfo: Equatable { private var objects: Set - func union(_ other: SchemaInfo) -> SchemaInfo { - SchemaInfo(objects: objects.union(other.objects)) - } - /// Returns whether there exists a object of given type with this name /// (case-insensitive). func containsObjectNamed(_ name: String, ofType type: SchemaObjectType) -> Bool { diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 5e3ef69ee..3836c7b55 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -885,4 +885,64 @@ extension DatabasePool { defaultLabel: "GRDB.DatabasePool", purpose: "snapshot.\($databaseSnapshotCount.increment())") } + + // swiftlint:disable:next line_length +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + /// Creates a database snapshot that uses the reader connections of + /// the pool. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// The returned snapshot sees an unchanging database content, as it existed + /// at the moment it was created. + /// + /// An error is thrown unless the SQLite database is in the + /// [WAL mode](https://www.sqlite.org/wal.html). + /// + /// It is a programmer error to create a snapshot from the writer dispatch + /// queue when a transaction is opened: + /// + /// ```swift + /// try dbPool.write { db in + /// try Player.deleteAll() + /// + /// // fatal error: makeSnapshot() must not be called from inside a transaction + /// let snapshot = try dbPool.makeSnapshot() + /// } + /// ``` + /// + /// To avoid this fatal error, create the snapshot *before* or *after* + /// the transaction: + /// + /// ```swift + /// let snapshot = try dbPool.makeSnapshot() // OK + /// + /// try dbPool.writeWithoutTransaction { db in + /// let snapshot = try dbPool.makeSnapshot() // OK + /// + /// try db.inTransaction { + /// try Player.deleteAll() + /// return .commit + /// } + /// + /// // OK + /// let snapshot = try dbPool.makeSnapshot() // OK + /// } + /// + /// let snapshot = try dbPool.makeSnapshot() // OK + /// ``` + public func makeSnapshotPool() throws -> DatabaseSnapshotPool { + // Sanity check + if writer.onValidQueue { + writer.execute { db in + GRDBPrecondition( + !db.isInsideTransaction, + "makeSnapshotPool() must not be called from inside a transaction.") + } + } + + return try DatabaseSnapshotPool(path: path, configuration: configuration) + } +#endif } diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index eed828e97..9acaae267 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -36,26 +36,6 @@ struct DatabaseSchemaCache { schemaInfo = nil } - func union(_ other: DatabaseSchemaCache) -> DatabaseSchemaCache { - let mergedSchemaInfo: SchemaInfo? - switch (schemaInfo, other.schemaInfo) { - case (nil, nil): - mergedSchemaInfo = nil - case let (nil, info?), let (info?, nil): - mergedSchemaInfo = info - case let (lhs?, rhs?): - mergedSchemaInfo = lhs.union(rhs) - } - - return DatabaseSchemaCache( - schemaInfo: mergedSchemaInfo, - tables: tables.merging(other.tables) { (current, _) in current }, - primaryKeys: primaryKeys.merging(other.primaryKeys) { (current, _) in current }, - columns: columns.merging(other.columns) { (current, _) in current }, - indexes: indexes.merging(other.indexes) { (current, _) in current }, - foreignKeys: foreignKeys.merging(other.foreignKeys) { (current, _) in current }) - } - func table(_ table: String) -> Presence? { tables[table] } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 997bb10e5..ea02271ad 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -100,7 +100,7 @@ public final class DatabaseSnapshot { try db.beginTransaction(.deferred) // Acquire snapshot isolation - try db.makeStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next() + try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") } } diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index d49663d8e..be01adae8 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -1,6 +1,9 @@ // swiftlint:disable:next line_length #if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) #else +// Sharing connections with DatabasePool creates a problem with reentrant access. +// If we create a new pool of connections, we avoid this problem. And we can +// simplify the management of shared cache (drop all cache-merging code) /// A database connection that allows concurrent accesses to an unchanging /// database content, as it existed at the moment the snapshot was created. @@ -13,9 +16,13 @@ /// lifetime. All database accesses performed from a snapshot always see the /// same identical database content. /// -/// A `DatabaseSnapshotPool` instance shares the same pool of reader SQLite -/// connections as a ``DatabasePool``. It requires an SQLite database in the -/// [WAL mode](https://www.sqlite.org/wal.html). +/// It creates a pool of up to ``Configuration/maximumReaderCount`` read-only +/// SQLite connections. All read accesses are executed in **reader dispatch +/// queues** (one per read-only SQLite connection). SQLite connections are +/// closed when the `DatabasePool` is deallocated. +/// +/// An SQLite database in the [WAL mode](https://www.sqlite.org/wal.html) is +/// required for creating a `DatabaseSnapshotPool`. /// /// ## Usage /// @@ -68,60 +75,86 @@ /// - /// - public final class DatabaseSnapshotPool { - /// The DatabasePool that provides reader connections. - let dbPool: DatabasePool + public let configuration: Configuration - /// The connection that holds a transaction and prevents checkpointing in - /// order to keep `walSnapshot` valid. - let dbSnapshot: DatabaseSnapshot + /// The pool of reader connections. + /// It is constant, until close() sets it to nil. + private var readerPool: Pool? - /// The WAL snapshot - let walSnapshot: WALSnapshot - - /// The version of the schema cache. - let schemaVersion: Int32 - - // Protected by a lock because the cache can be used by multiple - // database connections. - @LockedBox var schemaCache: Database.SchemaCache - - init( - dbPool: DatabasePool, - dbSnapshot: DatabaseSnapshot, - walSnapshot: WALSnapshot, - schemaVersion: Int32, - schemaCache: Database.SchemaCache) - { - self.dbPool = dbPool - self.dbSnapshot = dbSnapshot - self.walSnapshot = walSnapshot - self.schemaVersion = schemaVersion - self.schemaCache = schemaCache + public init(path: String, configuration: Configuration = Configuration()) throws { + GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1") + + var configuration = DatabasePool.readerConfiguration(configuration) + + // Snapshot keeps a long-lived transaction + configuration.allowsUnsafeTransactions = true + + var walSnapshot: WALSnapshot? + configuration.prepareDatabase { db in + // Open transaction + try db.beginTransaction(.deferred) + + // Acquire snapshot isolation + try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") + + // Open snapshot + if let walSnapshot { + let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot) + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code) + } + } + } + + self.configuration = configuration + + var readerCount = 0 + readerPool = Pool( + maximumCount: configuration.maximumReaderCount, + qos: configuration.readQoS, + makeElement: { + readerCount += 1 // protected by Pool (TODO: document this protection behavior) + return try SerializedDatabase( + path: path, + configuration: configuration, + defaultLabel: "GRDB.DatabaseSnapshotPool", + purpose: "snapshot.\(readerCount)") + }) + + walSnapshot = try readerPool!.get { reader in + try reader.sync { db in + try WALSnapshot(db) + } + } } } extension DatabaseSnapshotPool: @unchecked Sendable { } extension DatabaseSnapshotPool: DatabaseReader { - public var configuration: Configuration { - DatabasePool.readerConfiguration(dbPool.configuration) - } - - /// Throws a ``DatabaseError`` of code `SQLITE_MISUSE`. Close the source - /// ``DatabasePool`` instead. public func close() throws { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "") + try readerPool?.barrier { + defer { readerPool = nil } + + try readerPool?.forEach { reader in + try reader.sync { try $0.close() } + } + } } public func interrupt() { - dbPool.interrupt() + readerPool?.forEach { $0.interrupt() } } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func read(_ value: (Database) throws -> T) throws -> T { - try dbPool.read { db in - try db.read(from: self) { - try value(db) + GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + return try readerPool.get { reader in + try reader.sync { db in + return try value(db) } } } @@ -132,11 +165,18 @@ extension DatabaseSnapshotPool: DatabaseReader { } public func asyncRead(_ value: @escaping (Result) -> Void) { - dbPool.asyncRead { dbResult in + guard let readerPool else { + value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed"))) + return + } + + readerPool.asyncGet { result in do { - let db = try dbResult.get() - try db.read(from: self) { + let (reader, releaseReader) = try result.get() + // Second async jump because that's how `Pool.async` has to be used. + reader.async { db in value(.success(db)) + releaseReader() } } catch { value(.failure(error)) @@ -150,10 +190,15 @@ extension DatabaseSnapshotPool: DatabaseReader { } public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { - try dbPool.unsafeReentrantRead { db in - try db.isolated { - try db.read(from: self) { - try value(db) + if let reader = currentReader { + return try reader.reentrantSync(value) + } else { + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + return try readerPool.get { reader in + try reader.sync { db in + return try value(db) } } } @@ -167,83 +212,31 @@ extension DatabaseSnapshotPool: DatabaseReader { { _addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange) } -} - -extension DatabasePool { - /// Creates a database snapshot that uses the reader connections of - /// the pool. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// The returned snapshot sees an unchanging database content, as it existed - /// at the moment it was created. It shares the same reader SQLite - /// connections as the `DatabasePool`. - /// - /// An error is thrown unless the SQLite database is in the - /// [WAL mode](https://www.sqlite.org/wal.html). - /// - /// It is a programmer error to create a snapshot from the writer dispatch - /// queue when a transaction is opened: - /// - /// ```swift - /// try dbPool.write { db in - /// try Player.deleteAll() - /// - /// // fatal error: makeSnapshot() must not be called from inside a transaction - /// let snapshot = try dbPool.makeSnapshot() - /// } - /// ``` - /// - /// To avoid this fatal error, create the snapshot *before* or *after* - /// the transaction: - /// - /// ```swift - /// let snapshot = try dbPool.makeSnapshot() // OK - /// - /// try dbPool.writeWithoutTransaction { db in - /// let snapshot = try dbPool.makeSnapshot() // OK - /// - /// try db.inTransaction { - /// try Player.deleteAll() - /// return .commit - /// } - /// - /// // OK - /// let snapshot = try dbPool.makeSnapshot() // OK - /// } - /// - /// let snapshot = try dbPool.makeSnapshot() // OK - /// ``` - public func makeSnapshotPool() throws -> DatabaseSnapshotPool { - let dbSnapshot = try makeSnapshot() - return try dbSnapshot.read { db in - try DatabaseSnapshotPool( - dbPool: self, - dbSnapshot: dbSnapshot, - walSnapshot: WALSnapshot(db), - schemaVersion: db.schemaVersion(), - schemaCache: db.schemaCache) - } - } -} - -extension Database { - fileprivate func open(_ snapshot: DatabaseSnapshotPool) throws { - let code = sqlite3_snapshot_open(sqliteConnection, "main", snapshot.walSnapshot.sqliteSnapshot) - guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code) - } - lastSchemaVersion = snapshot.schemaVersion - schemaCache = snapshot.schemaCache - } - fileprivate func read(from snapshot: DatabaseSnapshotPool, _ value: () throws -> T) throws -> T { - try open(snapshot) - defer { - snapshot.$schemaCache.update { $0.formUnion(schemaCache) } + /// Returns a reader that can be used from the current dispatch queue, + /// if any. + private var currentReader: SerializedDatabase? { + guard let readerPool else { + return nil } - return try value() + var readers: [SerializedDatabase] = [] + readerPool.forEach { reader in + // We can't check for reader.onValidQueue here because + // Pool.forEach() runs its closure argument in some arbitrary + // dispatch queue. We thus extract the reader so that we can query + // it below. + readers.append(reader) + } + + // Now the readers array contains some readers. The pool readers may + // already be different, because some other thread may have started + // a new read, for example. + // + // This doesn't matter: the reader we are looking for is already on + // its own dispatch queue. If it exists, is still in use, thus still + // in the pool, and thus still relevant for our check: + return readers.first { $0.onValidQueue } } } #endif diff --git a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift index 12fc35e20..7d0b65703 100644 --- a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift @@ -22,11 +22,11 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { } } - func testSnapshotPoolCreationFromNewDatabase() throws { + func test_creation_from_new_database() throws { _ = try makeDatabasePool().makeSnapshotPool() } - func testSnapshotPoolCreationFromNonWALDatabase() throws { + func test_creation_from_non_WAL_database() throws { let dbQueue = try makeDatabaseQueue() var config = Configuration() @@ -39,10 +39,9 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { } catch DatabaseError.SQLITE_ERROR { } } - func testSnapshotPool_read() throws { + func test_read() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) - try dbPool.write(counter.increment) let snapshot = try dbPool.makeSnapshotPool() try dbPool.write(counter.increment) @@ -53,7 +52,46 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { try XCTAssertEqual(dbPool.read(counter.value), 2) } - func testSnapshotPool_unsafeRead() throws { + func test_concurrent_read() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 + try dbPool.write(counter.increment) // 2 + + // Block 1 Block 2 + // snapshot.read { + // SELECT COUNT(*) FROM counter + // > + let s1 = DispatchSemaphore(value: 0) + // snapshot.read { + // SELECT COUNT(*) FROM counter + // < + let s2 = DispatchSemaphore(value: 0) + // end end + // } + + let block1: () -> Void = { + try! snapshot.read { db -> Void in + try XCTAssertEqual(counter.value(db), 1) + s1.signal() + _ = s2.wait(timeout: .distantFuture) + } + } + let block2: () -> Void = { + _ = s1.wait(timeout: .distantFuture) + try! snapshot.read { db -> Void in + try XCTAssertEqual(counter.value(db), 1) + s2.signal() + } + } + let blocks = [block1, block2] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in + blocks[index]() + } + } + + func test_unsafeRead() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) @@ -67,7 +105,7 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { try XCTAssertEqual(dbPool.read(counter.value), 2) } - func testSnapshotPool_unsafeReentrantRead() throws { + func test_unsafeReentrantRead() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) @@ -82,7 +120,7 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - func testSnapshotPool_read_async() async throws { + func test_read_async() async throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) @@ -148,68 +186,5 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { try dbPool.write(counter.increment) try XCTAssertEqual(snapshot.read(counter.value), 1) } - - func testSnapshotPoolAndSchemaCache() throws { - let dbPool = try makeDatabasePool() - try dbPool.write { db in - try db.execute(sql: """ - CREATE TABLE player(id INTEGER PRIMARY KEY, name, score); - """) - } - - let snapshot = try dbPool.makeSnapshotPool() - - try dbPool.write { db in - try db.execute(sql: """ - CREATE TABLE team(id INTEGER PRIMARY KEY, name, color); - """) - } - - do { - let exists = try dbPool.read { try $0.tableExists("team") } - XCTAssertTrue(exists) - } - - do { - let exists = try snapshot.read { try $0.tableExists("team") } - XCTAssertFalse(exists) - } - - do { - let exists = try dbPool.read { try $0.tableExists("team") } - XCTAssertTrue(exists) - } - } - - func testSnapshotPoolAndStatementCache() throws { - let dbPool = try makeDatabasePool() - let request = SQLRequest(sql: "SELECT COUNT(*) FROM player", cached: true) - try dbPool.write { db in - try db.execute(sql: """ - CREATE TABLE player(id INTEGER PRIMARY KEY, name, score); - """) - } - - let snapshot = try dbPool.makeSnapshotPool() - - try dbPool.write { db in - try db.execute(sql: "DROP TABLE player") - } - - do { - let count = try snapshot.read { try request.fetchOne($0) } - XCTAssertEqual(count, 0) - } - - do { - _ = try dbPool.read { try request.fetchOne($0) } - XCTFail("Expected error") - } catch DatabaseError.SQLITE_ERROR { } - - do { - let count = try snapshot.read { try request.fetchOne($0) } - XCTAssertEqual(count, 0) - } - } } #endif From 12d656d3a19232596e88b99a2b5769a1d1cfd390 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 17 Nov 2022 20:01:17 +0100 Subject: [PATCH 25/69] Let SQLite check if DatabaseSnapshotPool can be created --- GRDB/Core/Database.swift | 3 + GRDB/Core/DatabasePool.swift | 64 ++------- GRDB/Core/DatabaseSnapshot.swift | 2 +- GRDB/Core/DatabaseSnapshotPool.swift | 119 +++++++++++++++- .../GRDBTests/DatabaseSnapshotPoolTests.swift | 134 +++++++++++++----- 5 files changed, 224 insertions(+), 98 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 30081aeb9..eddd8d380 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -217,6 +217,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Internal properties + let path: String + /// 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 @@ -306,6 +308,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags) self.description = description self.configuration = configuration + self.path = path // We do not report read-only transactions to transaction observers, so // don't bother installing the observation broker for read-only connections. diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 3836c7b55..11aaeb2d2 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -832,10 +832,8 @@ extension DatabasePool { // MARK: - Snapshots - /// Creates an independent database snapshot. - /// - /// The returned snapshot sees an unchanging database content, as it existed - /// at the moment it was created. + /// Creates a database snapshot that serializes accesses to an unchanging + /// database content, as it exists at the moment the snapshot is created. /// /// It is a programmer error to create a snapshot from the writer dispatch /// queue when a transaction is opened: @@ -889,60 +887,20 @@ extension DatabasePool { // swiftlint:disable:next line_length #if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) #else - /// Creates a database snapshot that uses the reader connections of - /// the pool. + /// Creates a database snapshot that allows concurrent accesses to an + /// unchanging database content, as it exists at the moment the snapshot + /// is created. /// /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// - /// The returned snapshot sees an unchanging database content, as it existed - /// at the moment it was created. - /// - /// An error is thrown unless the SQLite database is in the - /// [WAL mode](https://www.sqlite.org/wal.html). - /// - /// It is a programmer error to create a snapshot from the writer dispatch - /// queue when a transaction is opened: - /// - /// ```swift - /// try dbPool.write { db in - /// try Player.deleteAll() - /// - /// // fatal error: makeSnapshot() must not be called from inside a transaction - /// let snapshot = try dbPool.makeSnapshot() - /// } - /// ``` - /// - /// To avoid this fatal error, create the snapshot *before* or *after* - /// the transaction: - /// - /// ```swift - /// let snapshot = try dbPool.makeSnapshot() // OK - /// - /// try dbPool.writeWithoutTransaction { db in - /// let snapshot = try dbPool.makeSnapshot() // OK - /// - /// try db.inTransaction { - /// try Player.deleteAll() - /// return .commit - /// } - /// - /// // OK - /// let snapshot = try dbPool.makeSnapshot() // OK - /// } - /// - /// let snapshot = try dbPool.makeSnapshot() // OK - /// ``` + /// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite + /// database is not in the [WAL mode](https://www.sqlite.org/wal.html), or + /// if this method is called from a database access where a write + /// transaction is open. public func makeSnapshotPool() throws -> DatabaseSnapshotPool { - // Sanity check - if writer.onValidQueue { - writer.execute { db in - GRDBPrecondition( - !db.isInsideTransaction, - "makeSnapshotPool() must not be called from inside a transaction.") - } + try unsafeReentrantRead { db in + try DatabaseSnapshotPool(db) } - - return try DatabaseSnapshotPool(path: path, configuration: configuration) } #endif } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index ea02271ad..84fddf8f5 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -52,7 +52,7 @@ import Dispatch /// return .commit /// } /// -/// return dbPool.makeSnapshot() +/// return try dbPool.makeSnapshot() /// } /// /// // <- Other threads may have created some players here diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index be01adae8..33b98dd7d 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -26,8 +26,9 @@ /// /// ## Usage /// -/// You create a `DatabaseSnapshotPool` from a ``DatabasePool``, -/// with ``DatabasePool/makeSnapshotPool()``: +/// You create a `DatabaseSnapshotPool` from a +/// [WAL mode](https://www.sqlite.org/wal.html) database, such as databases +/// created from a ``DatabasePool``: /// /// ```swift /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") @@ -48,13 +49,15 @@ /// some players: /// /// ```swift -/// let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in +/// let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshotPool in /// try db.inTransaction { /// try Player.deleteAll() /// return .commit /// } /// -/// return dbPool.makeSnapshotPool() +/// return try dbPool.makeSnapshotPool() +/// // OR (this is equivalent) +/// return try DatabaseSnapshotPool(db) /// } /// /// // <- Other threads may have created some players here @@ -74,19 +77,120 @@ /// /// - /// - +/// +/// ## Topics +/// +/// ### Creating a DatabaseSnapshotPool +/// +/// See also ``DatabasePool/makeSnapshotPool()``. +/// +/// - ``init(_:)`` +/// - ``init(path:configuration:)`` public final class DatabaseSnapshotPool { public let configuration: Configuration + /// The path to the database file. + public let path: String + /// The pool of reader connections. /// It is constant, until close() sets it to nil. private var readerPool: Pool? + /// Creates a snapshot of the database. + /// + /// For example: + /// + /// ```swift + /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") + /// let snapshot = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshotPool in + /// try db.inTransaction { + /// try Player.deleteAll() + /// return .commit + /// } + /// + /// return DatabaseSnapshotPool(db) + /// } + /// ``` + /// + /// If any of the following statements are false when the snapshot is + /// created, a ``DatabaseError`` of code `SQLITE_ERROR` is thrown: + /// + /// - The database connection must be in the + /// [WAL mode](https://www.sqlite.org/wal.html). + /// - There must not be a write transaction open. + /// + /// Related SQLite documentation: + /// + /// - parameter db: A database connection. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public init(_ db: Database) throws { + // Snapshot keeps a long-lived transaction + var configuration = DatabasePool.readerConfiguration(db.configuration) + configuration.allowsUnsafeTransactions = true + + GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1") + + var walSnapshot: WALSnapshot? + configuration.prepareDatabase { db in + // Open transaction + try db.beginTransaction(.deferred) + + // Acquire snapshot isolation + try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") + + // Open snapshot + let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot!.sqliteSnapshot) + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code) + } + } + + self.configuration = configuration + self.path = db.path + + var readerCount = 0 + readerPool = Pool( + maximumCount: configuration.maximumReaderCount, + qos: configuration.readQoS, + makeElement: { + readerCount += 1 // protected by Pool (TODO: document this protection behavior) + return try SerializedDatabase( + path: db.path, + configuration: configuration, + defaultLabel: "GRDB.DatabaseSnapshotPool", + purpose: "snapshot.\(readerCount)") + }) + + // Get WAL snapshot + walSnapshot = try db.isolated(readOnly: true) { try WALSnapshot(db) } + + // Create first connection that will keep the WALSnapshot alive. + try readerPool!.get { _ in } + } + + /// Creates a snapshot of the database. + /// + /// For example: + /// + /// ```swift + /// let snapshot = try DatabaseSnapshotPool(path: "/path/to/database.sqlite") + /// ``` + /// + /// If the database at `path` is not in the + /// [WAL mode](https://www.sqlite.org/wal.html), a ``DatabaseError`` of code + /// `SQLITE_ERROR` is thrown. + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - path: The path to the database file. + /// - configuration: A configuration. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public init(path: String, configuration: Configuration = Configuration()) throws { GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1") - var configuration = DatabasePool.readerConfiguration(configuration) - // Snapshot keeps a long-lived transaction + var configuration = DatabasePool.readerConfiguration(configuration) configuration.allowsUnsafeTransactions = true var walSnapshot: WALSnapshot? @@ -98,7 +202,7 @@ public final class DatabaseSnapshotPool { try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") // Open snapshot - if let walSnapshot { + if let walSnapshot { // nil on first connection created below let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot) guard code == SQLITE_OK else { throw DatabaseError(resultCode: code) @@ -107,6 +211,7 @@ public final class DatabaseSnapshotPool { } self.configuration = configuration + self.path = path var readerCount = 0 readerPool = Pool( diff --git a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift index 7d0b65703..8716e2a8f 100644 --- a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift @@ -22,11 +22,11 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { } } - func test_creation_from_new_database() throws { + func test_creation_from_new_DatabasePool() throws { _ = try makeDatabasePool().makeSnapshotPool() } - func test_creation_from_non_WAL_database() throws { + func test_creation_from_non_WAL_DatabasePool() throws { let dbQueue = try makeDatabaseQueue() var config = Configuration() @@ -39,12 +39,75 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { } catch DatabaseError.SQLITE_ERROR { } } + func test_creation_from_DatabasePool_write_and_read() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.write { db in try DatabaseSnapshotPool(db) } // locked at 1 + try dbPool.write(counter.increment) // 2 + + try XCTAssertEqual(dbPool.read(counter.value), 2) + try XCTAssertEqual(snapshot.read(counter.value), 1) + // Reuse the last connection + try XCTAssertEqual(dbPool.read(counter.value), 2) + } + + func test_creation_from_DatabasePool_writeWithoutTransaction_and_read() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.writeWithoutTransaction { db in try DatabaseSnapshotPool(db) } // locked at 1 + try dbPool.write(counter.increment) // 2 + + try XCTAssertEqual(dbPool.read(counter.value), 2) + try XCTAssertEqual(snapshot.read(counter.value), 1) + // Reuse the last connection + try XCTAssertEqual(dbPool.read(counter.value), 2) + } + + func test_creation_from_DatabasePool_uncommitted_write() throws { + let dbPool = try makeDatabasePool() + do { + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE t(a)") + _ = try DatabaseSnapshotPool(db) + } + XCTFail("Expected error") + } catch DatabaseError.SQLITE_ERROR { } + } + + func test_creation_from_DatabasePool_read_and_read() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.read { db in try DatabaseSnapshotPool(db) } // locked at 1 + try dbPool.write(counter.increment) // 2 + + try XCTAssertEqual(dbPool.read(counter.value), 2) + try XCTAssertEqual(snapshot.read(counter.value), 1) + // Reuse the last connection + try XCTAssertEqual(dbPool.read(counter.value), 2) + } + + func test_creation_from_DatabasePool_unsafeRead_and_read() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.unsafeRead { db in try DatabaseSnapshotPool(db) } // locked at 1 + try dbPool.write(counter.increment) // 2 + + try XCTAssertEqual(dbPool.read(counter.value), 2) + try XCTAssertEqual(snapshot.read(counter.value), 1) + // Reuse the last connection + try XCTAssertEqual(dbPool.read(counter.value), 2) + } + func test_read() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() - try dbPool.write(counter.increment) + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(dbPool.read(counter.value), 2) try XCTAssertEqual(snapshot.read(counter.value), 1) @@ -93,11 +156,10 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { func test_unsafeRead() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() - try dbPool.write(counter.increment) + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(dbPool.read(counter.value), 2) try XCTAssertEqual(snapshot.unsafeRead(counter.value), 1) @@ -107,11 +169,10 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { func test_unsafeReentrantRead() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() - try dbPool.write(counter.increment) + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(dbPool.read(counter.value), 2) try XCTAssertEqual(snapshot.unsafeReentrantRead { _ in try snapshot.unsafeReentrantRead(counter.value) }, 1) @@ -122,11 +183,10 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func test_read_async() async throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - - try await dbPool.write { try counter.increment($0) } - let snapshot = try dbPool.makeSnapshotPool() - try await dbPool.write { try counter.increment($0) } + let counter = try Counter(dbPool: dbPool) // 0 + try await dbPool.write { try counter.increment($0) } // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 + try await dbPool.write { try counter.increment($0) } // 2 do { let count = try await dbPool.read { try counter.value($0) } @@ -145,45 +205,45 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { func testPassiveCheckpointDoesNotInvalidateSnapshotPool() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.passive) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) - try dbPool.write(counter.increment) + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(snapshot.read(counter.value), 1) } func testFullCheckpointDoesNotInvalidateSnapshotPool() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.full) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) - try dbPool.write(counter.increment) + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(snapshot.read(counter.value), 1) } func testRestartCheckpointDoesNotInvalidateSnapshotPool() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.restart) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) - try dbPool.write(counter.increment) + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(snapshot.read(counter.value), 1) } func testTruncateCheckpointDoesNotInvalidateSnapshotPool() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.truncate) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) - try dbPool.write(counter.increment) + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(snapshot.read(counter.value), 1) } } From b1770e89b7b4fb4b1ef3f9d17ff8dc1a88036ce0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 17 Nov 2022 20:11:58 +0100 Subject: [PATCH 26/69] Introduce DatabaseSnapshotReader --- GRDB/Core/DatabaseReader.swift | 15 ++++++++++++--- GRDB/Core/DatabaseSnapshot.swift | 2 +- GRDB/Core/DatabaseSnapshotPool.swift | 2 +- GRDB/Core/DatabaseWriter.swift | 4 ++-- GRDB/Documentation.docc/Concurrency.md | 3 ++- GRDB/Documentation.docc/DatabaseConnections.md | 2 +- 6 files changed, 19 insertions(+), 9 deletions(-) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index ff667252c..3f2b2dbae 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -5,9 +5,8 @@ import Dispatch /// A type that reads from an SQLite database. /// -/// Do not declare new conformances to `DatabaseReader`. Only the -/// ``DatabaseQueue``, ``DatabasePool``, and ``DatabaseSnapshot`` types are -/// valid conforming types. +/// Do not declare new conformances to `DatabaseReader`. Only the built-in +/// conforming types are valid. /// /// The protocol comes with isolation guarantees that describe the behavior of /// conforming types in a multithreaded application. See for @@ -687,3 +686,13 @@ extension AnyDatabaseReader: DatabaseReader { onChange: onChange) } } + +/// A type that sees an unchanging database content. +/// +/// Do not declare new conformances to `DatabaseSnapshotReader`. Only the +/// built-in conforming types are valid. +/// +/// The protocol comes with the same features and guarantees as +/// ``DatabaseReader``. On top of them, a `DatabaseSnapshotReader` always sees +/// the same state of the database. +public protocol DatabaseSnapshotReader: DatabaseReader { } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 84fddf8f5..e43168bb4 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -112,7 +112,7 @@ public final class DatabaseSnapshot { } } -extension DatabaseSnapshot: DatabaseReader { +extension DatabaseSnapshot: DatabaseSnapshotReader { public func close() throws { try reader.sync { try $0.close() } } diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 33b98dd7d..4e56f28d2 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -236,7 +236,7 @@ public final class DatabaseSnapshotPool { extension DatabaseSnapshotPool: @unchecked Sendable { } -extension DatabaseSnapshotPool: DatabaseReader { +extension DatabaseSnapshotPool: DatabaseSnapshotReader { public func close() throws { try readerPool?.barrier { defer { readerPool = nil } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 6322e7358..fb264a6b3 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -5,8 +5,8 @@ import Dispatch /// A type that writes into an SQLite database. /// -/// Do not declare new conformances to `DatabaseWriter`. Only the -/// ``DatabaseQueue`` and ``DatabasePool`` types are valid conforming types. +/// Do not declare new conformances to `DatabaseWriter`. Only the built-in +/// conforming types are valid. /// /// A database writer creates one single SQLite connection dedicated to database /// updates. All updates are executed in a serial **writer dispatch queue**. diff --git a/GRDB/Documentation.docc/Concurrency.md b/GRDB/Documentation.docc/Concurrency.md index fb40d98c4..4f6efbe02 100644 --- a/GRDB/Documentation.docc/Concurrency.md +++ b/GRDB/Documentation.docc/Concurrency.md @@ -337,8 +337,9 @@ Types that conform to ``TransactionObserver`` can also use those methods in thei ### Database Connections with Concurrency Guarantees -- ``DatabaseReader`` - ``DatabaseWriter`` +- ``DatabaseReader`` +- ``DatabaseSnapshotReader`` ### Advanced Concurrency diff --git a/GRDB/Documentation.docc/DatabaseConnections.md b/GRDB/Documentation.docc/DatabaseConnections.md index 0c959f199..db6321bd9 100644 --- a/GRDB/Documentation.docc/DatabaseConnections.md +++ b/GRDB/Documentation.docc/DatabaseConnections.md @@ -28,7 +28,7 @@ The differences are: - ``Configuration`` -### Opening Database Connections +### Database Connections - ``DatabaseQueue`` - ``DatabasePool`` From 79d4db7827f6da4ceaf8d6fafcaf37ffffc92edd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 17 Nov 2022 21:56:01 +0100 Subject: [PATCH 27/69] More DatabaseSnapshotPool tests --- GRDB/Core/DatabaseSnapshotPool.swift | 4 ++- GRDB/Core/WALSnapshot.swift | 2 -- .../DatabaseReaderReadPublisherTests.swift | 24 +++++++++++++++++ .../DatabaseAbortedTransactionTests.swift | 8 ++++++ .../DatabaseConfigurationTests.swift | 15 +++++++++++ .../ValueObservationPrintTests.swift | 26 +++++++++++++++++-- 6 files changed, 74 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 4e56f28d2..9b372f3f7 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -162,7 +162,9 @@ public final class DatabaseSnapshotPool { }) // Get WAL snapshot - walSnapshot = try db.isolated(readOnly: true) { try WALSnapshot(db) } + walSnapshot = try db.isolated(readOnly: true) { + try WALSnapshot(db) + } // Create first connection that will keep the WALSnapshot alive. try readerPool!.get { _ in } diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index 6ec2d7e48..2d25f77e1 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -42,8 +42,6 @@ final class WALSnapshot: Sendable { let sqliteSnapshot: UnsafeMutablePointer - /// Returns nil if `SQLITE_ENABLE_SNAPSHOT` is not enabled, or if an - /// error occurs. init(_ db: Database) throws { var sqliteSnapshot: UnsafeMutablePointer? let code = withUnsafeMutablePointer(to: &sqliteSnapshot) { diff --git a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift index aa4957c01..f039aa846 100644 --- a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift @@ -44,6 +44,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { 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() } +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() } +#endif } // MARK: - @@ -146,6 +150,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { 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() } +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshotPool() } +#endif } // MARK: - @@ -183,6 +191,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { 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() } +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() } +#endif } // MARK: - @@ -220,6 +232,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { 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() } +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() } +#endif } // MARK: - @@ -258,6 +274,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { 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() } +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() } +#endif } // MARK: - @@ -283,6 +303,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { 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() } +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshotPool() } +#endif } } #endif diff --git a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift index 55d929fff..975d18634 100644 --- a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift +++ b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift @@ -40,6 +40,10 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + try test(makeDatabasePool().makeSnapshotPool()) +#endif } func testReadTransactionAbortedByInterruptDoesNotPreventFurtherRead() throws { @@ -82,6 +86,10 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + try test(makeDatabasePool().makeSnapshotPool()) +#endif } func testWriteTransactionAbortedByInterrupt() throws { diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index 79a5dcfbf..4949ace63 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -26,6 +26,12 @@ class DatabaseConfigurationTests: GRDBTestCase { try pool.makeSnapshot().read { _ in } XCTAssertEqual(connectionCount, 5) + +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + try pool.makeSnapshotPool().read { _ in } + XCTAssertEqual(connectionCount, 6) +#endif } func testPrepareDatabaseError() throws { @@ -68,6 +74,15 @@ class DatabaseConfigurationTests: GRDBTestCase { _ = try pool.makeSnapshot() XCTFail("Expected TestError") } catch is TestError { } + +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + do { + error = TestError() + _ = try pool.makeSnapshotPool() + XCTFail("Expected TestError") + } catch is TestError { } +#endif } } diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index 35f6da8cd..b8cc04778 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -54,6 +54,10 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabaseQueue(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool()) +#endif } func test_readonly_success_immediateScheduling() throws { @@ -88,11 +92,18 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabaseQueue(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool()) +#endif } func test_readonly_failure_asynchronousScheduling() throws { struct TestError: Error { } - _ = try makeDatabasePool(filename: "test") + let dbPool = try makeDatabasePool(filename: "test") + // workaround Xcode 14.1 compiler (???) bug: database is not in the WAL + // mode unless the pool is used. + try dbPool.write { _ in } func test(_ dbReader: some DatabaseReader) throws { let logger = TestStream() @@ -120,11 +131,18 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabaseQueue(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool()) +#endif } func test_readonly_failure_immediateScheduling() throws { struct TestError: Error { } - _ = try makeDatabasePool(filename: "test") + let dbPool = try makeDatabasePool(filename: "test") + // workaround Xcode 14.1 compiler (???) bug: database is not in the WAL + // mode unless the pool is used. + try dbPool.write { _ in } func test(_ dbReader: some DatabaseReader) throws { let logger = TestStream() @@ -152,6 +170,10 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabaseQueue(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool()) +#endif } // MARK: - Writeonly From e4c5cc34510e5d22d2e4c96a727fea3b4c8fd3b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 17 Nov 2022 22:04:06 +0100 Subject: [PATCH 28/69] Test that DatabaseSnapshotPool can be used from ValueObservation --- Tests/GRDBTests/ValueObservationTests.swift | 27 ++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 35abb25d1..dc834a3c6 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -313,7 +313,7 @@ class ValueObservationTests: GRDBTestCase { } } } - + // MARK: - Snapshot Optimization func testDisallowedSnapshotOptimizationWithAsyncScheduler() throws { @@ -496,6 +496,31 @@ class ValueObservationTests: GRDBTestCase { } } + // MARK: - Snapshot Observation + + func testDatabaseSnapshotPoolObservation() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + let expectation = XCTestExpectation() + expectation.assertForOverFulfill = false + + let observation = ValueObservation.trackingConstantRegion { db in + try db.registerAccess(to: Table("t")) + expectation.fulfill() + return try DatabaseSnapshotPool(db) + } + + let recorder = observation.record(in: dbPool) + wait(for: [expectation], timeout: 5) + try dbPool.write { try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") } + + let results = try wait(for: recorder.next(2), timeout: 5) + XCTAssertEqual(results.count, 2) + try XCTAssertEqual(results[0].read { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! }, 0) + try XCTAssertEqual(results[1].read { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! }, 1) + } + // MARK: - Cancellation func testCancellableLifetime() throws { From 8a42c116244a5f653554f9f8e73f166e609d7a66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 17 Nov 2022 22:38:41 +0100 Subject: [PATCH 29/69] DatabaseSnapshotPool documentation --- GRDB/Core/DatabaseSnapshotPool.swift | 60 ++++++++++++++-------------- 1 file changed, 29 insertions(+), 31 deletions(-) diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 9b372f3f7..62f80006a 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -5,6 +5,7 @@ // If we create a new pool of connections, we avoid this problem. And we can // simplify the management of shared cache (drop all cache-merging code) +#warning("TODO: restore or don't reuse connections that have lost their transaction") /// A database connection that allows concurrent accesses to an unchanging /// database content, as it existed at the moment the snapshot was created. /// @@ -33,41 +34,29 @@ /// ```swift /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") /// let snapshot = try dbPool.makeSnapshotPool() -/// let playerCount = try snapshot.read { db in -/// try Player.fetchCount(db) -/// } /// ``` /// /// When you want to control the database state seen by a snapshot, create the -/// snapshot from within a write access, outside of any transaction. -/// -/// For example, compare the two snapshots below. The first one is guaranteed to -/// see an empty table of players, because is is created after all players have -/// been deleted, and from the serialized writer dispatch queue which prevents -/// any concurrent write. The second is created without this concurrency -/// protection, which means that some other threads may already have created -/// some players: +/// snapshot from a database connection, outside of a write transaction. You can +/// for example take snapshots from a ``ValueObservation``: /// /// ```swift -/// let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshotPool in -/// try db.inTransaction { -/// try Player.deleteAll() -/// return .commit -/// } -/// -/// return try dbPool.makeSnapshotPool() -/// // OR (this is equivalent) +/// // An observation of the 'player' table +/// // that notifies fresh database snapshots: +/// let observation = ValueObservation.tracking { db in +/// // Don't fetch players now, and return a snapshot instead. +/// // Register an access to the player table so that the +/// // observation tracks changes to this table. +/// try db.registerAccess(to: Player.all()) /// return try DatabaseSnapshotPool(db) /// } /// -/// // <- Other threads may have created some players here -/// let snapshot2 = try dbPool.makeSnapshotPool() -/// -/// // Guaranteed to be zero -/// let count1 = try snapshot1.read(Player.fetchCount) -/// -/// // Could be anything -/// let count2 = try snapshot2.read(Player.fetchCount) +/// // Start observing the 'player' table +/// let cancellable = try observation.start(in: dbPool) { error in +/// // Handle error +/// } onChange: { (snapshot: DatabaseSnapshotPool) in +/// // Handle a fresh snapshot +/// } /// ``` /// /// `DatabaseSnapshotPool` inherits its database access methods from the @@ -84,7 +73,7 @@ /// /// See also ``DatabasePool/makeSnapshotPool()``. /// -/// - ``init(_:)`` +/// - ``init(_:configuration:)`` /// - ``init(path:configuration:)`` public final class DatabaseSnapshotPool { public let configuration: Configuration @@ -108,8 +97,14 @@ public final class DatabaseSnapshotPool { /// return .commit /// } /// + /// // Create the snapshot after all players have been deleted. /// return DatabaseSnapshotPool(db) /// } + /// + /// // Later... Maybe some players have been created. + /// // The snapshot is guaranteed to see an empty table of players, though: + /// let count = try snapshot.read(Player.fetchCount) + /// assert(count == 0) /// ``` /// /// If any of the following statements are false when the snapshot is @@ -122,10 +117,13 @@ public final class DatabaseSnapshotPool { /// Related SQLite documentation: /// /// - parameter db: A database connection. + /// - parameter configuration: A configuration. If nil, the configuration of + /// `db` is used. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public init(_ db: Database) throws { + public init(_ db: Database, configuration: Configuration? = nil) throws { + var configuration = DatabasePool.readerConfiguration(configuration ?? db.configuration) + // Snapshot keeps a long-lived transaction - var configuration = DatabasePool.readerConfiguration(db.configuration) configuration.allowsUnsafeTransactions = true GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1") @@ -189,10 +187,10 @@ public final class DatabaseSnapshotPool { /// - configuration: A configuration. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public init(path: String, configuration: Configuration = Configuration()) throws { + var configuration = DatabasePool.readerConfiguration(configuration) GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1") // Snapshot keeps a long-lived transaction - var configuration = DatabasePool.readerConfiguration(configuration) configuration.allowsUnsafeTransactions = true var walSnapshot: WALSnapshot? From 847386860f1c92312fc169e97881bd13eceb5591 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 17 Nov 2022 22:48:13 +0100 Subject: [PATCH 30/69] Fix test compilation on Xcode 14 Grrr --- Tests/GRDBTests/ValueObservationTests.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index dc834a3c6..4d618aa71 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -498,6 +498,8 @@ class ValueObservationTests: GRDBTestCase { // MARK: - Snapshot Observation +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else func testDatabaseSnapshotPoolObservation() throws { let dbPool = try makeDatabasePool() try dbPool.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -520,6 +522,7 @@ class ValueObservationTests: GRDBTestCase { try XCTAssertEqual(results[0].read { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! }, 0) try XCTAssertEqual(results[1].read { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! }, 1) } +#endif // MARK: - Cancellation From 9b663e3bcc35d3c107adc43cda814e570ce383ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 Nov 2022 08:09:02 +0100 Subject: [PATCH 31/69] Pool can discard elements after use --- GRDB/Core/DatabasePool.swift | 6 +- GRDB/Core/DatabaseSnapshotPool.swift | 2 +- GRDB/Utils/Pool.swift | 35 ++++++++---- Tests/GRDBTests/PoolTests.swift | 85 +++++++++++++++++++--------- 4 files changed, 86 insertions(+), 42 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 11aaeb2d2..1e4231929 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -432,7 +432,7 @@ extension DatabasePool: DatabaseReader { reader.async { db in defer { try? db.commit() // Ignore commit error - releaseReader() + releaseReader(.reuse) } do { // The block isolation comes from the DEFERRED transaction. @@ -475,7 +475,7 @@ extension DatabasePool: DatabaseReader { // Second async jump because that's how `Pool.async` has to be used. reader.async { db in defer { - releaseReader() + releaseReader(.reuse) } do { try db.clearSchemaCacheIfNeeded() @@ -591,7 +591,7 @@ extension DatabasePool: DatabaseReader { reader.async { db in defer { try? db.commit() // Ignore commit error - releaseReader() + releaseReader(.reuse) } do { // https://www.sqlite.org/isolation.html diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 62f80006a..c69fc0c9d 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -281,7 +281,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { // Second async jump because that's how `Pool.async` has to be used. reader.async { db in value(.success(db)) - releaseReader() + releaseReader(.reuse) } } catch { value(.failure(error)) diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index 8c7e84994..d6303f4e7 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -75,7 +75,7 @@ final class Pool { /// Returns a tuple (element, release) /// Client must call release(), only once, after the element has been used. - func get() throws -> (element: T, release: () -> Void) { + func get() throws -> (element: T, release: (PoolCompletion) -> Void) { try barrierQueue.sync { itemsSemaphore.wait() itemsGroup.enter() @@ -91,7 +91,7 @@ final class Pool { return item } } - return (element: item.element, release: { self.release(item) }) + return (element: item.element, release: { self.release(item, completion: $0) }) } catch { itemsSemaphore.signal() itemsGroup.leave() @@ -107,7 +107,7 @@ final class Pool { /// /// - important: The `execute` argument is executed in a serial dispatch /// queue, so make sure you use the element asynchronously. - func asyncGet(_ execute: @escaping (Result<(element: T, release: () -> Void), Error>) -> Void) { + func asyncGet(_ execute: @escaping (Result<(element: T, release: (PoolCompletion) -> Void), Error>) -> Void) { // Inspired by https://khanlou.com/2016/04/the-GCD-handbook/ // > We wait on the semaphore in the serial queue, which means that // > we’ll have at most one blocked thread when we reach maximum @@ -122,16 +122,24 @@ final class Pool { /// Performs a synchronous block with an element. The element turns /// available after the block has executed. func get(block: (T) throws -> U) throws -> U { - let (element, release) = try get() - defer { release() } + let (element, completion) = try get() + defer { completion(.reuse) } return try block(element) } - private func release(_ item: Item) { - $items.update { _ in - // This is why Item is a class, not a struct: so that we can - // release it without having to find in it the items array. - item.isAvailable = true + private func release(_ item: Item, completion: PoolCompletion) { + $items.update { items in + switch completion { + case .reuse: + // This is why Item is a class, not a struct: so that we can + // release it without having to find in it the items array. + item.isAvailable = true + case .discard: + // Discard should be rare: perform lookup. + if let index = items.firstIndex(where: { $0 === item }) { + items.remove(at: index) + } + } } itemsSemaphore.signal() itemsGroup.leave() @@ -171,3 +179,10 @@ final class Pool { } } } + +enum PoolCompletion { + // Reuse the element + case reuse + // Discard the element + case discard +} diff --git a/Tests/GRDBTests/PoolTests.swift b/Tests/GRDBTests/PoolTests.swift index 7cb3b32a6..29c8fcaf7 100644 --- a/Tests/GRDBTests/PoolTests.swift +++ b/Tests/GRDBTests/PoolTests.swift @@ -14,7 +14,7 @@ class PoolTests: XCTestCase { // Get and release element let first = try pool.get() XCTAssertEqual(first.element, 1) - first.release() + first.release(.reuse) // Get recycled element let second = try pool.get() @@ -24,17 +24,46 @@ class PoolTests: XCTestCase { let third = try pool.get() XCTAssertEqual(third.element, 2) - // Release elements - second.release() - third.release() + // Reuse elements + second.release(.reuse) + third.release(.reuse) // Get and release recycled elements let fourth = try pool.get() XCTAssertEqual(fourth.element, 1) let fifth = try pool.get() XCTAssertEqual(fifth.element, 2) - fourth.release() - fifth.release() + fourth.release(.reuse) + fifth.release(.reuse) + } + + func testElementsCanBeDiscarded() throws { + let pool = makeCounterPool(maximumCount: 2) + + // Get and release element + let first = try pool.get() + XCTAssertEqual(first.element, 1) + first.release(.reuse) + + // Get recycled element + let second = try pool.get() + XCTAssertEqual(second.element, 1) + + // Get new element + let third = try pool.get() + XCTAssertEqual(third.element, 2) + + // Reuse second, discard third + second.release(.reuse) + third.release(.discard) + + // Get and release recycled elements + let fourth = try pool.get() + XCTAssertEqual(fourth.element, 1) + let fifth = try pool.get() + XCTAssertEqual(fifth.element, 3) + fourth.release(.reuse) + fifth.release(.reuse) } func testRemoveAll() throws { @@ -49,17 +78,17 @@ class PoolTests: XCTestCase { // removeAll is not locked by used elements pool.removeAll() - // Release elements - first.release() - second.release() + // Reuse elements + first.release(.reuse) + second.release(.reuse) // Get and release new elements let third = try pool.get() XCTAssertEqual(third.element, 3) let fourth = try pool.get() XCTAssertEqual(fourth.element, 4) - third.release() - fourth.release() + third.release(.reuse) + fourth.release(.reuse) } func testBarrierLocksElements() throws { @@ -85,7 +114,7 @@ class PoolTests: XCTestCase { let first = try! pool.get() element = first.element - first.release() + first.release(.reuse) expectation.fulfill() s3.signal() } @@ -93,7 +122,7 @@ class PoolTests: XCTestCase { // Assert that get() is blocked waitForExpectations(timeout: 1) - // Release barrier + // Reuse barrier s2.signal() // Wait for get() to complete @@ -121,8 +150,8 @@ class PoolTests: XCTestCase { // Assert that barrier is blocked waitForExpectations(timeout: 1) - // Release element - first.release() + // Reuse element + first.release(.reuse) // Wait for barrier to complete s.wait() @@ -130,7 +159,7 @@ class PoolTests: XCTestCase { // Get and release recycled element let second = try pool.get() XCTAssertEqual(second.element, 1) - second.release() + second.release(.reuse) } func testBarrierIsLockedByOneUsedElementOutOfTwo() throws { @@ -145,8 +174,8 @@ class PoolTests: XCTestCase { let second = try pool.get() XCTAssertEqual(second.element, 2) - // Release first element - first.release() + // Reuse first element + first.release(.reuse) let s = DispatchSemaphore(value: 0) DispatchQueue.global().async { @@ -158,8 +187,8 @@ class PoolTests: XCTestCase { // Assert that barrier is blocked waitForExpectations(timeout: 1) - // Release second element - second.release() + // Reuse second element + second.release(.reuse) // Wait for barrier to complete s.wait() @@ -167,7 +196,7 @@ class PoolTests: XCTestCase { // Get and release recycled element let third = try pool.get() XCTAssertEqual(third.element, 1) - third.release() + third.release(.reuse) } func testBarrierIsLockedByTwoUsedElementsOutOfTwo() throws { @@ -192,9 +221,9 @@ class PoolTests: XCTestCase { // Assert that barrier is blocked waitForExpectations(timeout: 1) - // Release elements - first.release() - second.release() + // Reuse elements + first.release(.reuse) + second.release(.reuse) // Wait for barrier to complete s.wait() @@ -202,7 +231,7 @@ class PoolTests: XCTestCase { // Get and release recycled element let third = try pool.get() XCTAssertEqual(third.element, 1) - third.release() + third.release(.reuse) } func testBarrierRemoveAll() throws { @@ -226,8 +255,8 @@ class PoolTests: XCTestCase { // Assert that barrier is blocked waitForExpectations(timeout: 1) - // Release element - first.release() + // Reuse element + first.release(.reuse) // Wait for barrier to complete s.wait() @@ -235,6 +264,6 @@ class PoolTests: XCTestCase { // Get and release new element let second = try pool.get() XCTAssertEqual(second.element, 2) - second.release() + second.release(.reuse) } } From 9b4d76ca37eae434023bd2406d9e2a6244ce9270 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 Nov 2022 08:53:30 +0100 Subject: [PATCH 32/69] Robustness: DatabaseSnapshotPool discards connections that have lost the snapshot --- GRDB/Core/DatabaseSnapshotPool.swift | 128 +++++++++++------- .../GRDBTests/DatabaseSnapshotPoolTests.swift | 41 ++++++ 2 files changed, 122 insertions(+), 47 deletions(-) diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index c69fc0c9d..252174b87 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -5,7 +5,6 @@ // If we create a new pool of connections, we avoid this problem. And we can // simplify the management of shared cache (drop all cache-merging code) -#warning("TODO: restore or don't reuse connections that have lost their transaction") /// A database connection that allows concurrent accesses to an unchanging /// database content, as it existed at the moment the snapshot was created. /// @@ -85,6 +84,13 @@ public final class DatabaseSnapshotPool { /// It is constant, until close() sets it to nil. private var readerPool: Pool? + /// The WAL snapshot + private let walSnapshot: WALSnapshot + + /// A connection that prevents checkpoints and keeps the WAL snapshot valid. + /// It is never used. + private let snapshotHolder: DatabaseQueue + /// Creates a snapshot of the database. /// /// For example: @@ -128,16 +134,26 @@ public final class DatabaseSnapshotPool { GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1") - var walSnapshot: WALSnapshot? - configuration.prepareDatabase { db in - // Open transaction + // Acquire and hold WAL snapshot + let walSnapshot = try db.isolated(readOnly: true) { + try WALSnapshot(db) + } + var holderConfig = Configuration() + holderConfig.allowsUnsafeTransactions = true + snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig) + try snapshotHolder.inDatabase { db in try db.beginTransaction(.deferred) - - // Acquire snapshot isolation try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") - - // Open snapshot - let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot!.sqliteSnapshot) + let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot) + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code) + } + } + + configuration.prepareDatabase { db in + try db.beginTransaction(.deferred) + try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") + let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot) guard code == SQLITE_OK else { throw DatabaseError(resultCode: code) } @@ -145,6 +161,7 @@ public final class DatabaseSnapshotPool { self.configuration = configuration self.path = db.path + self.walSnapshot = walSnapshot var readerCount = 0 readerPool = Pool( @@ -158,14 +175,6 @@ public final class DatabaseSnapshotPool { defaultLabel: "GRDB.DatabaseSnapshotPool", purpose: "snapshot.\(readerCount)") }) - - // Get WAL snapshot - walSnapshot = try db.isolated(readOnly: true) { - try WALSnapshot(db) - } - - // Create first connection that will keep the WALSnapshot alive. - try readerPool!.get { _ in } } /// Creates a snapshot of the database. @@ -193,25 +202,28 @@ public final class DatabaseSnapshotPool { // Snapshot keeps a long-lived transaction configuration.allowsUnsafeTransactions = true - var walSnapshot: WALSnapshot? - configuration.prepareDatabase { db in - // Open transaction + // Acquire and hold WAL snapshot + var holderConfig = Configuration() + holderConfig.allowsUnsafeTransactions = true + snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig) + let walSnapshot = try snapshotHolder.inDatabase { db in try db.beginTransaction(.deferred) - - // Acquire snapshot isolation try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") - - // Open snapshot - if let walSnapshot { // nil on first connection created below - let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot) - guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code) - } + return try WALSnapshot(db) + } + + configuration.prepareDatabase { db in + try db.beginTransaction(.deferred) + try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") + let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot) + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code) } } self.configuration = configuration self.path = path + self.walSnapshot = walSnapshot var readerCount = 0 readerPool = Pool( @@ -225,12 +237,6 @@ public final class DatabaseSnapshotPool { defaultLabel: "GRDB.DatabaseSnapshotPool", purpose: "snapshot.\(readerCount)") }) - - walSnapshot = try readerPool!.get { reader in - try reader.sync { db in - try WALSnapshot(db) - } - } } } @@ -257,9 +263,20 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { guard let readerPool else { throw DatabaseError.connectionIsClosed() } - return try readerPool.get { reader in - try reader.sync { db in - return try value(db) + + let (reader, releaseReader) = try readerPool.get() + var completion: PoolCompletion! + defer { + releaseReader(completion) + } + return try reader.sync { db in + do { + let value = try value(db) + completion = poolCompletion(db) + return value + } catch { + completion = poolCompletion(db) + throw error } } } @@ -281,7 +298,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { // Second async jump because that's how `Pool.async` has to be used. reader.async { db in value(.success(db)) - releaseReader(.reuse) + releaseReader(self.poolCompletion(db)) } } catch { value(.failure(error)) @@ -296,16 +313,16 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { if let reader = currentReader { - return try reader.reentrantSync(value) - } else { - guard let readerPool else { - throw DatabaseError.connectionIsClosed() - } - return try readerPool.get { reader in - try reader.sync { db in - return try value(db) + return try reader.reentrantSync { db in + let result = try value(db) + if snapshotIsLost(db) { + throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.") } + return result } + } else { + /// There is no unsafe access to a snapshot. + return try read(value) } } @@ -343,5 +360,22 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { // in the pool, and thus still relevant for our check: return readers.first { $0.onValidQueue } } + + private func poolCompletion(_ db: Database) -> PoolCompletion { + snapshotIsLost(db) ? .discard : .reuse + } + + private func snapshotIsLost(_ db: Database) -> Bool { + do { + let currentSnapshot = try WALSnapshot(db) + if currentSnapshot.compare(walSnapshot) == 0 { + return false + } else { + return true + } + } catch { + return true + } + } } #endif diff --git a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift index 8716e2a8f..d62177ab5 100644 --- a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift @@ -115,6 +115,47 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { try XCTAssertEqual(dbPool.read(counter.value), 2) } + func test_discarded_transaction() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 + try dbPool.write(counter.increment) // 2 + + try snapshot.read { db in + try XCTAssertEqual(counter.value(db), 1) + try db.commit() // lose snapshot + try XCTAssertEqual(counter.value(db), 2) + } + + // Try to invalidate the snapshot + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.truncate) } + + // Snapshot is not lost, and previous connection is not reused. + try XCTAssertEqual(snapshot.read(counter.value), 1) + } + + func test_replaced_transaction() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 + try dbPool.write(counter.increment) // 2 + + try snapshot.read { db in + try XCTAssertEqual(counter.value(db), 1) + try db.commit() // lose snapshot + try db.beginTransaction() + try XCTAssertEqual(counter.value(db), 2) + } + + // Try to invalidate the snapshot + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.truncate) } + + // Snapshot is not lost, and previous connection is not reused. + try XCTAssertEqual(snapshot.read(counter.value), 1) + } + func test_concurrent_read() throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) // 0 From fcf8ac43b793c5d878249d5d953590a06029a3ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 Nov 2022 12:41:15 +0100 Subject: [PATCH 33/69] Delete obsolete comment --- GRDB/Core/DatabaseSnapshotPool.swift | 4 ---- 1 file changed, 4 deletions(-) diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 252174b87..793581304 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -1,10 +1,6 @@ // swiftlint:disable:next line_length #if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) #else -// Sharing connections with DatabasePool creates a problem with reentrant access. -// If we create a new pool of connections, we avoid this problem. And we can -// simplify the management of shared cache (drop all cache-merging code) - /// A database connection that allows concurrent accesses to an unchanging /// database content, as it existed at the moment the snapshot was created. /// From 0ba3dff901c64897f7b965f245a319ef2c444f25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 Nov 2022 12:46:12 +0100 Subject: [PATCH 34/69] Rewrite availability check for WAL snapshots Also, enable WAL snapshots with SQLCipher, if SQLITE_ENABLE_SNAPSHOT is set. --- GRDB/Core/DatabasePool.swift | 3 +- GRDB/Core/DatabaseSnapshotPool.swift | 3 +- GRDB/Core/WALSnapshot.swift | 33 +++++++--------- .../DatabaseReaderReadPublisherTests.swift | 18 +++------ .../DatabaseAbortedTransactionTests.swift | 6 +-- .../DatabaseConfigurationTests.swift | 6 +-- Tests/GRDBTests/DatabaseReaderTests.swift | 39 +++++++------------ .../GRDBTests/DatabaseSnapshotPoolTests.swift | 3 +- .../ValueObservationPrintTests.swift | 12 ++---- Tests/GRDBTests/ValueObservationTests.swift | 23 ++++++----- 10 files changed, 56 insertions(+), 90 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 1e4231929..e47c82c49 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -885,8 +885,7 @@ extension DatabasePool { } // swiftlint:disable:next line_length -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) /// Creates a database snapshot that allows concurrent accesses to an /// unchanging database content, as it exists at the moment the snapshot /// is created. diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 793581304..d2f992afe 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -1,6 +1,5 @@ // swiftlint:disable:next line_length -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) /// A database connection that allows concurrent accesses to an unchanging /// database content, as it existed at the moment the snapshot was created. /// diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index 2d25f77e1..eed7b20d2 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -20,24 +20,11 @@ /// /// See . final class WALSnapshot: Sendable { - // Xcode 14 ships with a macOS SDK that misses snapshot support. - // Xcode 14.1 ships with a macOS SDK that has snapshot support. - // This is the meaning of (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) - // - // We can't provide snapshots api for SQLCipher, since we'd have linker - // errors if they are not enabled. + // Xcode 14 (Swift 5.7) ships with a macOS SDK that misses snapshot support. + // Xcode 14.1 (Swift 5.7.1) ships with a macOS SDK that has snapshot support. + // This is the meaning of (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))) // swiftlint:disable:next line_length -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) - static let available = false - - init(_ db: Database) throws { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "snapshots are not available") - } - - func compare(_ other: WALSnapshot) -> CInt { - preconditionFailure("snapshots are not available") - } -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) static let available = true let sqliteSnapshot: UnsafeMutablePointer @@ -70,5 +57,15 @@ final class WALSnapshot: Sendable { } // swiftlint:disable:next line_length -#endif // (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + static let available = false + + init(_ db: Database) throws { + throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "snapshots are not available") + } + + func compare(_ other: WALSnapshot) -> CInt { + preconditionFailure("snapshots are not available") + } +#endif } diff --git a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift index f039aa846..1f002f238 100644 --- a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift @@ -44,8 +44,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { 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() } -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() } #endif } @@ -150,8 +149,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { 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() } -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshotPool() } #endif } @@ -191,8 +189,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { 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() } -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() } #endif } @@ -232,8 +229,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { 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() } -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() } #endif } @@ -274,8 +270,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { 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() } -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() } #endif } @@ -303,8 +298,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { 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() } -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshotPool() } #endif } diff --git a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift index 975d18634..602e8705c 100644 --- a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift +++ b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift @@ -40,8 +40,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -86,8 +85,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(makeDatabasePool().makeSnapshotPool()) #endif } diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index 4949ace63..b0d4d2714 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -27,8 +27,7 @@ class DatabaseConfigurationTests: GRDBTestCase { try pool.makeSnapshot().read { _ in } XCTAssertEqual(connectionCount, 5) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try pool.makeSnapshotPool().read { _ in } XCTAssertEqual(connectionCount, 6) #endif @@ -75,8 +74,7 @@ class DatabaseConfigurationTests: GRDBTestCase { XCTFail("Expected TestError") } catch is TestError { } -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) do { error = TestError() _ = try pool.makeSnapshotPool() diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index eae59ecbc..fec7c02f5 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -28,8 +28,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue())) try test(setup(makeDatabasePool())) try test(setup(makeDatabasePool()).makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(setup(makeDatabasePool()).makeSnapshotPool()) #endif } @@ -52,8 +51,7 @@ class DatabaseReaderTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) try await test(setup(makeDatabasePool()).makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try await test(setup(makeDatabasePool()).makeSnapshotPool()) #endif } @@ -72,8 +70,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -93,8 +90,7 @@ class DatabaseReaderTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) try await test(makeDatabasePool().makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try await test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -118,8 +114,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue())) try test(setup(makeDatabasePool())) try test(setup(makeDatabasePool()).makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(setup(makeDatabasePool()).makeSnapshotPool()) #endif } @@ -142,8 +137,7 @@ class DatabaseReaderTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) try await test(setup(makeDatabasePool()).makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try await test(setup(makeDatabasePool()).makeSnapshotPool()) #endif } @@ -167,8 +161,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue())) try test(setup(makeDatabasePool())) try test(setup(makeDatabasePool()).makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(setup(makeDatabasePool()).makeSnapshotPool()) #endif } @@ -188,8 +181,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -236,8 +228,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -266,8 +257,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -287,8 +277,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -308,8 +297,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -336,8 +324,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue(configuration: Configuration()))) try test(setup(makeDatabasePool(configuration: Configuration()))) try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshotPool()) #endif } diff --git a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift index d62177ab5..eb66ff237 100644 --- a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift @@ -1,5 +1,4 @@ -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) import XCTest import GRDB diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index b8cc04778..d5085dcc9 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -54,8 +54,7 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabaseQueue(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool()) #endif } @@ -92,8 +91,7 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabaseQueue(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool()) #endif } @@ -131,8 +129,7 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabaseQueue(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool()) #endif } @@ -170,8 +167,7 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabaseQueue(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool()) #endif } diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 4d618aa71..3a2a7d49a 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -421,13 +421,13 @@ class ValueObservationTests: GRDBTestCase { } let expectedCounts: [Int] - #if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) - // Optimization not available - expectedCounts = [0, 0, 1] - #else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) // Optimization available expectedCounts = [0, 1] - #endif +#else + // Optimization not available + expectedCounts = [0, 0, 1] +#endif let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = expectedCounts.count @@ -471,13 +471,13 @@ class ValueObservationTests: GRDBTestCase { } let expectedCounts: [Int] - #if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) - // Optimization not available - expectedCounts = [0, 0, 1] - #else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) // Optimization available expectedCounts = [0, 1] - #endif +#else + // Optimization not available + expectedCounts = [0, 0, 1] +#endif let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = expectedCounts.count @@ -498,8 +498,7 @@ class ValueObservationTests: GRDBTestCase { // MARK: - Snapshot Observation -#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) -#else +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) func testDatabaseSnapshotPoolObservation() throws { let dbPool = try makeDatabasePool() try dbPool.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } From dc43607921caa0b9854b5035493024467952e692 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 Nov 2022 13:14:22 +0100 Subject: [PATCH 35/69] Cleanup --- .../ValueConcurrentObserver.swift | 28 +++++++------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/GRDB/ValueObservation/ValueConcurrentObserver.swift b/GRDB/ValueObservation/ValueConcurrentObserver.swift index dc3c3daa1..63c2f4df1 100644 --- a/GRDB/ValueObservation/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/ValueConcurrentObserver.swift @@ -250,16 +250,6 @@ extension ValueConcurrentObserver { return AnyDatabaseCancellable(self) } - private func startObservation(_ writerDB: Database, observedRegion: DatabaseRegion) { - observationState.region = observedRegion - assert(observationState.isModified == false) - writerDB.add(transactionObserver: self, extent: .observerLifetime) - } -} - -// MARK: - Starting the Observation (with SQLITE_ENABLE_SNAPSHOT) - -extension ValueConcurrentObserver { /// Synchronously starts the observation, and returns the initial value. /// /// Unlike `asyncStart()`, this method does not notify the initial value or error. @@ -271,11 +261,9 @@ extension ValueConcurrentObserver { // // Fetch value & tracked region in a synchronous way. // - // TODO: we currently perform the initial read from a snapshot, because + // We perform the initial read from a DatabaseSnapshot, because // it is a handy way to keep a read transaction open until we grab a - // write access, and compare the database versions. The problem is that - // we do not control the number of created shapshots: we should instead - // use a reader from the pool. + // write access, and compare the database versions. let initialSnapshot = try databaseAccess.dbPool.makeSnapshot() let (fetchedValue, initialRegion, initialWALSnapshot) = try initialSnapshot.read { db -> (Reducer.Fetched, DatabaseRegion, WALSnapshot?) in @@ -322,11 +310,9 @@ extension ValueConcurrentObserver { // without having to wait for an eventual long-running write // transaction to complete. // - // TODO: we currently perform the initial read from a snapshot, because + // We perform the initial read from a DatabaseSnapshot, because // it is a handy way to keep a read transaction open until we grab a - // write access, and compare the database versions. The problem is that - // we do not control the number of created shapshots: we should instead - // use a reader from the pool. + // write access, and compare the database versions. do { let initialSnapshot = try databaseAccess.dbPool.makeSnapshot() initialSnapshot.asyncRead { dbResult in @@ -477,6 +463,12 @@ extension ValueConcurrentObserver { } } } + + private func startObservation(_ writerDB: Database, observedRegion: DatabaseRegion) { + observationState.region = observedRegion + assert(observationState.isModified == false) + writerDB.add(transactionObserver: self, extent: .observerLifetime) + } } // MARK: - Observing Database Transactions From 2dce8d533ea8169f47e7d58dd69fdc07d53359c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 Nov 2022 13:33:12 +0100 Subject: [PATCH 36/69] Project organization --- GRDB.xcodeproj/project.pbxproj | 18 +++++++---- .../ValueConcurrentObserver.swift | 0 .../ValueWriteOnlyObserver.swift | 0 .../{ValueReducer => Reducers}/Fetch.swift | 0 .../{ValueReducer => Reducers}/Map.swift | 0 .../RemoveDuplicates.swift | 0 .../{ValueReducer => Reducers}/Trace.swift | 0 .../ValueReducer.swift | 0 GRDBCustom.xcodeproj/project.pbxproj | 30 ++++++++++++------- 9 files changed, 32 insertions(+), 16 deletions(-) rename GRDB/ValueObservation/{ => Observers}/ValueConcurrentObserver.swift (100%) rename GRDB/ValueObservation/{ => Observers}/ValueWriteOnlyObserver.swift (100%) rename GRDB/ValueObservation/{ValueReducer => Reducers}/Fetch.swift (100%) rename GRDB/ValueObservation/{ValueReducer => Reducers}/Map.swift (100%) rename GRDB/ValueObservation/{ValueReducer => Reducers}/RemoveDuplicates.swift (100%) rename GRDB/ValueObservation/{ValueReducer => Reducers}/Trace.swift (100%) rename GRDB/ValueObservation/{ValueReducer => Reducers}/ValueReducer.swift (100%) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index f62751351..089a9fd2a 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -910,11 +910,10 @@ children = ( 563082E32430B6BE00C14A05 /* DatabaseCancellable.swift */, 560233C32724234F00529DF3 /* SharedValueObservation.swift */, - 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */, 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */, 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */, - 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */, - 56AACAA022ACEC9700A40F2A /* ValueReducer */, + 566BD72F2927AFC300595649 /* Observers */, + 56AACAA022ACEC9700A40F2A /* Reducers */, ); path = ValueObservation; sourceTree = ""; @@ -1236,6 +1235,15 @@ path = Utils; sourceTree = ""; }; + 566BD72F2927AFC300595649 /* Observers */ = { + isa = PBXGroup; + children = ( + 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */, + 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */, + ); + path = Observers; + sourceTree = ""; + }; 5674A7251F30A8EF0095F066 /* FetchableRecord */ = { isa = PBXGroup; children = ( @@ -1500,7 +1508,7 @@ path = Record; sourceTree = ""; }; - 56AACAA022ACEC9700A40F2A /* ValueReducer */ = { + 56AACAA022ACEC9700A40F2A /* Reducers */ = { isa = PBXGroup; children = ( 56AACAA722ACED7100A40F2A /* Fetch.swift */, @@ -1509,7 +1517,7 @@ 563B8F91249E6171007A48C9 /* Trace.swift */, 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */, ); - path = ValueReducer; + path = Reducers; sourceTree = ""; }; 56DAA2C41DE99D8D006E10C8 /* Cursor */ = { diff --git a/GRDB/ValueObservation/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift similarity index 100% rename from GRDB/ValueObservation/ValueConcurrentObserver.swift rename to GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift diff --git a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift similarity index 100% rename from GRDB/ValueObservation/ValueWriteOnlyObserver.swift rename to GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift diff --git a/GRDB/ValueObservation/ValueReducer/Fetch.swift b/GRDB/ValueObservation/Reducers/Fetch.swift similarity index 100% rename from GRDB/ValueObservation/ValueReducer/Fetch.swift rename to GRDB/ValueObservation/Reducers/Fetch.swift diff --git a/GRDB/ValueObservation/ValueReducer/Map.swift b/GRDB/ValueObservation/Reducers/Map.swift similarity index 100% rename from GRDB/ValueObservation/ValueReducer/Map.swift rename to GRDB/ValueObservation/Reducers/Map.swift diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift similarity index 100% rename from GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift rename to GRDB/ValueObservation/Reducers/RemoveDuplicates.swift diff --git a/GRDB/ValueObservation/ValueReducer/Trace.swift b/GRDB/ValueObservation/Reducers/Trace.swift similarity index 100% rename from GRDB/ValueObservation/ValueReducer/Trace.swift rename to GRDB/ValueObservation/Reducers/Trace.swift diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/Reducers/ValueReducer.swift similarity index 100% rename from GRDB/ValueObservation/ValueReducer/ValueReducer.swift rename to GRDB/ValueObservation/Reducers/ValueReducer.swift diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 7c3bb40ed..3b15a8f99 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -92,7 +92,6 @@ 564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; 564B3D72239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; }; - 564CE43C21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */; }; 564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; }; 564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; }; 564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */; }; @@ -172,6 +171,8 @@ 566B91251FA4CF810012D5B0 /* Database+Schema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91221FA4CF810012D5B0 /* Database+Schema.swift */; }; 566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; }; 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; + 566BD7332927AFD600595649 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */; }; + 566BD7342927AFD600595649 /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */; }; 566BE7152342541F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7132342541F00A8254B /* LockedBox.swift */; }; 566DDE12288D76400000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE11288D76400000DCFB /* Fixits.swift */; }; 5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; @@ -190,7 +191,6 @@ 5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; 5676FBAA22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */; }; 56781B08243F7B5300650A83 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 5679533927E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */; }; 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; 567E420A242AB3CB00CAAD2C /* FailureTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */; }; @@ -524,7 +524,6 @@ 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = ""; }; - 564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = ""; }; 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; @@ -608,6 +607,8 @@ 566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = ""; }; 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; }; 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; + 566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = ""; }; + 566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.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 = ""; }; @@ -631,7 +632,6 @@ 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = ""; }; 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDB-Bridging.h"; path = "SQLiteCustom/GRDB-Bridging.h"; sourceTree = ""; }; - 5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; 567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailureTestCase.swift; sourceTree = ""; }; @@ -922,11 +922,10 @@ children = ( 563082E82430B6CD00C14A05 /* DatabaseCancellable.swift */, 560233D027243A9100529DF3 /* SharedValueObservation.swift */, - 564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */, 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */, 563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */, - 5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */, - 56C0538822ACEECD0029D27D /* ValueReducer */, + 566BD7302927AFD600595649 /* Observers */, + 56C0538822ACEECD0029D27D /* Reducers */, ); path = ValueObservation; sourceTree = ""; @@ -1247,6 +1246,15 @@ path = Utils; sourceTree = ""; }; + 566BD7302927AFD600595649 /* Observers */ = { + isa = PBXGroup; + children = ( + 566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */, + 566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */, + ); + path = Observers; + sourceTree = ""; + }; 5674A7251F30A8EF0095F066 /* FetchableRecord */ = { isa = PBXGroup; children = ( @@ -1496,7 +1504,7 @@ path = Record; sourceTree = ""; }; - 56C0538822ACEECD0029D27D /* ValueReducer */ = { + 56C0538822ACEECD0029D27D /* Reducers */ = { isa = PBXGroup; children = ( 56C0538A22ACEECD0029D27D /* Fetch.swift */, @@ -1505,7 +1513,7 @@ 563B8F99249E74E5007A48C9 /* Trace.swift */, 56C0538C22ACEECD0029D27D /* ValueReducer.swift */, ); - path = ValueReducer; + path = Reducers; sourceTree = ""; }; 56DAA2C41DE99D8D006E10C8 /* Cursor */ = { @@ -1831,8 +1839,8 @@ files = ( 5656A8712295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */, 56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */, + 566BD7332927AFD600595649 /* ValueConcurrentObserver.swift in Sources */, 56158786288D878500A67323 /* Optional.swift in Sources */, - 5679533927E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */, 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */, F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */, 563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */, @@ -1943,12 +1951,12 @@ 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, 56FBFED62210731100945324 /* SQLRequest.swift in Sources */, - 564CE43C21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */, 5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, 56D110EB28AFC90800E64463 /* MutablePersistableRecord+Insert.swift in Sources */, 5656A86F2295BD56001FF3FF /* Association.swift in Sources */, 56D110F728AFC90800E64463 /* MutablePersistableRecord+Update.swift in Sources */, + 566BD7342927AFD600595649 /* ValueWriteOnlyObserver.swift in Sources */, 56D110ED28AFC90800E64463 /* PersistableRecord+Insert.swift in Sources */, 563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */, 564D4F93261E1D3300F55856 /* CaseInsensitiveIdentifier.swift in Sources */, From d4cefc984f572cfe454ad5d46c50bbd4707af631 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 Nov 2022 13:33:22 +0100 Subject: [PATCH 37/69] Update documentation index --- GRDB/Documentation.docc/Documentation.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/GRDB/Documentation.docc/Documentation.md b/GRDB/Documentation.docc/Documentation.md index fe2c23bf4..d540f137e 100644 --- a/GRDB/Documentation.docc/Documentation.md +++ b/GRDB/Documentation.docc/Documentation.md @@ -4,8 +4,15 @@ A toolkit for SQLite databases, with a focus on application development ## Overview -GRDB provides raw access to SQL and advanced SQLite features, because one sometimes enjoys a sharp tool. It has robust concurrency primitives, so that multi-threaded applications can efficiently use their databases. It grants your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to. +Use GRDB to save your application’s permanent data into SQLite databases. +The library provides raw access to SQL and advanced SQLite features, because one sometimes enjoys a sharp tool. + +It has robust concurrency primitives, so that multi-threaded applications can efficiently use their databases. + +It grants your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to. + +Compared to [SQLite.swift](http://github.com/stephencelis/SQLite.swift) or [FMDB](http://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications. ## Topics From 131f414a757ce810ab9381298a72b709f4afa56d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 Nov 2022 13:49:28 +0100 Subject: [PATCH 38/69] Enhance DatabaseSchema.md --- GRDB/Documentation.docc/DatabaseSchema.md | 24 ++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index de824bb0e..003b10477 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -4,9 +4,7 @@ Learn how to define the database schema. ## Overview -SQLite directly supports a [set of schema alterations](https://www.sqlite.org/lang.html). Many of them are available as Swift methods such as ``Database/create(table:options:body:)``, ``Database/alter(table:body:)``, listed below. - -You can directly create tables when you open a database, as below: +You can directly define the database schema when you open a database, as below: ```swift let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") @@ -20,14 +18,22 @@ try dbQueue.write { db in } ``` -But you should prefer wrapping your schema changes in when you plan to upgrade the database schema in future versions of your app. +But you should prefer wrapping all your schema changes in , when you plan to upgrade the database schema in future versions of your app. -> Tip: When modifying the database schema, prefer Swift APIs over raw SQL queries. This helps the compiler check if features are available on the SQLite version that ships on the target operating system. For example: +## Schema Alterations + +SQLite directly supports a [set of schema alterations](https://www.sqlite.org/lang.html). + +Many of them are available as Swift methods such as ``Database/create(table:options:body:)``, listed below. + +When the schema alteration you need is not available as a Swift method, use a raw SQL query (for creating views or triggers, for example). + +When you need to modify a table in a way that is not directly supported by SQLite, or not available on your target operating system, you will need to recreate the database table. See for the detailed procedure. + +> Tip: Prefer Swift methods over raw SQL queries. This helps the compiler check if features are available on the SQLite version that ships on the target operating system. For example: > -> - Dropping a table column requires SQLite 3.35+ (iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0). -> - [Strict tables](https://www.sqlite.org/stricttables.html) require SQLite 3.37+ (iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5). -> -> When you need to modify a table in a way that is not directly supported by SQLite, or not available on your target operating system, you will need to recreate the database table. See for the detailed procedure. +> - Dropping a table column requires SQLite 3.35+ (iOS 15.0, macOS 12.0). +> - [Strict tables](https://www.sqlite.org/stricttables.html) require SQLite 3.37+ (iOS 15.4, macOS 12.4). ## Topics From e8f1e7695856ba3bc5806e825c0517d7a5e83b31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 Nov 2022 17:45:51 +0100 Subject: [PATCH 39/69] Enhance documentation --- GRDB/Documentation.docc/Documentation.md | 4 ++-- GRDB/Documentation.docc/QueryInterface.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB/Documentation.docc/Documentation.md b/GRDB/Documentation.docc/Documentation.md index d540f137e..ad7eac38a 100644 --- a/GRDB/Documentation.docc/Documentation.md +++ b/GRDB/Documentation.docc/Documentation.md @@ -28,11 +28,11 @@ Compared to [SQLite.swift](http://github.com/stephencelis/SQLite.swift) or [FMDB - - -### Record Types and the Query Interface +### Records and the Query Interface - -### Database Observation +### Responding to Database Changes - diff --git a/GRDB/Documentation.docc/QueryInterface.md b/GRDB/Documentation.docc/QueryInterface.md index 0c7bcd7ad..f06c18af7 100644 --- a/GRDB/Documentation.docc/QueryInterface.md +++ b/GRDB/Documentation.docc/QueryInterface.md @@ -1,6 +1,6 @@ -# Record Types and the Query Interface +# Records and the Query Interface -Record types and the query interface build SQL queries for you +Record types and the query interface build SQL queries for you. ## Topics From 392e9e447df8f68a0d73f94d69f4c1ae343c841c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 23 Nov 2022 18:32:57 +0100 Subject: [PATCH 40/69] Shared in-memory databases --- CHANGELOG.md | 3 +- GRDB/Core/DatabaseQueue.swift | 38 ++++++++++++++--- .../DatabaseQueueInMemoryTests.swift | 42 +++++++++++++++---- 3 files changed, 69 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e15ce28a..d65ffb4b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -107,7 +107,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: `DatabaseReader.configuration.maximumReaderCount` returns the effective capacity for concurrent reads, so that application code can adapt when needed. - **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime. - **New**: `Database.registerAccess(to:)` has `ValueObservation` track a region. This helps building optimized observations of a constant database region with `ValueObservation.trackingConstantRegion(_:)`. -- **New**: [#1293](https://github.com/groue/GRDB.swift/pull/1293) by [@groue](https://github.com/groue): Enable concurrent reads from a WAL snapshot; +- **New**: Open several connections to the same in-memory databases with `DatabaseQueue(named:)`. +- **New**: [#1293](https://github.com/groue/GRDB.swift/pull/1293) by [@groue](https://github.com/groue): Enable concurrent reads from a WAL snapshot. ## 6.3.1 diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index a7a6bba45..1e8268467 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -35,7 +35,7 @@ import UIKit /// /// ### Creating a DatabaseQueue /// -/// - ``init(configuration:)`` +/// - ``init(named:configuration:)`` /// - ``init(path:configuration:)`` /// /// ### Accessing the Database @@ -105,13 +105,41 @@ public final class DatabaseQueue { /// Opens an in-memory SQLite database. /// - /// The database memory is released when the database queue - /// gets deallocated. + /// To create an independent in-memory database, don't pass any name. The + /// database memory is released when the database queue is deallocated: /// + /// ```swift + /// // An independent in-memory database + /// let dbQueue = try DatabaseQueue() + /// ``` + /// + /// When you need to open several connections to the same in-memory + /// database, give it a name: + /// + /// ```swift + /// // A shared in-memory database + /// let dbQueue = try DatabaseQueue(named: "myDatabase") + /// ``` + /// + /// In this case, the database is automatically deleted and memory is + /// reclaimed when the last connection to the database of the given + /// name closes. + /// + /// Related SQLite documentation: + /// + /// - parameter name: When nil, an independent in-memory database opens. + /// Otherwise, the shared in-memory database of the given name opens. /// - parameter configuration: A configuration. - public init(configuration: Configuration = Configuration()) throws { + public init(named name: String? = nil, configuration: Configuration = Configuration()) throws { + let path: String + if let name { + path = "file:\(name)?mode=memory&cache=shared" + } else { + path = ":memory:" + } + writer = try SerializedDatabase( - path: ":memory:", + path: path, configuration: configuration, defaultLabel: "GRDB.DatabaseQueue") } diff --git a/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift b/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift index 6de662006..2c20ff867 100644 --- a/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift +++ b/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift @@ -1,16 +1,42 @@ import XCTest import GRDB -class DatabaseQueueInMemoryTests : GRDBTestCase -{ - func testInMemoryDatabase() throws { - let dbQueue = try DatabaseQueue() - try dbQueue.inTransaction { db in +class DatabaseQueueInMemoryTests : GRDBTestCase { + func test_independent_in_memory_database() throws { + let baz = try DatabaseQueue().write { db in try db.execute(sql: "CREATE TABLE foo (bar TEXT)") try db.execute(sql: "INSERT INTO foo (bar) VALUES ('baz')") - let baz = try String.fetchOne(db, sql: "SELECT bar FROM foo")! - XCTAssertEqual(baz, "baz") - return .rollback + return try String.fetchOne(db, sql: "SELECT bar FROM foo")! + } + XCTAssertEqual(baz, "baz") + } + + func test_independent_in_memory_databases_are_independent() throws { + try DatabaseQueue().write { db in + try db.execute(sql: "CREATE TABLE foo (bar TEXT)") + } + + try XCTAssertFalse(DatabaseQueue().read { try $0.tableExists("foo") }) + } + + func test_shared_in_memory_database() throws { + let baz = try DatabaseQueue(named: "dbA").write { db in + try db.execute(sql: "CREATE TABLE foo (bar TEXT)") + try db.execute(sql: "INSERT INTO foo (bar) VALUES ('baz')") + return try String.fetchOne(db, sql: "SELECT bar FROM foo")! + } + XCTAssertEqual(baz, "baz") + } + + func test_shared_in_memory_databases_are_shared_by_name() throws { + let dbA = try DatabaseQueue(named: "dbA") + try dbA.write { db in + try db.execute(sql: "CREATE TABLE foo (bar TEXT)") + } + + try withExtendedLifetime(dbA) { + try XCTAssertTrue(DatabaseQueue(named: "dbA").read { try $0.tableExists("foo") }) + try XCTAssertFalse(DatabaseQueue(named: "dbB").read { try $0.tableExists("foo") }) } } } From 10596e17bf5d5dcf7d46e8ad1b0c6b16cc9fb464 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 23 Nov 2022 19:42:12 +0100 Subject: [PATCH 41/69] Cleanup snapshot configurations --- GRDB/Core/DatabasePool.swift | 4 +-- GRDB/Core/DatabaseSnapshot.swift | 33 +++++++++++++++++++----- GRDB/Core/DatabaseSnapshotPool.swift | 38 ++++++++++++++++++++-------- 3 files changed, 56 insertions(+), 19 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index e47c82c49..5c5afa1d1 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -186,7 +186,7 @@ public final class DatabasePool { /// Returns a Configuration suitable for readonly connections on a /// WAL database. - static func readerConfiguration(_ configuration: Configuration) -> Configuration { + private static func readerConfiguration(_ configuration: Configuration) -> Configuration { var configuration = configuration configuration.readonly = true @@ -195,7 +195,7 @@ public final class DatabasePool { // Other transaction kinds are forbidden by SQLite in read-only connections. configuration.defaultTransactionKind = .deferred - // https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode + // // > But there are some obscure cases where a query against a WAL-mode // > database can return SQLITE_BUSY, so applications should be prepared // > for that happenstance. diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index e43168bb4..9ab92e592 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -82,12 +82,14 @@ public final class DatabaseSnapshot { reader.path } - init(path: String, configuration: Configuration, defaultLabel: String, purpose: String? = nil) throws { - var configuration = configuration - // DatabaseSnapshot can't perform parallel reads - configuration.maximumReaderCount = 1 - // Snapshot keeps a long-lived transaction - configuration.allowsUnsafeTransactions = true + init( + path: String, + configuration: Configuration, + defaultLabel: String = "GRDB.DatabaseSnapshot", + purpose: String? = nil) + throws + { + let configuration = Self.configure(configuration) reader = try SerializedDatabase( path: path, @@ -110,6 +112,25 @@ public final class DatabaseSnapshot { try? db.commit() } } + + private static func configure(_ configuration: Configuration) -> Configuration { + var configuration = configuration + + // DatabaseSnapshot can't perform parallel reads. + configuration.maximumReaderCount = 1 + + // DatabaseSnapshot is read-only. + configuration.readonly = true + + // DatabaseSnapshot uses deferred transactions by default. + // Other transaction kinds are forbidden by SQLite in read-only connections. + configuration.defaultTransactionKind = .deferred + + // DatabaseSnapshot keeps a long-lived transaction. + configuration.allowsUnsafeTransactions = true + + return configuration + } } extension DatabaseSnapshot: DatabaseSnapshotReader { diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index d2f992afe..c084188f1 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -122,12 +122,7 @@ public final class DatabaseSnapshotPool { /// `db` is used. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public init(_ db: Database, configuration: Configuration? = nil) throws { - var configuration = DatabasePool.readerConfiguration(configuration ?? db.configuration) - - // Snapshot keeps a long-lived transaction - configuration.allowsUnsafeTransactions = true - - GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1") + var configuration = Self.configure(configuration ?? db.configuration) // Acquire and hold WAL snapshot let walSnapshot = try db.isolated(readOnly: true) { @@ -191,11 +186,7 @@ public final class DatabaseSnapshotPool { /// - configuration: A configuration. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public init(path: String, configuration: Configuration = Configuration()) throws { - var configuration = DatabasePool.readerConfiguration(configuration) - GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1") - - // Snapshot keeps a long-lived transaction - configuration.allowsUnsafeTransactions = true + var configuration = Self.configure(configuration) // Acquire and hold WAL snapshot var holderConfig = Configuration() @@ -233,6 +224,31 @@ public final class DatabaseSnapshotPool { purpose: "snapshot.\(readerCount)") }) } + + private static func configure(_ configuration: Configuration) -> Configuration { + var configuration = configuration + + // DatabaseSnapshotPool needs a non-empty pool of connections. + GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1") + + // DatabaseSnapshotPool is read-only. + configuration.readonly = true + + // DatabaseSnapshotPool uses deferred transactions by default. + // Other transaction kinds are forbidden by SQLite in read-only connections. + configuration.defaultTransactionKind = .deferred + + // DatabaseSnapshotPool keeps a long-lived transaction. + configuration.allowsUnsafeTransactions = true + + // DatabaseSnapshotPool requires the WAL mode. + // See + if configuration.readonlyBusyMode == nil { + configuration.readonlyBusyMode = .timeout(10) + } + + return configuration + } } extension DatabaseSnapshotPool: @unchecked Sendable { } From 4ff8928dc495f80127c8c2ce283d6a5493e1d3e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 23 Nov 2022 19:46:00 +0100 Subject: [PATCH 42/69] Simplify declaration of ValueObservation factory methods (SE-0267) --- GRDB/Fixits.swift | 5 +++-- GRDB/ValueObservation/Reducers/ValueReducer.swift | 13 +------------ GRDB/ValueObservation/ValueObservation.swift | 14 +++++++++----- 3 files changed, 13 insertions(+), 19 deletions(-) diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index fb7e12b0d..8ff802b97 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -159,10 +159,11 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { @available(*, unavailable, renamed: "Statement") public typealias UpdateStatement = Statement -extension ValueObservation { +extension ValueObservation { @available(*, unavailable, renamed: "tracking(_:)") public static func trackingVaryingRegion( _ fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> Self + where Reducer == ValueReducers.Fetch { preconditionFailure() } } diff --git a/GRDB/ValueObservation/Reducers/ValueReducer.swift b/GRDB/ValueObservation/Reducers/ValueReducer.swift index 261d62b98..0a4706057 100644 --- a/GRDB/ValueObservation/Reducers/ValueReducer.swift +++ b/GRDB/ValueObservation/Reducers/ValueReducer.swift @@ -39,15 +39,4 @@ public protocol ValueReducer: _ValueReducer { } /// A namespace for concrete types that adopt the ``ValueReducer`` protocol. -public enum ValueReducers { - // ValueReducers.Auto allows us to define ValueObservation factory methods. - // - // For example, ValueObservation.tracking(_:) is, practically, - // ValueObservation.tracking(_:). - /// `Auto` supports ``ValueObservation`` factory methods. - /// - /// Do not use this type. - public enum Auto: _ValueReducer { - public mutating func _value(_ fetched: Never) -> Never? { } - } -} +public enum ValueReducers { } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 31208226a..54b5292f7 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -616,7 +616,7 @@ extension DatabasePublishers { } #endif -extension ValueObservation where Reducer == ValueReducers.Auto { +extension ValueObservation { // MARK: - Creating ValueObservation @@ -733,7 +733,8 @@ extension ValueObservation where Reducer == ValueReducers.Auto { /// - parameter fetch: The closure that fetches the observed value. public static func trackingConstantRegion( _ fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> Self + where Reducer == ValueReducers.Fetch { .init( trackingMode: .constantRegionRecordedFromSelection, @@ -790,7 +791,8 @@ extension ValueObservation where Reducer == ValueReducers.Auto { public static func tracking( region: any DatabaseRegionConvertible..., fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> Self + where Reducer == ValueReducers.Fetch { tracking(regions: region, fetch: fetch) } @@ -845,7 +847,8 @@ extension ValueObservation where Reducer == ValueReducers.Auto { public static func tracking( regions: [any DatabaseRegionConvertible], fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> Self + where Reducer == ValueReducers.Fetch { .init( trackingMode: .constantRegion(regions), @@ -872,7 +875,8 @@ extension ValueObservation where Reducer == ValueReducers.Auto { /// - parameter fetch: The closure that fetches the observed value. public static func tracking( _ fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> Self + where Reducer == ValueReducers.Fetch { .init( trackingMode: .nonConstantRegionRecordedFromSelection, From e430b4ebd7764f630843b0f58f7ee48ab2283ad9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 25 Nov 2022 08:15:14 +0100 Subject: [PATCH 43/69] DatabaseSnapshotReader reentrant read is not unsafe --- GRDB/Core/DatabaseReader.swift | 45 ++++++++++++++++++++++++++++ GRDB/Core/DatabaseSnapshotPool.swift | 10 ------- 2 files changed, 45 insertions(+), 10 deletions(-) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 3f2b2dbae..aa1851cd4 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -695,4 +695,49 @@ extension AnyDatabaseReader: DatabaseReader { /// The protocol comes with the same features and guarantees as /// ``DatabaseReader``. On top of them, a `DatabaseSnapshotReader` always sees /// the same state of the database. +/// +/// ## Topics +/// +/// ### Reading from the Database +/// +/// - ``reentrantRead(_:)`` public protocol DatabaseSnapshotReader: DatabaseReader { } + +extension DatabaseSnapshotReader { + /// Executes database operations, and returns their result after they have + /// finished executing. + /// + /// This method can be called from other database access methods. If called + /// from the dispatch queue of a current database access, the `Database` + /// argument to `value` is the same as the current database access. + /// + /// For example: + /// + /// ```swift + /// let count = try snapshot.reentrantRead { db in + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. + /// + /// - parameter value: A closure which accesses the database. + /// - throws: The error thrown by `value`, or any ``DatabaseError`` that + /// would happen while establishing the database access. + public func reentrantRead(_ value: (Database) throws -> T) throws -> T { + // Reentrant reads are safe in a snapshot + try unsafeReentrantRead(value) + } + + // There is no such thing as an unsafe access to a snapshot. + public func unsafeRead(_ value: (Database) throws -> T) throws -> T { + try read(value) + } + + // There is no such thing as an unsafe access to a snapshot. + public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + asyncRead(value) + } +} diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index c084188f1..8f635c244 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -292,11 +292,6 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } } - public func unsafeRead(_ value: (Database) throws -> T) throws -> T { - /// There is no unsafe access to a snapshot. - try read(value) - } - public func asyncRead(_ value: @escaping (Result) -> Void) { guard let readerPool else { value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed"))) @@ -317,11 +312,6 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { - /// There is no unsafe access to a snapshot. - asyncRead(value) - } - public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { if let reader = currentReader { return try reader.reentrantSync { db in From 6295f4609e653fc42dbe42f7a60cb92b70e8d1dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 25 Nov 2022 08:31:47 +0100 Subject: [PATCH 44/69] More precise WALSnapshot creation errors --- GRDB/Core/WALSnapshot.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index eed7b20d2..aa690b21b 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -35,6 +35,14 @@ final class WALSnapshot: Sendable { return sqlite3_snapshot_get(db.sqliteConnection, "main", $0) } guard code == SQLITE_OK else { + if sqlite3_get_autocommit(db.sqliteConnection) != 0 { + throw DatabaseError(resultCode: code, message: "Can't create snapshot because database is in autocommit mode.") + } + if let journalMode = try? String.fetchOne(db, sql: "PRAGMA journal_mode"), + journalMode != "wal" + { + throw DatabaseError(resultCode: code, message: "Can't create snapshot because database is not in WAL mode.") + } throw DatabaseError(resultCode: code) } guard let sqliteSnapshot else { From 4e4699ebed8ed62af49751f61101fa7768a6a9fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 26 Nov 2022 16:26:46 +0100 Subject: [PATCH 45/69] Improve inline documentation --- .../Request/RequestProtocols.swift | 4 +- GRDB/QueryInterface/SQL/Table.swift | 8 +- .../Schema/TableDefinition.swift | 86 ++++++++++++++++--- .../TableRecord+QueryInterfaceRequest.swift | 4 +- GRDB/Record/FetchableRecord+TableRecord.swift | 4 +- GRDB/Record/TableRecord.swift | 6 +- 6 files changed, 88 insertions(+), 24 deletions(-) diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 2ee094189..553511e19 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -498,7 +498,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// When executed, this request raises a fatal error if no unique index /// exists on a subset of the key columns. /// - /// - parameter key: A unique key. + /// - parameter key: A key dictionary. public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> Self { guard let key else { return none() @@ -526,7 +526,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// When executed, this request raises a fatal error if no unique index /// exists on a subset of the key columns. /// - /// - parameter keys: A collection of unique keys + /// - parameter keys: An array of key dictionaries. public func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> Self { if keys.isEmpty { return none() diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 6b5b578a6..d6ec258be 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -538,7 +538,7 @@ extension Table { /// When executed, this request raises a fatal error if no unique index /// exists on a subset of the key columns. /// - /// - parameter key: A unique key. + /// - parameter key: A key dictionary. public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> QueryInterfaceRequest { all().filter(key: key) } @@ -566,7 +566,7 @@ extension Table { /// When executed, this request raises a fatal error if no unique index /// exists on a subset of the key columns. /// - /// - parameter keys: A collection of unique keys + /// - parameter keys: An array of key dictionaries. public func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> QueryInterfaceRequest { all().filter(keys: keys) } @@ -1611,7 +1611,7 @@ extension Table { /// /// - parameters: /// - db: A database connection. - /// - key: A unique key. + /// - key: A key dictionary. /// - returns: Whether a row exists for this key. public func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try !filter(key: key).isEmpty(db) @@ -1842,7 +1842,7 @@ extension Table { /// key columns. /// - parameters: /// - db: A database connection. - /// - key: A dictionary of values. + /// - key: A key dictionary. /// - returns: Whether a row was deleted. @discardableResult public func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 842d0edc3..b1e538026 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -467,14 +467,32 @@ public final class TableDefinition { /// /// ```swift /// // CREATE TABLE citizenship ( - /// // citizenID INTEGER NOT NULL, + /// // citizenId INTEGER NOT NULL, /// // countryCode TEXT NOT NULL, - /// // PRIMARY KEY (citizenID, countryCode) + /// // PRIMARY KEY (citizenId, countryCode) /// // ) /// try db.create(table: "citizenship") { t in - /// t.column("citizenID", .integer).notNull() + /// t.column("citizenId", .integer).notNull() /// t.column("countryCode", .text).notNull() - /// t.primaryKey(["citizenID", "countryCode"]) + /// t.primaryKey(["citizenId", "countryCode"]) + /// } + /// ``` + /// + /// - important: Make sure you add not null constraints on your primary key + /// columns, as in the above example, or SQLite will allow null values. + /// See + /// for more information. + /// + /// When defining a primary key on a single column, you can use the + /// ``ColumnDefinition/primaryKey(onConflict:autoincrement:)`` + /// shortcut: + /// + /// ```swift + /// // CREATE TABLE player( + /// // id TEXT NOT NULL PRIMARY KEY + /// // ) + /// try db.create(table: "player") { t in + /// t.column("id", .text).notNull().primaryKey() /// } /// ``` /// @@ -510,6 +528,18 @@ public final class TableDefinition { /// } /// ``` /// + /// When defining a unique constraint on a single column, you can use the + /// ``ColumnDefinition/unique(onConflict:)`` shortcut: + /// + /// ```swift + /// // CREATE TABLE player( + /// // email TEXT UNIQUE + /// // ) + /// try db.create(table: "player") { t in + /// t.column("email", .text).unique() + /// } + /// ``` + /// /// Related SQLite documentation: /// /// - parameter columns: The unique key columns. @@ -526,17 +556,27 @@ public final class TableDefinition { /// ```swift /// // CREATE TABLE passport ( /// // issueDate DATE NOT NULL, - /// // citizenID INTEGER NOT NULL, + /// // citizenId INTEGER NOT NULL, /// // countryCode INTEGER NOT NULL, - /// // FOREIGN KEY (citizenID, countryCode) - /// // REFERENCES citizenship(citizenID, countryCode) + /// // FOREIGN KEY (citizenId, countryCode) + /// // REFERENCES citizenship(citizenId, countryCode) /// // ON DELETE CASCADE /// // ) /// try db.create(table: "passport") { t in /// t.column("issueDate", .date).notNull() - /// t.column("citizenID", .integer).notNull() + /// t.column("citizenId", .integer).notNull() /// t.column("countryCode", .text).notNull() - /// t.foreignKey(["citizenID", "countryCode"], references: "citizenship", onDelete: .cascade) + /// t.foreignKey(["citizenId", "countryCode"], references: "citizenship", onDelete: .cascade) + /// } + /// ``` + /// + /// When defining a foreign key on a single column, you can use the + /// ``ColumnDefinition/references(_:column:onDelete:onUpdate:deferred:)`` + /// shortcut: + /// + /// ```swift + /// try db.create(table: "player") { t in + /// t.column("teamId", .integer).references("team", onDelete: .cascade) /// } /// ``` /// @@ -588,6 +628,18 @@ public final class TableDefinition { /// } /// ``` /// + /// When defining a check constraint on a single column, you can use the + /// ``ColumnDefinition/check(_:)`` shortcut: + /// + /// ```swift + /// // CREATE TABLE player( + /// // name TEXT CHECK (LENGTH(name) > 0) + /// // ) + /// try db.create(table: "player") { t in + /// t.column("name", .text).check { length($0) > 0 } + /// } + /// ``` + /// /// Related SQLite documentation: /// /// - parameter condition: The checked condition. @@ -612,6 +664,18 @@ public final class TableDefinition { /// } /// ``` /// + /// When defining a check constraint on a single column, you can use the + /// ``ColumnDefinition/check(sql:)`` shortcut: + /// + /// ```swift + /// // CREATE TABLE player( + /// // name TEXT CHECK (LENGTH(name) > 0) + /// // ) + /// try db.create(table: "player") { t in + /// t.column("name", .text).check(sql: "LENGTH(name) > 0") + /// } + /// ``` + /// /// Related SQLite documentation: /// /// - parameter sql: An SQL snippet @@ -642,8 +706,8 @@ public final class TableDefinition { /// ``SQL`` literals allow you to safely embed raw values in your SQL, /// without any risk of syntax errors or SQL injection: /// - /// // CREATE TABLE player ( /// ```swift + /// // CREATE TABLE player ( /// // score INTEGER, /// // CHECK (score >= 0) /// // ) @@ -1126,7 +1190,7 @@ public final class ColumnDefinition { /// } /// ``` /// - /// - warning: Make sure you add a not null constraint on your primary key + /// - important: Make sure you add a not null constraint on your primary key /// column, as in the above example, or SQLite will allow null values. /// See /// for more information. diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 21af9630b..00ec06396 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -374,7 +374,7 @@ extension TableRecord { /// When executed, this request raises a fatal error if no unique index /// exists on a subset of the key columns. /// - /// - parameter key: A unique key. + /// - parameter key: A key dictionary. public static func filter(key: [String: (any DatabaseValueConvertible)?]?) -> QueryInterfaceRequest { all().filter(key: key) } @@ -402,7 +402,7 @@ extension TableRecord { /// When executed, this request raises a fatal error if no unique index /// exists on a subset of the key columns. /// - /// - parameter keys: A collection of unique keys + /// - parameter keys: An array of key dictionaries. public static func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> QueryInterfaceRequest { all().filter(keys: keys) } diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index ceb76c048..7dcc3daa7 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -266,7 +266,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa /// ```swift /// try dbQueue.read { db in /// let player = try Player.fetchOne(db, id: 123) - /// let country = try Country.fetchOne(db, key: "FR") + /// let country = try Country.fetchOne(db, id: "FR") /// } /// ``` /// @@ -421,7 +421,7 @@ extension FetchableRecord where Self: TableRecord { /// /// - parameters: /// - db: A database connection. - /// - key: A dictionary of values. + /// - key: A key dictionary. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? { diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index cb3f26c74..2c91dd50a 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -362,7 +362,7 @@ extension TableRecord { /// /// - parameters: /// - db: A database connection. - /// - key: A unique key. + /// - key: A key dictionary. /// - 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) @@ -552,7 +552,7 @@ extension TableRecord { return try filter(keys: keys).deleteAll(db) } - /// Deletes the record identified by its primary or unique keys, and returns + /// Deletes the record identified by its primary or unique key, and returns /// whether a record was deleted. /// /// For example: @@ -580,7 +580,7 @@ extension TableRecord { /// key columns. /// - parameters: /// - db: A database connection. - /// - key: A dictionary of values. + /// - key: A key dictionary. /// - returns: Whether a record was deleted. @discardableResult public static func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { From a0bfbafd9c91d03d5cb2b5e7ea2658bc530daab9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 26 Nov 2022 16:27:27 +0100 Subject: [PATCH 46/69] Add tests for MutablePersistableRecord on tables without explicit primary key --- .../MutablePersistableRecordTests.swift | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index 13bd726e6..3b0528978 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -349,6 +349,49 @@ class MutablePersistableRecordTests: GRDBTestCase { } } + func testUpdateWithoutExplicitPrimaryKeyButWithExplicitRowIDSupport() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE record(name)") + + struct Record: Codable, MutablePersistableRecord { + var rowID: Int64? + var name: String + mutating func didInsert(_ inserted: InsertionSuccess) { + rowID = inserted.rowID + } + } + + var record1 = Record(name: "Arthur") + var record2 = Record(name: "Barbara") + try record1.insert(db) + try record2.insert(db) + record1.name = "Craig" + try record1.update(db) + + let names = try String.fetchAll(db, sql: "SELECT name FROM record ORDER BY rowid") + XCTAssertEqual(names, ["Craig", "Barbara"]) + } + } + + func testUpdateWithoutExplicitPrimaryKeyAndWithoutExplicitRowIDSupport() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE record(name)") + + struct Record: Codable, PersistableRecord { + var name: String + } + + let record = Record(name: "Arthur") + try record.insert(db) + do { + try record.update(db) + XCTFail("Expected PersistenceError") + } catch is PersistenceError { } + } + } + func testUpdateMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -501,6 +544,48 @@ class MutablePersistableRecordTests: GRDBTestCase { } } + func testDeleteWithoutExplicitPrimaryKeyButWithExplicitRowIDSupport() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE record(name)") + + struct Record: Codable, MutablePersistableRecord { + var rowID: Int64? + var name: String + mutating func didInsert(_ inserted: InsertionSuccess) { + rowID = inserted.rowID + } + } + + var record1 = Record(name: "Arthur") + var record2 = Record(name: "Barbara") + try record1.insert(db) + try record2.insert(db) + try record1.delete(db) + + let names = try String.fetchAll(db, sql: "SELECT name FROM record ORDER BY rowid") + XCTAssertEqual(names, ["Barbara"]) + } + } + + func testDeleteWithoutExplicitPrimaryKeyAndWithoutExplicitRowIDSupport() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE record(name)") + + struct Record: Codable, PersistableRecord { + var name: String + } + + let record = Record(name: "Arthur") + try record.insert(db) + try XCTAssertFalse(record.delete(db)) + + let names = try String.fetchAll(db, sql: "SELECT name FROM record ORDER BY rowid") + XCTAssertEqual(names, ["Arthur"]) + } + } + func testDeleteMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in From d91e6c2db623cdc6677cd1eb121b9eb053996011 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 26 Nov 2022 16:54:05 +0100 Subject: [PATCH 47/69] Add schema recommendations to DatabaseSchema.md --- GRDB/Documentation.docc/DatabaseSchema.md | 358 +++++++++++++++++++++- 1 file changed, 341 insertions(+), 17 deletions(-) diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index 003b10477..e7680d837 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -1,39 +1,363 @@ # The Database Schema -Learn how to define the database schema. +The database schema is the structure of the database content. ## Overview -You can directly define the database schema when you open a database, as below: +The database schema is made of tables that contain data, as well as views, indexes, and triggers. + +**GRDB supports all database schemas, and has no requirement.** Any existing SQLite database can be opened, and you are free to structure your new databases as you wish. We'll see below some recommendations that will make your life easier, though. + +It is recommended to wrap all schema changes in when the database schema will need to be upgraded in future versions of an application. + +## Schema Alterations + +SQLite supports a [predefined set of schema alterations](https://www.sqlite.org/lang.html): creating or altering tables, creating indexes, etc. + +Many of them are available as Swift methods such as ``Database/create(table:options:body:)``, listed at the end of this page. + +When a schema alteration is not available as a Swift method, use a raw SQL query (for creating views or triggers, for example). + +When a schema alteration is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See for the detailed procedure. + +> Tip: Prefer Swift methods over raw SQL queries. This helps the compiler check if features are available on the target operating system. For example: +> +> - Dropping a table column requires SQLite 3.35+ (iOS 15.0, macOS 12.0). +> - [Strict tables](https://www.sqlite.org/stricttables.html) require SQLite 3.37+ (iOS 15.4, macOS 12.4). + +## Database Schema Recommendations + +Some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below. + +When those conventions are not applied, or not applicable, you will have to perform extra configurations. + +### Table names should be English, singular, and camelCased + +Make them look like singular Swift identifiers: `player`, `team`, `postalAddress`: ```swift -let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") +// RECOMMENDED +try db.create(table: "player") { t in + // table columns and constraints +} -try dbQueue.write { db in - try db.create(table: "player", options: .ifNotExists) { t in - t.autoIncrementedPrimaryKey("id") - t.column("name", .text).notNull() - t.column("score", .integer).notNull() +// REQUIRES EXTRA CONFIGURATION +try db.create(table: "players") { t in + // table columns and constraints +} +``` + +☝️ **If table names follow a different naming convention**, record types (see ) will need explicit table names: + +```swift +extension Player: TableRecord { + // Required because table name is not 'player' + static let databaseTableName = "players" +} + +extension PostalAddress: TableRecord { + // Required because table name is not 'postalAddress' + static let databaseTableName = "postal_address" +} + +extension Award: TableRecord { + // Required because table name is not 'award' + static let databaseTableName = "Auszeichnung" +} +``` + +[Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) will need explicit keys as well: + +```swift +extension Player: TableRecord { + // Explicit association key because the table name is not 'postalAddress' + static let postalAddress = belongsTo(PostalAddress.self, key: "postalAddress") + + // Explicit association key because the table name is not 'award' + static let awards = hasMany(Award.self, key: "awards") +} +``` + +As in the above example, make sure to-one associations use singular keys, and to-many associations use plural keys. + +### Column names should be camelCased + +Again, make them look like Swift identifiers: `fullName`, `score`, `creationDate`: + +```swift +// RECOMMENDED +try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("fullName", .text).notNull() + t.column("score", .integer).notNull() + t.column("creationDate", .datetime).notNull() +} + +// REQUIRES EXTRA CONFIGURATION +try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("full_name", .text).notNull() + t.column("score", .integer).notNull() + t.column("creation_date", .datetime).notNull() +} +``` + +☝️ **If the column names follow a different naming convention**, `Codable` record types will need an explicit `CodingKeys` enum: + +```swift +struct Player: Decodable, FetchableRecord { + var id: Int64 + var fullName: String + var score: Int + var creationDate: Date + + // Required CodingKeys customization because + // column are not named like Swift properties + enum CodingKeys: String, CodingKey { + case id, fullName = "full_name", score, creationDate = "creation_date" } } ``` -But you should prefer wrapping all your schema changes in , when you plan to upgrade the database schema in future versions of your app. +### Tables should have explicit primary keys -## Schema Alterations +A primary key uniquely identifies a row in a table. It is defined on one or several columns: -SQLite directly supports a [set of schema alterations](https://www.sqlite.org/lang.html). +```swift +// RECOMMENDED +try db.create(table: "player") { t in + // Auto-incremented primary key + t.autoIncrementedPrimaryKey("id") + t.column("name", .text).notNull() +} -Many of them are available as Swift methods such as ``Database/create(table:options:body:)``, listed below. +try db.create(table: "team") { t in + // Single-column primary key + t.column("id", .text).notNull().primaryKey() + t.column("name", .text).notNull() +} -When the schema alteration you need is not available as a Swift method, use a raw SQL query (for creating views or triggers, for example). +try db.create(table: "membership") { t in + // Composite primary key + t.primaryKey(["playerId", "teamId"]) + t.column("playerId", .integer).notNull().references("player") + t.column("teamId", .text).notNull().references("team") + t.column("role", .text).notNull() +} -When you need to modify a table in a way that is not directly supported by SQLite, or not available on your target operating system, you will need to recreate the database table. See for the detailed procedure. +// REQUIRES EXTRA CONFIGURATION +try db.create(table: "player") { t in + t.column("name", .text).notNull() +} -> Tip: Prefer Swift methods over raw SQL queries. This helps the compiler check if features are available on the SQLite version that ships on the target operating system. For example: +try db.create(table: "team") { t in + t.column("id", .text).notNull().unique() + t.column("name", .text).notNull() +} + +try db.create(table: "membership") { t in + t.column("playerId", .integer).notNull() + t.column("teamId", .text).notNull() + t.column("role", .text).notNull() +} +``` + +Primary keys support record fetching methods such as ``FetchableRecord/fetchOne(_:id:)``, and persistence methods such as ``MutablePersistableRecord/update(_:onConflict:)`` or ``MutablePersistableRecord/delete(_:)``. + +See when you need to define a table that contains a single row. + +> Important: Add not null constraints on primary key columns, as in the above recommended examples, or SQLite will allow null values. See for more information. + +☝️ **If the database table does not define any explicit primary key**, the record type for this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html): + +```swift +// A table without any explicit primary key +try db.create(table: "player") { t in + t.column("name", .text).notNull() + t.column("score", .integer).notNull() +} + +// The record type for the 'player' table' +struct Player: Codable { + // Uniquely identifies a player. + var rowid: Int64? + var name: String + var score: Int +} + +extension Player: Identifiable { + // Required because the primary key column is not 'id' + var id: Int64? { rowid } +} + +extension Player: FetchableRecord, MutablePersistableRecord { + // Required because the primary key + // is the hidden rowid column. + static let databaseSelection: [any SQLSelectable] = [ + AllColumns(), + Column.rowID] + + mutating func didInsert(_ inserted: InsertionSuccess) { + rowid = inserted.rowID + } +} + +try dbQueue.read { db in + // SELECT *, rowid FROM player WHERE rowid = 1 + let player = try Player.fetchOne(db, id: 1) +} +``` + +### Single-column primary keys should be named 'id' + +This helps record types play well with the standard `Identifiable` protocol. + +```swift +// RECOMMENDED +try db.create(table: "player") { t in + t.column("id", .text).notNull().primaryKey() + t.column("name", .text).notNull() +} + +// REQUIRES EXTRA CONFIGURATION +try db.create(table: "player") { t in + t.column("uuid", .text).notNull().primaryKey() + t.column("name", .text).notNull() +} +``` +☝️ **If the primary key follows a different naming convention**, `Identifiable` record types will need an extra property: + +```swift +struct Player { + var uuid: String + var name: String +} + +extension Player: Identifiable { + // Required because the primary key column is not 'id' + var id: String { uuid } +} +``` + +### Unique keys should be supported by unique indexes + +Unique indexes makes sure SQLite prevents the insertion of conflicting rows: + +```swift +// RECOMMENDED +try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + // Players must have distinct names + t.column("name", .text).unique() + t.column("teamId", .integer).notNull().references("team") + t.column("position", .integer).notNull() +} + +// One single player at any given position in a team +try db.create( + index: "playerTeamPosition", + on: "player", columns: ["teamId", "position"], + options: .unique) +``` + +> Tip: SQLite does not support deferred unique indexes, and this creates undesired churn when you need to temporarily break them. This may happen, for example, when you want to reorder player positions in our above example. > -> - Dropping a table column requires SQLite 3.35+ (iOS 15.0, macOS 12.0). -> - [Strict tables](https://www.sqlite.org/stricttables.html) require SQLite 3.37+ (iOS 15.4, macOS 12.4). +> There exist several workarounds; one of them involves dropping and recreating the unique index after the temporary violations have been fixed. If you plan to use this technique, take care that only actual indexes can be dropped. Unique constraints created inside the table body can not: +> +> ```swift +> // Unique constraint on player(name) can not be dropped. +> try db.create(table: "player") { t in +> t.column("name", .text).unique() +> } +> +> // Unique index on team(name) can be dropped. +> try db.create(table: "team") { t in +> t.column("name", .text) +> } +> try db.create( +> index: "teamName", +> on: "team", columns: ["name"], +> options: .unique) +> ``` + +☝️ **If a table misses unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error: + +```swift +try dbQueue.write { db in + // Fatal error: table player has no unique index on columns ... + let player = try Player.fetchOne(db, key: ["teamId": 42, "position": 1]) + try Player.deleteOne(db, key: ["name": "Arthur"]) + + // Use instead: + let player = try Player + .filter(Column("teamId") == 42 && Column("position") == 1) + .fetchOne(db) + + try Player + .filter(Column("name") == "Arthur") + .deleteAll(db) +} +``` + +### Relations between tables should be supported by foreign keys + +[Foreign Keys](https://www.sqlite.org/foreignkeys.html) have SQLite enforce valid relationships between tables: + +```swift +try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + t.column("color", .text).notNull() +} + +// RECOMMENDED +try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text).notNull() + // A player must refer to an existing team + t.column("teamId", .integer).notNull().references("team") +} + +// REQUIRES EXTRA CONFIGURATION +try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text).notNull() + // No foreign key + t.column("teamId", .integer).notNull() +} +``` + +GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema: + +```swift +extension Player: TableRecord { + static let team = belongsTo(Team.self) +} + +extension Team: TableRecord { + static let players = hasMany(Player.self) +} +``` + +See [Associations and the Database Schema](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#associations-and-the-database-schema) for more precise recommendations. + +☝️ **If a foreign key is not declared in the schema**, you will need to explicitly configure related associations: + +```swift +extension Player: TableRecord { + // Required configuration because the database does + // not declare any foreign key from players to their team. + static let teamForeignKey = ForeignKey(["teamId"]) + static let team = belongsTo(Team.self, + using: teamForeignKey) +} + +extension Team: TableRecord { + // Required configuration because the database does + // not declare any foreign key from players to their team. + static let players = hasMany(Player.self, + using: Player.teamForeignKey) +} +``` ## Topics From 3074b61cb772a7c3ec8b1d1f15d236c7e0de22a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 11:07:13 +0100 Subject: [PATCH 48/69] Move schema documentation to DocC --- .../GRDBAsyncDemo/AppDatabase.swift | 2 +- .../GRDBCombineDemo/AppDatabase.swift | 2 +- .../GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift | 2 +- GRDB/Core/Database.swift | 44 ++-- GRDB/Documentation.docc/DatabaseSchema.md | 38 ++-- .../Schema/TableDefinition.swift | 199 ++++++++++++++-- README.md | 213 +----------------- 7 files changed, 229 insertions(+), 271 deletions(-) diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift index 03f7d14b0..0d4b2227c 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift @@ -34,7 +34,7 @@ struct AppDatabase { migrator.registerMigration("createPlayer") { db in // Create a table - // See https://github.com/groue/GRDB.swift#create-tables + // See try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift index 3c8370907..b9516f3d0 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift @@ -35,7 +35,7 @@ struct AppDatabase { migrator.registerMigration("createPlayer") { db in // Create a table - // See https://github.com/groue/GRDB.swift#create-tables + // See try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index 7543a31e5..ff56eec1f 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -33,7 +33,7 @@ final class AppDatabase { migrator.registerMigration("createPlayer") { db in // Create a table - // See https://github.com/groue/GRDB.swift#create-tables + // See try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index eddd8d380..b174be1a6 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -103,11 +103,6 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// - ``DatabaseBackupProgress`` /// - ``TraceEvent`` /// - ``TracingOptions`` -/// -/// ### Sunsetted Methods -/// -/// - ``create(index:on:columns:unique:ifNotExists:condition:)`` -/// - ``create(table:temporary:ifNotExists:withoutRowID:body:)`` public final class Database: CustomStringConvertible, CustomDebugStringConvertible { // The Database class is not thread-safe. An instance should always be // used through a SerializedDatabase. @@ -1729,26 +1724,23 @@ extension Database { /// An SQL column type. /// - /// You use column types when you modify the database schema. For example, - /// the code below create a `player` table with a `name` column whose type - /// is ``text`` (`TEXT` in SQL): + /// You use column types when you modify the database schema. For example: /// /// ```swift /// // CREATE TABLE player( - /// // id INTEGER PRIMARY KEY AUTOINCREMENT, - /// // name TEXT + /// // id INTEGER PRIMARY KEY, + /// // name TEXT, + /// // creationDate DATETIME, /// // ) /// try db.create(table: "player") { t in - /// t.autoIncrementedPrimaryKey("id") + /// t.column("id", .integer).primaryKey() /// t.column("name", .text) + /// t.column("creationDate", .datetime) /// } /// ``` /// - /// A `ColumnType` is an element of the SQL language, as is `TEXT` in the - /// example above. The type comes with many built-in constants for - /// frequently used types: ``text``, ``integer``, etc. - /// - /// Related SQLite documentation: + /// For more information, see + /// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html). public struct ColumnType: RawRepresentable, Hashable { /// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.) public let rawValue: String @@ -1758,34 +1750,34 @@ extension Database { self.rawValue = rawValue } - /// The `TEXT` SQL column type. + /// The `TEXT` column type. public static let text = ColumnType(rawValue: "TEXT") - /// The `INTEGER` SQL column type. + /// The `INTEGER` column type. public static let integer = ColumnType(rawValue: "INTEGER") - /// The `DOUBLE` SQL column type. + /// The `DOUBLE` column type. public static let double = ColumnType(rawValue: "DOUBLE") - /// The `REAL` SQL column type. + /// The `REAL` column type. public static let real = ColumnType(rawValue: "REAL") - /// The `NUMERIC` SQL column type. + /// The `NUMERIC` column type. public static let numeric = ColumnType(rawValue: "NUMERIC") - /// The `BOOLEAN` SQL column type. + /// The `BOOLEAN` column type. public static let boolean = ColumnType(rawValue: "BOOLEAN") - /// The `BLOB` SQL column type. + /// The `BLOB` column type. public static let blob = ColumnType(rawValue: "BLOB") - /// The `DATE` SQL column type. + /// The `DATE` column type. public static let date = ColumnType(rawValue: "DATE") - /// The `DATETIME` SQL column type. + /// The `DATETIME` column type. public static let datetime = ColumnType(rawValue: "DATETIME") - /// The `ANY` SQL column type. + /// The `ANY` column type. public static let any = ColumnType(rawValue: "ANY") } diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index e7680d837..1727d71bc 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -1,33 +1,28 @@ # The Database Schema -The database schema is the structure of the database content. - ## Overview -The database schema is made of tables that contain data, as well as views, indexes, and triggers. +**GRDB supports all database schemas, and has no requirement.** Any existing SQLite database can be opened, and you are free to structure your new databases as you wish. -**GRDB supports all database schemas, and has no requirement.** Any existing SQLite database can be opened, and you are free to structure your new databases as you wish. We'll see below some recommendations that will make your life easier, though. +You perform modifications to the database schema with methods such as ``Database/create(table:options:body:)``, listed at the end of this page. For example: -It is recommended to wrap all schema changes in when the database schema will need to be upgraded in future versions of an application. +```swift +try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text).notNull() + t.column("score", .integer).notNull() +} +``` -## Schema Alterations +When you plan to evolve the schema as new versions of your application ship, wrap all schema changes in . -SQLite supports a [predefined set of schema alterations](https://www.sqlite.org/lang.html): creating or altering tables, creating indexes, etc. +Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating views or triggers, for example). -Many of them are available as Swift methods such as ``Database/create(table:options:body:)``, listed at the end of this page. - -When a schema alteration is not available as a Swift method, use a raw SQL query (for creating views or triggers, for example). - -When a schema alteration is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See for the detailed procedure. - -> Tip: Prefer Swift methods over raw SQL queries. This helps the compiler check if features are available on the target operating system. For example: -> -> - Dropping a table column requires SQLite 3.35+ (iOS 15.0, macOS 12.0). -> - [Strict tables](https://www.sqlite.org/stricttables.html) require SQLite 3.37+ (iOS 15.4, macOS 12.4). +When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See for the detailed procedure. ## Database Schema Recommendations -Some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below. +Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below. When those conventions are not applied, or not applicable, you will have to perform extra configurations. @@ -409,3 +404,10 @@ extension Team: TableRecord { - ``Database/foreignKeyViolations()`` - ``Database/foreignKeyViolations(in:)`` - ``ForeignKeyViolation`` + +### Sunsetted Methods + +Those are legacy interfaces that are preserved for backwards compatibility. Their use is not recommended. + +- ``Database/create(index:on:columns:unique:ifNotExists:condition:)`` +- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)`` diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index b1e538026..26af8e648 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -21,7 +21,8 @@ extension Database { /// - /// - /// - /// - warning: This method is sunsetted. You should prefer + /// - warning: This is a legacy interface that is preserved for backwards + /// compatibility. Use of this interface is not recommended: prefer /// ``create(table:options:body:)`` instead. /// /// - parameters: @@ -51,21 +52,190 @@ extension Database { /// Creates a database table. /// - /// For example: + /// ### Reference documentation + /// + /// SQLite has many reference documents about table creation. They are a + /// great learning material: + /// + /// - [CREATE TABLE](https://www.sqlite.org/lang_createtable.html) + /// - [Datatypes In SQLite](https://www.sqlite.org/datatype3.html) + /// - [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html) + /// - [The ON CONFLICT Clause](https://www.sqlite.org/lang_conflict.html) + /// - [Rowid Tables](https://www.sqlite.org/rowidtable.html) + /// - [The WITHOUT ROWID Optimization](https://www.sqlite.org/withoutrowid.html) + /// - [STRICT Tables](https://www.sqlite.org/stricttables.html) + /// + /// ### Usage /// /// ```swift + /// // CREATE TABLE place ( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // title TEXT, + /// // isFavorite BOOLEAN NOT NULL DEFAULT 0, + /// // latitude DOUBLE NOT NULL, + /// // longitude DOUBLE NOT NULL + /// // ) /// try db.create(table: "place") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) - /// t.column("favorite", .boolean).notNull().default(false) + /// t.column("isFavorite", .boolean).notNull().default(false) /// t.column("longitude", .double).notNull() /// t.column("latitude", .double).notNull() /// } /// ``` /// - /// Related SQLite documentation: - /// - - /// - + /// ### Configure table creation + /// + /// Use the `options` parameter to configure table creation + /// (see ``TableOptions``): + /// + /// ```swift + /// // CREATE TABLE player ( ... ) + /// try db.create(table: "player") { t in ... } + /// + /// // CREATE TEMPORARY TABLE player IF NOT EXISTS ( + /// try db.create(table: "player", options: [.temporary, .ifNotExists]) { t in ... } + /// ``` + /// + /// ### Add columns + /// + /// Add columns with their name and eventual type (`text`, `integer`, + /// `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime` + /// and `any`) - see ``Database/ColumnType``: + /// + /// ```swift + /// // CREATE TABLE example ( + /// // a, + /// // name TEXT, + /// // creationDate DATETIME, + /// try db.create(table: "example") { t in + /// t.column("a") + /// t.column("name", .text) + /// t.column("creationDate", .datetime) + /// ``` + /// + /// The `column()` method returns a ``ColumnDefinition`` that you can + /// further configure: + /// + /// ### NOT NULL constraints, DEFAULT values + /// + /// ```swift + /// // email TEXT NOT NULL, + /// t.column("email", .text).notNull() + /// + /// // flag BOOLEAN NOT NULL DEFAULT 0, + /// t.column("flag", .boolean).notNull().defaults(to: false) + /// ``` + /// + /// ### Primary, unique, and foreign keys + /// + /// Use an individual column as **primary**, **unique**, or **foreign key**. + /// When defining a foreign key, the referenced column is the primary key of + /// the referenced table (unless you specify otherwise): + /// + /// ```swift + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// t.autoIncrementedPrimaryKey("id") + /// + /// // uuid TEXT NOT NULL PRIMARY KEY, + /// t.column("uuid", .text) + /// .notNull() + /// .primaryKey() + /// + /// // email TEXT UNIQUE, + /// t.column("email", .text) + /// .unique() + /// + /// // countryCode TEXT REFERENCES country(code) ON DELETE CASCADE, + /// t.column("countryCode", .text) + /// .references("country", onDelete: .cascade) + /// ``` + /// + /// Primary, unique and foreign keys can also be added on several columns: + /// + /// ```swift + /// // PRIMARY KEY (a, b), + /// t.primaryKey(["a", "b"]) + /// + /// // UNIQUE (a, b) ON CONFLICT REPLACE, + /// t.uniqueKey(["a", "b"], onConflict: .replace) + /// + /// // FOREIGN KEY (a, b) REFERENCES parents(c, d), + /// t.foreignKey(["a", "b"], references: "parents") + /// ``` + /// + /// > Tip: when you need an integer primary key that automatically generates + /// unique values, it is recommended that you use the + /// ``TableDefinition/autoIncrementedPrimaryKey(_:onConflict:)`` method: + /// > + /// > ```swift + /// > try db.create(table: "example") { t in + /// > t.autoIncrementedPrimaryKey("id") + /// > ... + /// > } + /// > ``` + /// > + /// > The reason for this recommendation is that auto-incremented primary + /// > keys forbid the reuse of ids. This prevents your app or + /// > to think that a row was updated, when it was + /// > actually deleted and replaced. Depending on your application needs, + /// > this may be acceptable. But usually it is not. + /// + /// ### Indexed columns + /// + /// ```swift + /// t.column("score", .integer).indexed() + /// ``` + /// + /// For extra index options, see ``create(index:on:columns:options:condition:)``. + /// + /// ### Integrity checks + /// + /// SQLite will only let conforming rows in: + /// + /// ```swift + /// // name TEXT CHECK (LENGTH(name) > 0) + /// t.column("name", .text).check { length($0) > 0 } + /// + /// // score INTEGER CHECK (score > 0) + /// t.column("score", .integer).check(sql: "score > 0") + /// + /// // CHECK (a + b < 10), + /// t.check(Column("a") + Column("b") < 10) + /// + /// // CHECK (a + b < 10) + /// t.check(sql: "a + b < 10") + /// ``` + /// + /// ### Generated columns + /// + /// [Generated columns](https://sqlite.org/gencol.html) are available with a + /// [custom SQLite build](https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md): + /// + /// ```swift + /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus") + /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus")) + /// ``` + /// + /// ### Raw SQL columns and constraints + /// + /// Columns and constraints can be defined with raw sql: + /// + /// ```swift + /// t.column(sql: "name TEXT") + /// t.constraint(sql: "CHECK (a + b < 10)") + /// ``` + /// + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: + /// + /// ```swift + /// let defaultName = "O'Reilly" + /// t.column(literal: "name TEXT DEFAULT \(defaultName)") + /// + /// let forbiddenName = "admin" + /// t.constraint(literal: "CHECK (name <> \(forbiddenName))") + /// ``` /// /// - parameters: /// - name: The table name. @@ -146,7 +316,8 @@ extension Database { /// /// Related SQLite documentation: /// - /// - warning: This method is sunsetted. You should prefer + /// - warning: This is a legacy interface that is preserved for backwards + /// compatibility. Use of this interface is not recommended: prefer /// ``create(index:on:columns:options:condition:)`` instead. /// /// - parameters: @@ -252,7 +423,7 @@ extension Database { } } -/// Table creation options +/// Table creation options. public struct TableOptions: OptionSet { public let rawValue: Int @@ -264,18 +435,16 @@ public struct TableOptions: OptionSet { /// Creates a temporary table. public static let temporary = TableOptions(rawValue: 1 << 1) - /// Creates a without rowid table. See + /// Creates a [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) table. + /// + /// Such tables can not be tracked with tools. public static let withoutRowID = TableOptions(rawValue: 1 << 2) #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Creates a STRICT table - /// - /// Related SQLite documentation: + /// Creates a [STRICT](https://www.sqlite.org/stricttables.html) table. public static let strict = TableOptions(rawValue: 1 << 3) #else - /// Creates a STRICT table - /// - /// Related SQLite documentation: + /// Creates a [STRICT](https://www.sqlite.org/stricttables.html) table. @available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) // SQLite 3.37+ public static let strict = TableOptions(rawValue: 1 << 3) #endif diff --git a/README.md b/README.md index 267bea9c9..7a654e8e3 100644 --- a/README.md +++ b/README.md @@ -336,7 +336,7 @@ Documentation #### Records and the Query Interface - [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies -- [Query Interface](#the-query-interface): A swift way to generate SQL • [table creation](#database-schema) • [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md) +- [Query Interface](#the-query-interface): A swift way to generate SQL • [create tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) • [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md) #### Application Tools @@ -2449,7 +2449,7 @@ try dbQueue.write { db in } ``` -Of course, you need to open a [database connection](#database-connections), and [create database tables](#database-schema) first. +Of course, you need to open a [database connection](#database-connections), and [create database tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) first. To define your custom records, you subclass the ready-made `Record` class, or you extend your structs and classes with protocols that come with focused sets of features: fetching methods, persistence methods, record comparison... @@ -4495,7 +4495,7 @@ So don't miss the [SQL API](#sqlite-api). > **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) +- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) - [Requests](#requests) - [Expressions](#expressions) - [SQL Operators](#sql-operators) @@ -4512,211 +4512,6 @@ So don't miss the [SQL API](#sqlite-api). - :blue_book: [Common Table Expressions] - :blue_book: [Query Interface Organization] - -## Database Schema - -Once granted with a [database connection](#database-connections), you can setup your database schema without writing SQL: - -- [Create Tables](#create-tables) -- [Modify Tables](#modify-tables) -- [Drop Tables](#drop-tables) -- [Create Indexes](#create-indexes) - - -### Create Tables - -```swift -// CREATE TABLE place ( -// id INTEGER PRIMARY KEY AUTOINCREMENT, -// title TEXT, -// favorite BOOLEAN NOT NULL DEFAULT 0, -// latitude DOUBLE NOT NULL, -// longitude DOUBLE NOT NULL -// ) -try db.create(table: "place") { t in - t.autoIncrementedPrimaryKey("id") - t.column("title", .text) - t.column("favorite", .boolean).notNull().defaults(to: false) - t.column("longitude", .double).notNull() - t.column("latitude", .double).notNull() -} -``` - -The `create(table:)` method covers nearly all SQLite table creation features. For virtual tables, see [Full-Text Search], or use raw SQL. - -SQLite itself has many reference documents about table creation: [CREATE TABLE](https://www.sqlite.org/lang_createtable.html), [Datatypes In SQLite Version 3](https://www.sqlite.org/datatype3.html), [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html), [ON CONFLICT](https://www.sqlite.org/lang_conflict.html), [The WITHOUT ROWID Optimization](https://www.sqlite.org/withoutrowid.html). - -**Configure table creation**: - -```swift -// CREATE TABLE example ( ... ) -try db.create(table: "example") { t in ... } - -// CREATE TEMPORARY TABLE example IF NOT EXISTS ( -try db.create(table: "example", options: [.temporary, .ifNotExists]) { t in ... } -``` - -> :bulb: **Tip**: database table names should be singular, and camelCased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, `httpRequest`. -> -> 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. -> -> **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): - -```swift -// CREATE TABLE example ( -// a, -// name TEXT, -// creationDate DATETIME, -try db.create(table: "example") { t in - t.column("a") - t.column("name", .text) - t.column("creationDate", .datetime) -``` - -Define **not null** columns, and set **default** values: - -```swift - // email TEXT NOT NULL, - t.column("email", .text).notNull() - - // name TEXT NOT NULL DEFAULT 'Anonymous', - t.column("name", .text).notNull().defaults(to: "Anonymous") -``` - -Use an individual column as **primary**, **unique**, or **foreign key**. When defining a foreign key, the referenced column is the primary key of the referenced table (unless you specify otherwise): - -```swift - // id INTEGER PRIMARY KEY AUTOINCREMENT, - t.autoIncrementedPrimaryKey("id") - - // uuid TEXT PRIMARY KEY, - t.column("uuid", .text).primaryKey() - - // email TEXT UNIQUE, - t.column("email", .text).unique() - - // countryCode TEXT REFERENCES country(code) ON DELETE CASCADE, - t.column("countryCode", .text).references("country", onDelete: .cascade) -``` - -> :bulb: **Tip**: when you need an integer primary key that automatically generates unique values, it is highly recommended that you use the `autoIncrementedPrimaryKey` method: -> -> ```swift -> try db.create(table: "example") { t in -> t.autoIncrementedPrimaryKey("id") -> ... -> } -> ``` -> -> The reason for this recommendation is that auto-incremented primary keys prevent the reuse of ids. This prevents your app or [database observation tools](#database-changes-observation) to think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be acceptable. But usually it is not. - -**Create an index** on the column: - -```swift - t.column("score", .integer).indexed() -``` - -For extra index options, see [Create Indexes](#create-indexes) below. - -**Perform integrity checks** on individual columns, and SQLite will only let conforming rows in. In the example below, the `$0` closure variable is a column which lets you build any SQL [expression](#expressions). - -```swift - // name TEXT CHECK (LENGTH(name) > 0) - // score INTEGER CHECK (score > 0) - t.column("name", .text).check { length($0) > 0 } - t.column("score", .integer).check(sql: "score > 0") -``` - -Columns can also be defined with a raw sql String, or an [SQL literal] in which you can safely embed raw values without any risk of syntax errors or SQL injection: - -```swift - t.column(sql: "name TEXT") - - let defaultName: String = ... - t.column(literal: "name TEXT DEFAULT \(defaultName)") -``` - -Other **table constraints** can involve several columns: - -```swift - // PRIMARY KEY (a, b), - t.primaryKey(["a", "b"]) - - // UNIQUE (a, b) ON CONFLICT REPLACE, - t.uniqueKey(["a", "b"], onConflict: .replace) - - // FOREIGN KEY (a, b) REFERENCES parents(c, d), - t.foreignKey(["a", "b"], references: "parents") - - // CHECK (a + b < 10), - t.check(Column("a") + Column("b") < 10) - - // CHECK (a + b < 10) - t.check(sql: "a + b < 10") - - // Raw SQL constraints - t.constraint(sql: "CHECK (a + b < 10)") - t.constraint(literal: "CHECK (a + b < \(10))") -``` - -[Generated columns](https://sqlite.org/gencol.html) are available with a [custom SQLite build]: - -```swift - t.column("totalScore", .integer).generatedAs(sql: "score + bonus") - t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus")) -} -``` - -### Modify Tables - -SQLite lets you modify existing tables: - -```swift -// ALTER TABLE referer RENAME TO referrer -try db.rename(table: "referer", to: "referrer") - -// ALTER TABLE player ADD COLUMN hasBonus BOOLEAN -// ALTER TABLE player RENAME COLUMN url TO homeURL -// ALTER TABLE player DROP COLUMN score -try db.alter(table: "player") { t in - t.add(column: "hasBonus", .boolean) - t.rename(column: "url", to: "homeURL") // SQLite 3.25+ - t.drop(column: "score") // SQLite 3.35+ -} -``` - -> **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. - - -### Drop Tables - -Drop tables with the `drop(table:)` method: - -```swift -try db.drop(table: "obsolete") -``` - -### Create Indexes - -Create indexes with the `create(index:)` method: - -```swift -// CREATE INDEX byName ON users(lastName, firstName) -try db.create(index: "byName", on: "users", columns: ["lastName, "firstName"]) - -// CREATE UNIQUE INDEX byEmail IF NOT EXISTS ON users(email) -try db.create(index: "byEmail", on: "users", columns: ["email"], options: [.unique, .ifNotExists]) -``` - -Relevant SQLite documentation: - -- [CREATE INDEX](https://www.sqlite.org/lang_createindex.html) -- [Indexes On Expressions](https://www.sqlite.org/expridx.html) -- [Partial Indexes](https://www.sqlite.org/partialindex.html) - - ## Requests **The query interface requests** let you fetch values from the database: @@ -7846,7 +7641,7 @@ They uncover programmer errors, false assumptions, and prevent misuses. Here are let name: String = row["name"] ``` - Solution: fix the contents of the database, use [NOT NULL constraints](#create-tables), or load an optional: + Solution: fix the contents of the database, use [NOT NULL constraints](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/columndefinition/notnull(onconflict:)), or load an optional: ```swift let name: String? = row["name"] From 8b8e480391273bf07d6b690cf69ae5ed9f0ddab4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 11:32:38 +0100 Subject: [PATCH 49/69] Primary key definition with NOT NULL constraint by default --- .../Schema/TableDefinition.swift | 167 +++++++++++++++--- 1 file changed, 139 insertions(+), 28 deletions(-) diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 26af8e648..ca2c8d67d 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -471,11 +471,19 @@ public struct TableOptions: OptionSet { /// - ``column(sql:)`` /// - ``ColumnDefinition`` /// -/// ### Define Keys +/// ### Define the Primary Key /// /// - ``autoIncrementedPrimaryKey(_:onConflict:)`` +/// - ``primaryKey(_:_:onConflict:)`` +/// - ``primaryKey(onConflict:body:)`` +/// - ``PrimaryKeyDefinition`` +/// +/// ### Define a Foreign Key +/// /// - ``foreignKey(_:references:columns:onDelete:onUpdate:deferred:)`` -/// - ``primaryKey(_:onConflict:)`` +/// +/// ### Define a Unique Key +/// /// - ``uniqueKey(_:onConflict:)`` /// /// ### Define Others Constraints @@ -485,7 +493,12 @@ public struct TableOptions: OptionSet { /// - ``constraint(literal:)`` /// - ``constraint(sql:)`` /// -/// Related SQLite documentation: +/// ### Sunsetted Methods +/// +/// Those are legacy interfaces that are preserved for backwards compatibility. +/// Their use is not recommended. +/// +/// - ``primaryKey(_:onConflict:)`` public final class TableDefinition { private typealias KeyConstraint = ( columns: [String], @@ -570,6 +583,68 @@ public final class TableDefinition { column(name, .integer).primaryKey(onConflict: conflictResolution, autoincrement: true) } + /// Defines the primary key on a single column. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player ( + /// // id INTEGER NOT NULL PRIMARY KEY + /// // ) + /// try db.create(table: "player") { t in + /// t.primaryKey("id", .integer) + /// } + /// ``` + /// + /// A NOT NULL constraint is always added to the primary key column. + /// + /// - parameter name: the column name. + /// - parameter type: the column type. + /// - returns: A ``ColumnDefinition`` that allows you to refine the + /// column definition. + @discardableResult + public func primaryKey( + _ name: String, + _ type: Database.ColumnType, + onConflict conflictResolution: Database.ConflictResolution? = nil) + -> ColumnDefinition + { + column(name, type) + .notNull() + .primaryKey(onConflict: conflictResolution) + } + + /// Defines the primary key on multiple columns. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE passport ( + /// // citizenId INTEGER NOT NULL, + /// // countryCode TEXT NOT NULL, + /// // issueDate DATE NOT NULL, + /// // PRIMARY KEY (citizenId, countryCode) + /// // ) + /// try db.create(table: "passport") { t in + /// t.primaryKey { pk in + /// pk.column("citizenId", .integer) + /// pk.column("countryCode", .text) + /// } + /// t.column("issueDate", .date).notNull() + /// } + /// ``` + /// + /// A NOT NULL constraint is always added to the primary key columns. + public func primaryKey( + onConflict conflictResolution: Database.ConflictResolution? = nil, + body: (PrimaryKeyDefinition) throws -> Void) + rethrows + { + let pk = PrimaryKeyDefinition(tableDefinition: self) + try body(pk) + primaryKey(pk.columns, onConflict: conflictResolution) + } + /// Appends a table column. /// /// For example: @@ -587,7 +662,7 @@ public final class TableDefinition { /// /// - parameter name: the column name. /// - parameter type: the eventual column type. - /// - returns: An ``ColumnDefinition`` that allows you to refine the + /// - returns: A ``ColumnDefinition`` that allows you to refine the /// column definition. @discardableResult public func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition { @@ -652,22 +727,9 @@ public final class TableDefinition { /// See /// for more information. /// - /// When defining a primary key on a single column, you can use the - /// ``ColumnDefinition/primaryKey(onConflict:autoincrement:)`` - /// shortcut: - /// - /// ```swift - /// // CREATE TABLE player( - /// // id TEXT NOT NULL PRIMARY KEY - /// // ) - /// try db.create(table: "player") { t in - /// t.column("id", .text).notNull().primaryKey() - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - - /// - + /// - warning: This is a legacy interface that is preserved for backwards + /// compatibility. Use of this interface is not recommended: prefer + /// ``TableDefinition/primaryKey(onConflict:body:)`` instead. /// /// - parameter columns: The primary key columns. /// - parameter conflictResolution: An optional conflict resolution @@ -1252,6 +1314,51 @@ public final class TableAlteration { } } +/// Describes the primary key of a table. +/// +/// See ``TableDefinition/primaryKey(onConflict:body:)``. +public final class PrimaryKeyDefinition { + let tableDefinition: TableDefinition + var columns: [String] + + init(tableDefinition: TableDefinition) { + self.tableDefinition = tableDefinition + self.columns = [] + } + + /// Appends a column to the primary key. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE passport ( + /// // citizenId INTEGER NOT NULL, + /// // countryCode TEXT NOT NULL, + /// // issueDate DATE NOT NULL, + /// // PRIMARY KEY (citizenId, countryCode) + /// // ) + /// try db.create(table: "passport") { t in + /// t.primaryKey { pk in + /// pk.column("citizenId", .integer) + /// pk.column("countryCode", .text) + /// } + /// t.column("issueDate", .date).notNull() + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameter name: the column name. + /// - parameter type: the column type. + /// - returns: A ``ColumnDefinition`` that allows you to refine the + /// column definition. + @discardableResult + public func column(_ name: String, _ type: Database.ColumnType) -> ColumnDefinition { + columns.append(name) + return tableDefinition.column(name, type).notNull() + } +} + /// Describes a database column. /// /// You get instances of `ColumnDefinition` when you create or alter a database @@ -1276,9 +1383,8 @@ public final class TableAlteration { /// /// ## Topics /// -/// ### Keys +/// ### Foreign Keys /// -/// - ``primaryKey(onConflict:autoincrement:)`` /// - ``references(_:column:onDelete:onUpdate:deferred:)`` /// /// ### Indexes @@ -1301,6 +1407,13 @@ public final class TableAlteration { /// - ``check(_:)`` /// - ``check(sql:)`` /// - ``notNull(onConflict:)`` +/// +/// ### Sunsetted Methods +/// +/// Those are legacy interfaces that are preserved for backwards compatibility. +/// Their use is not recommended. +/// +/// - ``primaryKey(onConflict:autoincrement:)`` public final class ColumnDefinition { enum Index { case none @@ -1364,12 +1477,10 @@ public final class ColumnDefinition { /// See /// for more information. /// - /// When you want to define a primary key on multiple columns, do not use - /// this method. Use ``TableDefinition/primaryKey(_:onConflict:)`` instead. - /// - /// Related SQLite documentation: - /// - - /// - + /// - warning: This is a legacy interface that is preserved for backwards + /// compatibility. Use of this interface is not recommended: prefer + /// ``TableDefinition/primaryKey(_:_:onConflict:)`` + /// instead. /// /// - parameters: /// - conflictResolution: An optional ``Database/ConflictResolution``. From cd16e921fe743bf5ccbf8b4145e5ad7cf8a27aec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 11:47:56 +0100 Subject: [PATCH 50/69] Tests for primary key definition with NOT NULL constraint by default --- .../Schema/TableDefinition.swift | 10 +- Tests/GRDBTests/TableDefinitionTests.swift | 113 ++++++++++++++---- 2 files changed, 99 insertions(+), 24 deletions(-) diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index ca2c8d67d..279150231 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -609,9 +609,13 @@ public final class TableDefinition { onConflict conflictResolution: Database.ConflictResolution? = nil) -> ColumnDefinition { - column(name, type) - .notNull() - .primaryKey(onConflict: conflictResolution) + let pk = column(name, type).primaryKey(onConflict: conflictResolution) + if type == .integer { + // INTEGER PRIMARY KEY is always NOT NULL + return pk + } else { + return pk.notNull() + } } /// Defines the primary key on multiple columns. diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index e63c134d6..5c32c5204 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -8,7 +8,7 @@ class TableDefinitionTests: GRDBTestCase { try dbQueue.inDatabase { db in // Simple table creation try db.create(table: "test") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } @@ -25,7 +25,7 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test", temporary: true, ifNotExists: true, withoutRowID: true) { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } assertEqualSQL(lastSQLQuery!, """ CREATE TEMPORARY TABLE IF NOT EXISTS "test" (\ @@ -36,7 +36,7 @@ class TableDefinitionTests: GRDBTestCase { try dbQueue.inDatabase { db in try db.create(table: "test2", options: [.temporary, .ifNotExists, .withoutRowID]) { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } assertEqualSQL(lastSQLQuery!, """ CREATE TEMPORARY TABLE IF NOT EXISTS "test2" (\ @@ -59,7 +59,7 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test3", options: [.strict]) { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("a", .integer) t.column("b", .real) t.column("c", .text) @@ -145,7 +145,7 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in try db.create(table: "test") { t in - t.column("id", .integer).primaryKey(onConflict: .fail) + t.primaryKey("id", .integer, onConflict: .fail) } assertEqualSQL(lastSQLQuery!, """ CREATE TABLE "test" (\ @@ -156,6 +156,7 @@ class TableDefinitionTests: GRDBTestCase { } try dbQueue.inTransaction { db in try db.create(table: "test") { t in + // legacy api t.column("id", .integer).primaryKey(autoincrement: true) } assertEqualSQL(lastSQLQuery!, """ @@ -332,7 +333,7 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parent") { t in - t.column("name", .text).primaryKey() + t.primaryKey("name", .text) t.column("email", .text).unique() } try db.create(table: "pkless") { t in @@ -393,6 +394,7 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in try db.create(table: "test") { t in + // Legacy api t.primaryKey(["a", "b"]) t.column("a", .text) t.column("b", .text) @@ -408,6 +410,23 @@ class TableDefinitionTests: GRDBTestCase { } try dbQueue.inTransaction { db in try db.create(table: "test") { t in + t.primaryKey { pk in + pk.column("a", .text) + pk.column("b", .text) + } + } + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "a" TEXT NOT NULL, \ + "b" TEXT NOT NULL, \ + PRIMARY KEY ("a", "b")\ + ) + """) + return .rollback + } + try dbQueue.inTransaction { db in + try db.create(table: "test") { t in + // Legacy api t.primaryKey(["a", "b"], onConflict: .fail) t.column("a", .text) t.column("b", .text) @@ -421,6 +440,22 @@ class TableDefinitionTests: GRDBTestCase { """) return .rollback } + try dbQueue.inTransaction { db in + try db.create(table: "test") { t in + t.primaryKey(onConflict: .fail) { pk in + pk.column("a", .text) + pk.column("b", .text) + } + } + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "a" TEXT NOT NULL, \ + "b" TEXT NOT NULL, \ + PRIMARY KEY ("a", "b") ON CONFLICT FAIL\ + ) + """) + return .rollback + } } func testTableUniqueKey() throws { @@ -449,9 +484,10 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parent") { t in - t.primaryKey(["a", "b"]) - t.column("a", .text) - t.column("b", .text) + t.primaryKey { pk in + pk.column("a", .text) + pk.column("b", .text) + } } try db.create(table: "child") { t in t.foreignKey(["c", "d"], references: "parent", onDelete: .cascade, onUpdate: .cascade) @@ -526,7 +562,7 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test1") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("id2", .integer).references("test1") } assertEqualSQL(lastSQLQuery!, """ @@ -536,34 +572,69 @@ class TableDefinitionTests: GRDBTestCase { ) """) - try db.create(table: "test2") { t in + try db.create(table: "test2_legacy") { t in + // Legacy api t.column("id", .integer) - t.column("id2", .integer).references("test2") + t.column("id2", .integer).references("test2_legacy") t.primaryKey(["id"]) } assertEqualSQL(lastSQLQuery!, """ - CREATE TABLE "test2" (\ + CREATE TABLE "test2_legacy" (\ "id" INTEGER, \ - "id2" INTEGER REFERENCES "test2"("id"), \ + "id2" INTEGER REFERENCES "test2_legacy"("id"), \ PRIMARY KEY ("id")\ ) """) - try db.create(table: "test3") { t in + try db.create(table: "test2") { t in + t.column("id2", .integer).references("test2") + t.primaryKey { pk in + pk.column("id", .integer) + } + } + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test2" (\ + "id2" INTEGER REFERENCES "test2"("id"), \ + "id" INTEGER NOT NULL, \ + PRIMARY KEY ("id")\ + ) + """) + + try db.create(table: "test3Legacy") { t in t.column("a", .integer) t.column("b", .integer) t.column("c", .integer) t.column("d", .integer) - t.foreignKey(["c", "d"], references: "test3") + t.foreignKey(["c", "d"], references: "test3Legacy") t.primaryKey(["a", "b"]) } assertEqualSQL(lastSQLQuery!, """ - CREATE TABLE "test3" (\ + CREATE TABLE "test3Legacy" (\ "a" INTEGER, \ "b" INTEGER, \ "c" INTEGER, \ "d" INTEGER, \ PRIMARY KEY ("a", "b"), \ + FOREIGN KEY ("c", "d") REFERENCES "test3Legacy"("a", "b")\ + ) + """) + + try db.create(table: "test3") { t in + t.column("c", .integer) + t.column("d", .integer) + t.foreignKey(["c", "d"], references: "test3") + t.primaryKey { pk in + pk.column("a", .integer) + pk.column("b", .integer) + } + } + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test3" (\ + "c" INTEGER, \ + "d" INTEGER, \ + "a" INTEGER NOT NULL, \ + "b" INTEGER NOT NULL, \ + PRIMARY KEY ("a", "b"), \ FOREIGN KEY ("c", "d") REFERENCES "test3"("a", "b")\ ) """) @@ -774,7 +845,7 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } XCTAssertTrue(try db.tableExists("test")) @@ -790,7 +861,7 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("a", .text) t.column("b", .text) } @@ -813,7 +884,7 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("a", .text) t.column("b", .text) } @@ -830,7 +901,7 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(index: "test_on_name", on: "test", columns: ["name"]) From f5ebf0de4d1b0564c3ad444ad4267de7c1a98d3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 12:35:47 +0100 Subject: [PATCH 51/69] Use primary key definitions with NOT NULL constraint by default --- Documentation/AssociationsBasics.md | 2 +- GRDB/Core/Database.swift | 2 +- GRDB/Documentation.docc/DatabaseSchema.md | 13 +++---- GRDB/Documentation.docc/SingleRowTables.md | 12 +++---- .../Association/HasOneAssociation.swift | 2 +- .../Schema/TableDefinition.swift | 36 +++++++++++++------ README.md | 2 +- .../GRDBTests/AssociationAggregateTests.swift | 6 ++-- ...ciationBelongsToDecodableRecordTests.swift | 4 +-- ...ciationBelongsToFetchableRecordTests.swift | 4 +-- .../AssociationBelongsToRowScopeTests.swift | 4 +-- ...sociationBelongsToSQLDerivationTests.swift | 4 +-- .../AssociationBelongsToSQLTests.swift | 10 +++--- .../AssociationChainRowScopesTests.swift | 8 ++--- .../GRDBTests/AssociationChainSQLTests.swift | 8 ++--- .../AssociationHasManyOrderingTests.swift | 4 +-- .../AssociationHasManySQLTests.swift | 6 ++-- ...sociationHasManyThroughOrderingTests.swift | 4 +-- ...sociationHasManyThroughRowScopeTests.swift | 4 +-- .../AssociationHasOneSQLDerivationTests.swift | 4 +-- .../GRDBTests/AssociationHasOneSQLTests.swift | 6 ++-- ...ociationParallelDecodableRecordTests.swift | 6 ++-- .../AssociationParallelRowScopesTests.swift | 8 ++--- .../AssociationParallelSQLTests.swift | 8 ++--- .../AssociationRowScopeSearchTests.swift | 8 ++--- .../AssociationTableAliasTestsSQLTests.swift | 4 +-- .../DatabaseDateEncodingStrategyTests.swift | 6 ++-- .../DatabasePoolConcurrencyTests.swift | 6 ++-- .../DatabaseRegionObservationTests.swift | 2 +- .../DatabaseUUIDEncodingStrategyTests.swift | 6 ++-- Tests/GRDBTests/DatabaseWriterTests.swift | 4 +-- Tests/GRDBTests/FTS4TableBuilderTests.swift | 8 ++--- Tests/GRDBTests/FTS5TableBuilderTests.swift | 8 ++--- Tests/GRDBTests/FetchRequestTests.swift | 8 ++--- Tests/GRDBTests/JoinSupportTests.swift | 10 +++--- ...MutablePersistableRecordChangesTests.swift | 2 +- ...RecordPersistenceConflictPolicyTests.swift | 16 ++++----- .../MutablePersistableRecordTests.swift | 4 +-- Tests/GRDBTests/SelectStatementTests.swift | 10 +++--- Tests/GRDBTests/SingletonRecordTest.swift | 2 +- ...bleRecord+QueryInterfaceRequestTests.swift | 6 ++-- Tests/GRDBTests/TableTests.swift | 4 +-- .../GRDBTests/ValueObservationRowTests.swift | 2 +- 43 files changed, 148 insertions(+), 135 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index b7fc7d696..320880fa7 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -649,7 +649,7 @@ Here is the recommended [migration] for the **[HasOne]** association: ```swift migrator.registerMigration("Countries") { db in try db.create(table: "country") { t in - t.column("code", .text).primaryKey() // (1) + t.primaryKey("code", .text) // (1) t.column("name", .text) } try db.create(table: "demographics") { t in diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index b174be1a6..fb0e129c2 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1733,7 +1733,7 @@ extension Database { /// // creationDate DATETIME, /// // ) /// try db.create(table: "player") { t in - /// t.column("id", .integer).primaryKey() + /// t.primaryKey("id", .integer) /// t.column("name", .text) /// t.column("creationDate", .datetime) /// } diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index 1727d71bc..95cba05a4 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -128,15 +128,16 @@ try db.create(table: "player") { t in try db.create(table: "team") { t in // Single-column primary key - t.column("id", .text).notNull().primaryKey() + t.primaryKey("id", .text) t.column("name", .text).notNull() } try db.create(table: "membership") { t in // Composite primary key - t.primaryKey(["playerId", "teamId"]) - t.column("playerId", .integer).notNull().references("player") - t.column("teamId", .text).notNull().references("team") + t.primaryKey { pk in + pk.column("playerId", .integer).references("player") + pk.column("teamId", .text).references("team") + } t.column("role", .text).notNull() } @@ -210,13 +211,13 @@ This helps record types play well with the standard `Identifiable` protocol. ```swift // RECOMMENDED try db.create(table: "player") { t in - t.column("id", .text).notNull().primaryKey() + t.primaryKey("id", .text) t.column("name", .text).notNull() } // REQUIRES EXTRA CONFIGURATION try db.create(table: "player") { t in - t.column("uuid", .text).notNull().primaryKey() + t.primaryKey("uuid", .text) t.column("name", .text).notNull() } ``` diff --git a/GRDB/Documentation.docc/SingleRowTables.md b/GRDB/Documentation.docc/SingleRowTables.md index 37241c099..cf90c6995 100644 --- a/GRDB/Documentation.docc/SingleRowTables.md +++ b/GRDB/Documentation.docc/SingleRowTables.md @@ -28,10 +28,8 @@ Those two cases can create a nagging question for the application. By default, i // flag BOOLEAN NOT NULL, // ...) try db.create(table: "appConfiguration") { t in - // Single row guarantee - t.column("id", .integer) - // Have inserts replace the existing row - .primaryKey(onConflict: .replace) + // Single row guarantee: have inserts replace the existing row + t.primaryKey("id", .integer, onConflict: .replace) // Make sure the id column is always 1 .check { $0 == 1 } @@ -48,7 +46,7 @@ When you use , you may wonder if it is a good idea or not to per migrator.registerMigration("appConfiguration") { db in try db.create(table: "appConfiguration") { t in // The single row guarantee - t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 } + t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 } // Define sensible defaults for each column t.column("flag", .boolean).notNull() @@ -74,7 +72,7 @@ The recommended migration creates the table, nothing more: migrator.registerMigration("appConfiguration") { db in try db.create(table: "appConfiguration") { t in // The single row guarantee - t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 } + t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 } // The configuration columns t.column("flag", .boolean).notNull() @@ -175,7 +173,7 @@ We all love to copy and paste, don't we? Just customize the template code below: // Table creation try db.create(table: "appConfiguration") { t in // The single row guarantee - t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 } + t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 } // The configuration columns t.column("flag", .boolean).notNull() diff --git a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift index b3ac2cded..36f9e7708 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift @@ -24,7 +24,7 @@ /// /// ```swift /// try db.create(table: "country") { t in -/// t.column("code", .text).primaryKey() // (1) +/// t.primaryKey("code", .text) // (1) /// t.column("name", .text) /// } /// try db.create(table: "demographics") { t in diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 279150231..f7df7cc7b 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -138,9 +138,7 @@ extension Database { /// t.autoIncrementedPrimaryKey("id") /// /// // uuid TEXT NOT NULL PRIMARY KEY, - /// t.column("uuid", .text) - /// .notNull() - /// .primaryKey() + /// t.primaryKey("uuid", .text) /// /// // email TEXT UNIQUE, /// t.column("email", .text) @@ -154,13 +152,26 @@ extension Database { /// Primary, unique and foreign keys can also be added on several columns: /// /// ```swift + /// // a INTEGER NOT NULL, + /// // b TEXT NOT NULL, /// // PRIMARY KEY (a, b), - /// t.primaryKey(["a", "b"]) + /// t.primaryKey { pk in + /// pk.column("a", .integer) + /// pk.column("b", .text) + /// } /// + /// // a INTEGER, + /// // b TEXT, /// // UNIQUE (a, b) ON CONFLICT REPLACE, + /// t.column("a", .integer) + /// t.column("b", .text) /// t.uniqueKey(["a", "b"], onConflict: .replace) /// + /// // a INTEGER, + /// // b TEXT, /// // FOREIGN KEY (a, b) REFERENCES parents(c, d), + /// t.column("a", .integer) + /// t.column("b", .text) /// t.foreignKey(["a", "b"], references: "parents") /// ``` /// @@ -588,16 +599,14 @@ public final class TableDefinition { /// For example: /// /// ```swift - /// // CREATE TABLE player ( - /// // id INTEGER NOT NULL PRIMARY KEY + /// // CREATE TABLE country ( + /// // isoCode TEXT NOT NULL PRIMARY KEY /// // ) - /// try db.create(table: "player") { t in - /// t.primaryKey("id", .integer) + /// try db.create(table: "country") { t in + /// t.primaryKey("isoCode", .text) /// } /// ``` /// - /// A NOT NULL constraint is always added to the primary key column. - /// /// - parameter name: the column name. /// - parameter type: the column type. /// - returns: A ``ColumnDefinition`` that allows you to refine the @@ -614,6 +623,8 @@ public final class TableDefinition { // INTEGER PRIMARY KEY is always NOT NULL return pk } else { + // Add a not null constraint in order to fix an SQLite bug: + // return pk.notNull() } } @@ -1359,6 +1370,9 @@ public final class PrimaryKeyDefinition { @discardableResult public func column(_ name: String, _ type: Database.ColumnType) -> ColumnDefinition { columns.append(name) + + // Add a not null constraint in order to fix an SQLite bug: + // return tableDefinition.column(name, type).notNull() } } @@ -1472,7 +1486,7 @@ public final class ColumnDefinition { /// // id TEXT NOT NULL PRIMARY KEY /// // ) /// try db.create(table: "player") { t in - /// t.column("id", .text).notNull().primaryKey() + /// t.primaryKey("id", .text) /// } /// ``` /// diff --git a/README.md b/README.md index 7a654e8e3..b8f4cc742 100644 --- a/README.md +++ b/README.md @@ -3309,7 +3309,7 @@ Some database tables have a single-column primary key which is not called "id": ```swift try db.create(table: "country") { t in - t.column("isoCode", .text).notNull().primaryKey() + t.primaryKey("isoCode", .text) t.column("name", .text).notNull() t.column("population", .integer).notNull() } diff --git a/Tests/GRDBTests/AssociationAggregateTests.swift b/Tests/GRDBTests/AssociationAggregateTests.swift index 8f6338e92..8d4333a26 100644 --- a/Tests/GRDBTests/AssociationAggregateTests.swift +++ b/Tests/GRDBTests/AssociationAggregateTests.swift @@ -46,17 +46,17 @@ class AssociationAggregateTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "team") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "player") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("teamId", .integer).references("team") t.column("name", .text) t.column("score", .integer) } try db.create(table: "award") { t in - t.column("customPrimaryKey", .integer).primaryKey() + t.primaryKey("customPrimaryKey", .integer) t.column("teamId", .integer).references("team") t.column("name", .text) } diff --git a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift index a61ae6401..161e8e148 100644 --- a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift @@ -50,11 +50,11 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "teams") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "players") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("teamId", .integer).references("teams") t.column("name", .text) } diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift index b7569d318..06e63f47a 100644 --- a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -52,11 +52,11 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "teams") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "players") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("teamId", .integer).references("teams") t.column("name", .text) } diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift index 8b04ac643..b7f826ab0 100644 --- a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift @@ -22,11 +22,11 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "teams") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "players") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("teamId", .integer).references("teams") t.column("name", .text) } diff --git a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift index 187de9ae9..49a81fa25 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift @@ -30,11 +30,11 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "a") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("bid", .integer).references("b") } } diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index 03aceea2e..c56904732 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -173,7 +173,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "children") { t in @@ -326,7 +326,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "children") { t in @@ -542,7 +542,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "children") { t in @@ -1767,7 +1767,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "children") { t in @@ -2033,7 +2033,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "author") { t in - t.column("id", .text).primaryKey() + t.primaryKey("id", .text) } try db.create(table: "book") { t in t.autoIncrementedPrimaryKey("id") diff --git a/Tests/GRDBTests/AssociationChainRowScopesTests.swift b/Tests/GRDBTests/AssociationChainRowScopesTests.swift index 987d4047b..ca30569e1 100644 --- a/Tests/GRDBTests/AssociationChainRowScopesTests.swift +++ b/Tests/GRDBTests/AssociationChainRowScopesTests.swift @@ -38,20 +38,20 @@ class AssociationChainRowScopesTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "d") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "a") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("bid", .integer).references("b") t.column("name", .text) } try db.create(table: "c") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("bid", .integer).references("b") t.column("did", .integer).references("d") t.column("name", .text) diff --git a/Tests/GRDBTests/AssociationChainSQLTests.swift b/Tests/GRDBTests/AssociationChainSQLTests.swift index e944fe86c..602edfa08 100644 --- a/Tests/GRDBTests/AssociationChainSQLTests.swift +++ b/Tests/GRDBTests/AssociationChainSQLTests.swift @@ -33,17 +33,17 @@ class AssociationChainSQLTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "d") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "a") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("bid", .integer).references("b") } try db.create(table: "c") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("bid", .integer).references("b") t.column("did", .integer).references("d") } diff --git a/Tests/GRDBTests/AssociationHasManyOrderingTests.swift b/Tests/GRDBTests/AssociationHasManyOrderingTests.swift index 40cada2b6..5feb757c9 100644 --- a/Tests/GRDBTests/AssociationHasManyOrderingTests.swift +++ b/Tests/GRDBTests/AssociationHasManyOrderingTests.swift @@ -31,11 +31,11 @@ class AssociationHasManyOrderingTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "team") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text).notNull() } try db.create(table: "player") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("teamId", .integer).notNull().references("team") t.column("name", .text).notNull() t.column("position", .integer).notNull() diff --git a/Tests/GRDBTests/AssociationHasManySQLTests.swift b/Tests/GRDBTests/AssociationHasManySQLTests.swift index ddd47d74e..ffc3fcaab 100644 --- a/Tests/GRDBTests/AssociationHasManySQLTests.swift +++ b/Tests/GRDBTests/AssociationHasManySQLTests.swift @@ -118,7 +118,7 @@ class AssociationHasManySQLTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "children") { t in t.column("parentId", .integer) @@ -214,7 +214,7 @@ class AssociationHasManySQLTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "children") { t in t.column("parentId", .integer).references("parents") @@ -343,7 +343,7 @@ class AssociationHasManySQLTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "children") { t in t.column("parent1Id", .integer).references("parents") diff --git a/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift b/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift index 52522c233..79be3fa5e 100644 --- a/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift +++ b/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift @@ -32,11 +32,11 @@ class AssociationHasManyThroughOrderingTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "team") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text).notNull() } try db.create(table: "player") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text).notNull() } try db.create(table: "playerRole") { t in diff --git a/Tests/GRDBTests/AssociationHasManyThroughRowScopeTests.swift b/Tests/GRDBTests/AssociationHasManyThroughRowScopeTests.swift index a51364990..215720a6b 100644 --- a/Tests/GRDBTests/AssociationHasManyThroughRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationHasManyThroughRowScopeTests.swift @@ -310,10 +310,10 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "muscleGroup") { table in - table.column("id", .text).notNull().primaryKey() + table.primaryKey("id", .text) } try db.create(table: "exercise") { table in - table.column("id", .text).notNull().primaryKey() + table.primaryKey("id", .text) } try db.create(table: "primaryMuscleGroup") { table in table.column("muscleGroupId", .text).notNull().references("muscleGroup", onDelete: .cascade) diff --git a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift index 8d24f0a37..9165292b1 100644 --- a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift @@ -30,10 +30,10 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "b") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("aid", .integer).references("a") t.column("name", .text) } diff --git a/Tests/GRDBTests/AssociationHasOneSQLTests.swift b/Tests/GRDBTests/AssociationHasOneSQLTests.swift index 66d704621..f61c05772 100644 --- a/Tests/GRDBTests/AssociationHasOneSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasOneSQLTests.swift @@ -103,7 +103,7 @@ class AssociationHasOneSQLTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "children") { t in t.column("parentId", .integer) @@ -186,7 +186,7 @@ class AssociationHasOneSQLTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "children") { t in t.column("parentId", .integer).references("parents") @@ -296,7 +296,7 @@ class AssociationHasOneSQLTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "children") { t in t.column("parent1Id", .integer).references("parents") diff --git a/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift index b27807b79..890e25267 100644 --- a/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift @@ -48,15 +48,15 @@ class AssociationParallelDecodableRecordTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "d") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "a") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("bid", .integer).references("b") t.column("did", .integer).references("d") t.column("name", .text) diff --git a/Tests/GRDBTests/AssociationParallelRowScopesTests.swift b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift index 17f9c4e57..cc15b34a0 100644 --- a/Tests/GRDBTests/AssociationParallelRowScopesTests.swift +++ b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift @@ -46,21 +46,21 @@ class AssociationParallelRowScopesTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "d") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) } try db.create(table: "a") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("bid", .integer).references("b") t.column("did", .integer).references("d") t.column("name", .text) } try db.create(table: "c") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("bid", .integer).references("b") t.column("name", .text) } diff --git a/Tests/GRDBTests/AssociationParallelSQLTests.swift b/Tests/GRDBTests/AssociationParallelSQLTests.swift index 9c1b42562..513e9cc27 100644 --- a/Tests/GRDBTests/AssociationParallelSQLTests.swift +++ b/Tests/GRDBTests/AssociationParallelSQLTests.swift @@ -31,18 +31,18 @@ class AssociationParallelSQLTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "d") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "a") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("bid", .integer).references("b") t.column("did", .integer).references("d") } try db.create(table: "c") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("bid", .integer).references("b") } } diff --git a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift index ba579efc3..b8e79922b 100644 --- a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift +++ b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift @@ -34,19 +34,19 @@ class AssociationRowScopeSearchTests: GRDBTestCase { try dbWriter.write { db in // 1. Prepare data try db.create(table: "a") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "b") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("aid", .integer).references("a") } try db.create(table: "c") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("aid", .integer).references("a") t.column("bid", .integer).references("b") } try db.create(table: "d") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("bid", .integer).references("b") } try db.execute(sql: "INSERT INTO a (id) VALUES (1)") diff --git a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift index 7dce1d24e..3ecb21d40 100644 --- a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift +++ b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift @@ -24,10 +24,10 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "a") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("bid1", .integer).references("b") t.column("bid2", .integer).references("b") t.column("parentId", .integer).references("a") diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index 322310e7e..aa4b996fa 100644 --- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -222,7 +222,7 @@ extension DatabaseDateEncodingStrategyTests { extension DatabaseDateEncodingStrategyTests { func testFilterKey() throws { try makeDatabaseQueue().write { db in - try db.create(table: "t") { $0.column("id").primaryKey() } + try db.create(table: "t") { $0.primaryKey("id", .datetime) } do { let request = Table>("t").filter(key: testedDates[0]) @@ -260,7 +260,7 @@ extension DatabaseDateEncodingStrategyTests { } try makeDatabaseQueue().write { db in - try db.create(table: "t") { $0.column("id").primaryKey() } + try db.create(table: "t") { $0.primaryKey("id", .datetime) } do { let request = Table>("t").filter(id: testedDates[0]) @@ -340,7 +340,7 @@ extension DatabaseDateEncodingStrategyTests { } try makeDatabaseQueue().write { db in - try db.create(table: "t") { $0.column("id").primaryKey() } + try db.create(table: "t") { $0.primaryKey("id", .datetime) } do { try Table>("t").deleteOne(db, id: testedDates[0]) diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index feb1700f9..7a329c38c 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -827,7 +827,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue(filename: dbName) try dbPool.write { db in - try db.create(table: "t") { $0.column("id", .integer).primaryKey() } + try db.create(table: "t") { $0.primaryKey("id", .integer) } try db.execute(sql: "INSERT INTO t DEFAULT VALUES") } @@ -1095,7 +1095,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.create(table: "persons") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } } @@ -1172,7 +1172,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.create(table: "persons") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } } diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift index 9e6f69fc7..bec4f9cf9 100644 --- a/Tests/GRDBTests/DatabaseRegionObservationTests.swift +++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift @@ -234,7 +234,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { // let dbQueue = try makeDatabaseQueue() // try dbQueue.write { db in // try db.create(table: "gallery") { t in -// t.column("id", .integer).primaryKey() +// t.primaryKey("id", .integer) // t.column("status", .integer) // } // } diff --git a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift index 80686cfc5..d898df7e7 100644 --- a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift @@ -129,7 +129,7 @@ extension DatabaseUUIDEncodingStrategyTests { extension DatabaseUUIDEncodingStrategyTests { func testFilterKey() throws { try makeDatabaseQueue().write { db in - try db.create(table: "t") { $0.column("id").primaryKey() } + try db.create(table: "t") { $0.primaryKey("id", .blob) } let uuids = [ UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!, UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!, @@ -185,7 +185,7 @@ extension DatabaseUUIDEncodingStrategyTests { } try makeDatabaseQueue().write { db in - try db.create(table: "t") { $0.column("id").primaryKey() } + try db.create(table: "t") { $0.primaryKey("id", .blob) } let uuids = [ UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!, UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!, @@ -304,7 +304,7 @@ extension DatabaseUUIDEncodingStrategyTests { } try makeDatabaseQueue().write { db in - try db.create(table: "t") { $0.column("id").primaryKey() } + try db.create(table: "t") { $0.primaryKey("id", .blob) } let uuids = [ UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!, UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!, diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 8f2e4b1e3..76a7eb88d 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -7,7 +7,7 @@ class DatabaseWriterTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.unsafeReentrantWrite { db1 in try db1.create(table: "table1") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try dbQueue.unsafeReentrantWrite { db2 in try db2.execute(sql: "INSERT INTO table1 (id) VALUES (NULL)") @@ -25,7 +25,7 @@ class DatabaseWriterTests : GRDBTestCase { let dbPool = try makeDatabasePool() try dbPool.unsafeReentrantWrite { db1 in try db1.create(table: "table1") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try dbPool.unsafeReentrantWrite { db2 in try db2.execute(sql: "INSERT INTO table1 (id) VALUES (NULL)") diff --git a/Tests/GRDBTests/FTS4TableBuilderTests.swift b/Tests/GRDBTests/FTS4TableBuilderTests.swift index 2717dbc12..ad7287b4d 100644 --- a/Tests/GRDBTests/FTS4TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS4TableBuilderTests.swift @@ -164,7 +164,7 @@ class FTS4TableBuilderTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "documents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("content", .text) } try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"]) @@ -198,7 +198,7 @@ class FTS4TableBuilderTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.create(table: "documents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("content", .text) } assertDidExecute(sql: "CREATE TABLE \"documents\" (\"id\" INTEGER PRIMARY KEY, \"content\" TEXT)") @@ -215,7 +215,7 @@ class FTS4TableBuilderTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "documents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("content", .text) } try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"]) @@ -244,7 +244,7 @@ class FTS4TableBuilderTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "documents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("content", .text) } try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"]) diff --git a/Tests/GRDBTests/FTS5TableBuilderTests.swift b/Tests/GRDBTests/FTS5TableBuilderTests.swift index 156fa5c57..9bccf6c11 100644 --- a/Tests/GRDBTests/FTS5TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS5TableBuilderTests.swift @@ -222,7 +222,7 @@ class FTS5TableBuilderTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "documents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("content", .text) } try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"]) @@ -256,7 +256,7 @@ class FTS5TableBuilderTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.create(table: "documents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("content", .text) } assertDidExecute(sql: "CREATE TABLE \"documents\" (\"id\" INTEGER PRIMARY KEY, \"content\" TEXT)") @@ -280,7 +280,7 @@ class FTS5TableBuilderTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "documents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("content", .text) } try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"]) @@ -309,7 +309,7 @@ class FTS5TableBuilderTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "documents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("content", .text) } try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"]) diff --git a/Tests/GRDBTests/FetchRequestTests.swift b/Tests/GRDBTests/FetchRequestTests.swift index 4c36f1872..a8430b187 100644 --- a/Tests/GRDBTests/FetchRequestTests.swift +++ b/Tests/GRDBTests/FetchRequestTests.swift @@ -8,7 +8,7 @@ class FetchRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.execute(sql: "INSERT INTO table1 DEFAULT VALUES") try db.execute(sql: "INSERT INTO table1 DEFAULT VALUES") @@ -25,7 +25,7 @@ class FetchRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } let derivedExpression = request > 0 @@ -41,7 +41,7 @@ class FetchRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } do { @@ -66,7 +66,7 @@ class FetchRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } let sqlRequest: SQLRequest = "SELECT * FROM (\(request))" diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index 9de30a497..61f94e027 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -216,26 +216,26 @@ class JoinSupportTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "t1") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text).notNull() } try db.create(table: "t2") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("t1id", .integer).notNull().references("t1", onDelete: .cascade) t.column("name", .text).notNull() t.uniqueKey(["t1id", "name"]) } try db.create(table: "t3") { t in - t.column("t1id", .integer).primaryKey().references("t1", onDelete: .cascade) + t.primaryKey("t1id", .integer).references("t1", onDelete: .cascade) t.column("name", .text).notNull() t.column("ignored", .integer) } try db.create(table: "t4") { t in - t.column("t1id", .integer).primaryKey().references("t1", onDelete: .cascade) + t.primaryKey("t1id", .integer).references("t1", onDelete: .cascade) t.column("name", .text).notNull() } try db.create(table: "t5") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("t3id", .integer).references("t3", onDelete: .cascade) t.column("t4id", .integer).references("t4", onDelete: .cascade) t.column("name", .text).notNull() diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index bc974114b..bfa1bf32a 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -31,7 +31,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "players") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("name", .text) t.column("score", .integer) t.column("creationDate", .datetime) diff --git a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift index 1caa68b1c..5ebae5d26 100644 --- a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift @@ -119,7 +119,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "records") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } // Insert @@ -139,7 +139,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "records") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } // Insert @@ -158,7 +158,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "records") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } // Insert @@ -202,7 +202,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { try dbQueue.writeWithoutTransaction { db in try db.create(table: "records") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("email", .text).unique() } @@ -254,7 +254,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "records") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } // Insert @@ -274,7 +274,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "records") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } // Insert @@ -294,7 +294,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "records") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } // Insert @@ -314,7 +314,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "records") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } // Insert diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index 3b0528978..5b708c5c9 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -1122,7 +1122,7 @@ class MutablePersistableRecordTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "records") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("a", .text) t.column("b", .text) t.column("c", .integer).notNull().defaults(to: 123) @@ -1157,7 +1157,7 @@ class MutablePersistableRecordTests: GRDBTestCase { // Expect database errors when missing columns must have a value try db.drop(table: "records") try db.create(table: "records") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("a", .text) t.column("b", .text).notNull() } diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index f68746e10..959a1d4f4 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -312,25 +312,25 @@ class SelectStatementTests : GRDBTestCase { } try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("id3", .integer).references("table3", column: "id", onDelete: .cascade, onUpdate: .cascade) t.column("id4", .integer).references("table4", column: "id", onDelete: .setNull, onUpdate: .cascade) t.column("a", .integer) t.column("b", .integer) } try db.create(table: "table2") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("a", .integer) t.column("b", .integer) } try db.create(table: "table3") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "table4") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.create(table: "table5") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) } try db.execute(sql: "CREATE TRIGGER table5trigger AFTER INSERT ON table5 BEGIN INSERT INTO table1 (id3, id4, a, b) VALUES (NULL, NULL, 0, 0); END") diff --git a/Tests/GRDBTests/SingletonRecordTest.swift b/Tests/GRDBTests/SingletonRecordTest.swift index d526a4a2b..13bf62384 100644 --- a/Tests/GRDBTests/SingletonRecordTest.swift +++ b/Tests/GRDBTests/SingletonRecordTest.swift @@ -41,7 +41,7 @@ class SingletonRecordTest: GRDBTestCase { // Table creation try db.create(table: "appConfiguration") { t in // Single row guarantee - t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 } + t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 } // The configuration columns t.column("text", .text).notNull() diff --git a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index 3553cec4c..19182f7aa 100644 --- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -328,7 +328,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { try dbQueue.inTransaction { db in struct Player: TableRecord { } try db.create(table: "player") { t in - t.column("a", .integer).notNull().primaryKey() + t.primaryKey("a", .integer) } try XCTAssertFalse(Player.exists(db, key: 1)) @@ -343,7 +343,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { try dbQueue.inTransaction { db in struct Player: TableRecord { } try db.create(table: "player") { t in - t.column("id", .text).notNull().primaryKey() + t.primaryKey("id", .text) } try XCTAssertFalse(Player.exists(db, key: "foo")) @@ -397,7 +397,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { var id: String } try db.create(table: "player") { t in - t.column("id", .text).notNull().primaryKey() + t.primaryKey("id", .text) } try XCTAssertFalse(Player.exists(db, id: "foo")) diff --git a/Tests/GRDBTests/TableTests.swift b/Tests/GRDBTests/TableTests.swift index 375649d4d..6b67e8092 100644 --- a/Tests/GRDBTests/TableTests.swift +++ b/Tests/GRDBTests/TableTests.swift @@ -728,7 +728,7 @@ class TableTests: GRDBTestCase { t.uniqueKey(["b", "c"]) } try db.create(table: "country") { t in - t.column("code", .text).notNull().primaryKey() + t.primaryKey("code", .text) } try db.create(table: "document") { t in t.column("a") @@ -883,7 +883,7 @@ class TableTests: GRDBTestCase { t.uniqueKey(["b", "c"]) } try db.create(table: "country") { t in - t.column("code", .text).notNull().primaryKey() + t.primaryKey("code", .text) } try db.create(table: "document") { t in t.column("a") diff --git a/Tests/GRDBTests/ValueObservationRowTests.swift b/Tests/GRDBTests/ValueObservationRowTests.swift index 5b01e8e63..dccf8c445 100644 --- a/Tests/GRDBTests/ValueObservationRowTests.swift +++ b/Tests/GRDBTests/ValueObservationRowTests.swift @@ -126,7 +126,7 @@ class ValueObservationRowTests: GRDBTestCase { [["content":"foo"]]], setup: { db in try db.create(table: "documents") { t in - t.column("id", .integer).primaryKey() + t.primaryKey("id", .integer) t.column("content", .text) } try db.create(virtualTable: "ft_documents", using: FTS4()) { t in From c7df15faf5b7cf1c5ede622484d5deb12970b591 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 12:41:00 +0100 Subject: [PATCH 52/69] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d65ffb4b9..f00475837 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -108,6 +108,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime. - **New**: `Database.registerAccess(to:)` has `ValueObservation` track a region. This helps building optimized observations of a constant database region with `ValueObservation.trackingConstantRegion(_:)`. - **New**: Open several connections to the same in-memory databases with `DatabaseQueue(named:)`. +- **New**: `TableDefinition` has new `primaryKey` methods that fix [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls) by adding NOT NULL constraints to primary key columns. Previous techniques for defining the primary key are preserved for backwards compatibility, but their use is not recommended. - **New**: [#1293](https://github.com/groue/GRDB.swift/pull/1293) by [@groue](https://github.com/groue): Enable concurrent reads from a WAL snapshot. ## 6.3.1 From 7a9b8093ed94b6a8308999d0d2d268b1f76ada68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 12:46:23 +0100 Subject: [PATCH 53/69] Fix Swiftlint warnings --- GRDB/Core/WALSnapshot.swift | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index aa690b21b..7ce291061 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -36,12 +36,16 @@ final class WALSnapshot: Sendable { } guard code == SQLITE_OK else { if sqlite3_get_autocommit(db.sqliteConnection) != 0 { - throw DatabaseError(resultCode: code, message: "Can't create snapshot because database is in autocommit mode.") + throw DatabaseError(resultCode: code, message: """ + Can't create snapshot because database is in autocommit mode. + """) } if let journalMode = try? String.fetchOne(db, sql: "PRAGMA journal_mode"), journalMode != "wal" { - throw DatabaseError(resultCode: code, message: "Can't create snapshot because database is not in WAL mode.") + throw DatabaseError(resultCode: code, message: """ + Can't create snapshot because database is not in WAL mode. + """) } throw DatabaseError(resultCode: code) } @@ -63,8 +67,6 @@ final class WALSnapshot: Sendable { func compare(_ other: WALSnapshot) -> CInt { return sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot) } - - // swiftlint:disable:next line_length #else static let available = false From f774aa7c0784f069246be1fc098ab543cc22d7a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 12:46:59 +0100 Subject: [PATCH 54/69] Fix tests for named in-memory database --- Tests/GRDBTests/DatabaseQueueInMemoryTests.swift | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift b/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift index 2c20ff867..35c314a8e 100644 --- a/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift +++ b/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift @@ -20,23 +20,25 @@ class DatabaseQueueInMemoryTests : GRDBTestCase { } func test_shared_in_memory_database() throws { - let baz = try DatabaseQueue(named: "dbA").write { db in + let name = UUID().uuidString + let baz = try DatabaseQueue(named: name).write { db in try db.execute(sql: "CREATE TABLE foo (bar TEXT)") try db.execute(sql: "INSERT INTO foo (bar) VALUES ('baz')") return try String.fetchOne(db, sql: "SELECT bar FROM foo")! } XCTAssertEqual(baz, "baz") } - + func test_shared_in_memory_databases_are_shared_by_name() throws { - let dbA = try DatabaseQueue(named: "dbA") + let nameA = UUID().uuidString + let dbA = try DatabaseQueue(named: nameA) try dbA.write { db in try db.execute(sql: "CREATE TABLE foo (bar TEXT)") } try withExtendedLifetime(dbA) { - try XCTAssertTrue(DatabaseQueue(named: "dbA").read { try $0.tableExists("foo") }) - try XCTAssertFalse(DatabaseQueue(named: "dbB").read { try $0.tableExists("foo") }) + try XCTAssertTrue(DatabaseQueue(named: nameA).read { try $0.tableExists("foo") }) + try XCTAssertFalse(DatabaseQueue(named: UUID().uuidString).read { try $0.tableExists("foo") }) } } } From f8728bbed82b9a28203b53ccd764bf1acbbb5ea1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 13:01:42 +0100 Subject: [PATCH 55/69] Enhance documentation --- GRDB/QueryInterface/Schema/TableDefinition.swift | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index f7df7cc7b..11f775f97 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -117,14 +117,20 @@ extension Database { /// The `column()` method returns a ``ColumnDefinition`` that you can /// further configure: /// - /// ### NOT NULL constraints, DEFAULT values + /// ### Not null constraints, default values /// /// ```swift /// // email TEXT NOT NULL, /// t.column("email", .text).notNull() /// + /// // name TEXT DEFAULT 'O''Reilly', + /// t.column("name", .text).defaults(to: "O'Reilly") + /// /// // flag BOOLEAN NOT NULL DEFAULT 0, /// t.column("flag", .boolean).notNull().defaults(to: false) + /// + /// // creationDate DATETIME DEFAULT CURRENT_TIMESTAMP, + /// t.column("creationDate", .datetime).defaults(sql: "CURRENT_TIMESTAMP") /// ``` /// /// ### Primary, unique, and foreign keys From 7bd1992e612f44ab2c270b7676982e2279a5a37e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 14:09:25 +0100 Subject: [PATCH 56/69] Fix ergonomics issue with the definition of compound primary key If the user would forget the PrimaryKeyDefinition, the primary was not defined: try db.create(table: "membership") { t in // WRONG: pk is unused t.primaryKey { pk in t.column("playerId", .integer) t.column("teamId", .text) } } The fix is to remove the PrimaryKeyDefinition: try db.create(table: "membership") { t in t.primaryKey { t.column("playerId", .integer) t.column("teamId", .text) } } --- GRDB/Documentation.docc/DatabaseSchema.md | 6 +- .../Schema/TableDefinition.swift | 114 +++++++----------- Tests/GRDBTests/TableDefinitionTests.swift | 34 +++--- 3 files changed, 64 insertions(+), 90 deletions(-) diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index 95cba05a4..2d6ae1575 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -134,9 +134,9 @@ try db.create(table: "team") { t in try db.create(table: "membership") { t in // Composite primary key - t.primaryKey { pk in - pk.column("playerId", .integer).references("player") - pk.column("teamId", .text).references("team") + t.primaryKey { + t.column("playerId", .integer).references("player") + t.column("teamId", .text).references("team") } t.column("role", .text).notNull() } diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 11f775f97..e755deea2 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -161,9 +161,9 @@ extension Database { /// // a INTEGER NOT NULL, /// // b TEXT NOT NULL, /// // PRIMARY KEY (a, b), - /// t.primaryKey { pk in - /// pk.column("a", .integer) - /// pk.column("b", .text) + /// t.primaryKey { + /// t.column("a", .integer) + /// t.column("b", .text) /// } /// /// // a INTEGER, @@ -493,7 +493,6 @@ public struct TableOptions: OptionSet { /// - ``autoIncrementedPrimaryKey(_:onConflict:)`` /// - ``primaryKey(_:_:onConflict:)`` /// - ``primaryKey(onConflict:body:)`` -/// - ``PrimaryKeyDefinition`` /// /// ### Define a Foreign Key /// @@ -517,9 +516,10 @@ public struct TableOptions: OptionSet { /// /// - ``primaryKey(_:onConflict:)`` public final class TableDefinition { - private typealias KeyConstraint = ( - columns: [String], - conflictResolution: Database.ConflictResolution?) + struct KeyConstraint { + var columns: [String] + var conflictResolution: Database.ConflictResolution? + } private struct ForeignKeyConstraint { var columns: [String] @@ -555,6 +555,7 @@ public final class TableDefinition { private let name: String private let options: TableOptions private var columns: [ColumnItem] = [] + private var inPrimaryKeyBody = false private var primaryKeyConstraint: KeyConstraint? private var uniqueKeyConstraints: [KeyConstraint] = [] private var foreignKeyConstraints: [ForeignKeyConstraint] = [] @@ -647,9 +648,9 @@ public final class TableDefinition { /// // PRIMARY KEY (citizenId, countryCode) /// // ) /// try db.create(table: "passport") { t in - /// t.primaryKey { pk in - /// pk.column("citizenId", .integer) - /// pk.column("countryCode", .text) + /// t.primaryKey { + /// t.column("citizenId", .integer) + /// t.column("countryCode", .text) /// } /// t.column("issueDate", .date).notNull() /// } @@ -658,12 +659,19 @@ public final class TableDefinition { /// A NOT NULL constraint is always added to the primary key columns. public func primaryKey( onConflict conflictResolution: Database.ConflictResolution? = nil, - body: (PrimaryKeyDefinition) throws -> Void) + body: () throws -> Void) rethrows { - let pk = PrimaryKeyDefinition(tableDefinition: self) - try body(pk) - primaryKey(pk.columns, onConflict: conflictResolution) + guard primaryKeyConstraint == nil else { + // Programmer error + fatalError("can't define several primary keys") + } + primaryKeyConstraint = KeyConstraint(columns: [], conflictResolution: conflictResolution) + + let oldValue = inPrimaryKeyBody + inPrimaryKeyBody = true + defer { inPrimaryKeyBody = oldValue } + try body() } /// Appends a table column. @@ -689,6 +697,14 @@ public final class TableDefinition { public func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition { let column = ColumnDefinition(name: name, type: type) columns.append(.definition(column)) + + if inPrimaryKeyBody { + // Add a not null constraint in order to fix an SQLite bug: + // + column.notNull() + primaryKeyConstraint!.columns.append(name) + } + return column } @@ -705,6 +721,7 @@ public final class TableDefinition { /// } /// ``` public func column(sql: String) { + GRDBPrecondition(!inPrimaryKeyBody, "Primary key columns can not be defined with raw SQL") columns.append(.literal(SQL(sql: sql))) } @@ -723,6 +740,7 @@ public final class TableDefinition { /// } /// ``` public func column(literal: SQL) { + GRDBPrecondition(!inPrimaryKeyBody, "Primary key columns can not be defined with raw SQL") columns.append(.literal(literal)) } @@ -760,7 +778,7 @@ public final class TableDefinition { // Programmer error fatalError("can't define several primary keys") } - primaryKeyConstraint = (columns: columns, conflictResolution: conflictResolution) + primaryKeyConstraint = KeyConstraint(columns: columns, conflictResolution: conflictResolution) } /// Adds a unique constraint. @@ -798,7 +816,7 @@ public final class TableDefinition { /// - parameter conflictResolution: An optional conflict resolution /// (see ). public func uniqueKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil) { - uniqueKeyConstraints.append((columns: columns, conflictResolution: conflictResolution)) + uniqueKeyConstraints.append(KeyConstraint(columns: columns, conflictResolution: conflictResolution)) } /// Adds a foreign key. @@ -989,8 +1007,8 @@ public final class TableDefinition { chunks.append(name.quotedDatabaseIdentifier) let primaryKeyColumns: [String] - if let (columns, _) = primaryKeyConstraint { - primaryKeyColumns = columns + if let primaryKeyConstraint { + primaryKeyColumns = primaryKeyConstraint.columns } else if let column = columns.lazy.compactMap(\.columnDefinition).first(where: { $0.primaryKey != nil }) { primaryKeyColumns = [column.name] } else { @@ -1009,22 +1027,22 @@ public final class TableDefinition { try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) }) - if let (columns, conflictResolution) = primaryKeyConstraint { + if let constraint = primaryKeyConstraint { var chunks: [String] = [] chunks.append("PRIMARY KEY") - chunks.append("(\(columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))") - if let conflictResolution = conflictResolution { + chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))") + if let conflictResolution = constraint.conflictResolution { chunks.append("ON CONFLICT") chunks.append(conflictResolution.rawValue) } items.append(chunks.joined(separator: " ")) } - for (columns, conflictResolution) in uniqueKeyConstraints { + for constraint in uniqueKeyConstraints { var chunks: [String] = [] chunks.append("UNIQUE") - chunks.append("(\(columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))") - if let conflictResolution = conflictResolution { + chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))") + if let conflictResolution = constraint.conflictResolution { chunks.append("ON CONFLICT") chunks.append(conflictResolution.rawValue) } @@ -1335,54 +1353,6 @@ public final class TableAlteration { } } -/// Describes the primary key of a table. -/// -/// See ``TableDefinition/primaryKey(onConflict:body:)``. -public final class PrimaryKeyDefinition { - let tableDefinition: TableDefinition - var columns: [String] - - init(tableDefinition: TableDefinition) { - self.tableDefinition = tableDefinition - self.columns = [] - } - - /// Appends a column to the primary key. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE passport ( - /// // citizenId INTEGER NOT NULL, - /// // countryCode TEXT NOT NULL, - /// // issueDate DATE NOT NULL, - /// // PRIMARY KEY (citizenId, countryCode) - /// // ) - /// try db.create(table: "passport") { t in - /// t.primaryKey { pk in - /// pk.column("citizenId", .integer) - /// pk.column("countryCode", .text) - /// } - /// t.column("issueDate", .date).notNull() - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameter name: the column name. - /// - parameter type: the column type. - /// - returns: A ``ColumnDefinition`` that allows you to refine the - /// column definition. - @discardableResult - public func column(_ name: String, _ type: Database.ColumnType) -> ColumnDefinition { - columns.append(name) - - // Add a not null constraint in order to fix an SQLite bug: - // - return tableDefinition.column(name, type).notNull() - } -} - /// Describes a database column. /// /// You get instances of `ColumnDefinition` when you create or alter a database diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index 5c32c5204..eebe2d597 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -410,15 +410,19 @@ class TableDefinitionTests: GRDBTestCase { } try dbQueue.inTransaction { db in try db.create(table: "test") { t in - t.primaryKey { pk in - pk.column("a", .text) - pk.column("b", .text) + t.column("regular1") + t.primaryKey { + t.column("a", .text) + t.column("b", .text) } + t.column("regular2") } assertEqualSQL(lastSQLQuery!, """ CREATE TABLE "test" (\ + "regular1", \ "a" TEXT NOT NULL, \ "b" TEXT NOT NULL, \ + "regular2", \ PRIMARY KEY ("a", "b")\ ) """) @@ -442,14 +446,14 @@ class TableDefinitionTests: GRDBTestCase { } try dbQueue.inTransaction { db in try db.create(table: "test") { t in - t.primaryKey(onConflict: .fail) { pk in - pk.column("a", .text) - pk.column("b", .text) + t.primaryKey(onConflict: .fail) { + t.column("a", .text).defaults(to: "O'Reilly") + t.column("b", .text) } } assertEqualSQL(lastSQLQuery!, """ CREATE TABLE "test" (\ - "a" TEXT NOT NULL, \ + "a" TEXT NOT NULL DEFAULT 'O''Reilly', \ "b" TEXT NOT NULL, \ PRIMARY KEY ("a", "b") ON CONFLICT FAIL\ ) @@ -484,9 +488,9 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parent") { t in - t.primaryKey { pk in - pk.column("a", .text) - pk.column("b", .text) + t.primaryKey { + t.column("a", .text) + t.column("b", .text) } } try db.create(table: "child") { t in @@ -588,8 +592,8 @@ class TableDefinitionTests: GRDBTestCase { try db.create(table: "test2") { t in t.column("id2", .integer).references("test2") - t.primaryKey { pk in - pk.column("id", .integer) + t.primaryKey { + t.column("id", .integer) } } assertEqualSQL(lastSQLQuery!, """ @@ -623,9 +627,9 @@ class TableDefinitionTests: GRDBTestCase { t.column("c", .integer) t.column("d", .integer) t.foreignKey(["c", "d"], references: "test3") - t.primaryKey { pk in - pk.column("a", .integer) - pk.column("b", .integer) + t.primaryKey { + t.column("a", .integer) + t.column("b", .integer) } } assertEqualSQL(lastSQLQuery!, """ From 2e2b79a3a9ccf9d2ed9e8c2ce0402e37d0542251 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 14:29:14 +0100 Subject: [PATCH 57/69] The technique for exposing rowids to record types has moved to DocC --- Documentation/FullTextSearch.md | 5 +- README.md | 129 +------------------------------- 2 files changed, 5 insertions(+), 129 deletions(-) diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 631b0e7b2..b0c2f61a0 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -726,10 +726,7 @@ let books = Book.fetchAll(db, sql: sql, arguments: [pattern]) **You can define [record](../README.md#records) types around the full-text virtual tables.** -However these tables don't have any explicit primary key. Instead, they use the [implicit rowid primary key](../README.md#the-implicit-rowid-primary-key): a special hidden column named `rowid`. - -You will have to [expose this hidden column](../README.md#exposing-the-rowid-column) in order to fetch, delete, and update full-text records by primary key. - +The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) for more information. ## Unicode Full-Text Gotchas diff --git a/README.md b/README.md index b8f4cc742..3f10a8627 100644 --- a/README.md +++ b/README.md @@ -2952,7 +2952,7 @@ For more information about batch updates, see [Update Requests](#update-requests - `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). +**All primary keys are supported**, including composite primary keys that span several columns, and the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html). **To customize persistence methods**, you provide [Persistence Callbacks], described below. Do not attempt at overriding the ready-made persistence methods. @@ -3773,7 +3773,6 @@ GRDB records come with many default behaviors, that are designed to fit most sit - [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)`. - [Beyond FetchableRecord]: the FetchableRecord protocol is not the end of the story. @@ -3867,125 +3866,6 @@ try player.insert(db) > > **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 - -**All SQLite tables have a primary key.** Even when the primary key is not explicit: - -```swift -// No explicit primary key -try db.create(table: "event") { t in - t.column("message", .text) - t.column("date", .datetime) -} - -// No way to define an explicit primary key -try db.create(virtualTable: "book", using: FTS4()) { t in - t.column("title") - t.column("author") - t.column("body") -} -``` - -The implicit primary key is stored in the hidden column `rowid`. Hidden means that `SELECT *` does not select it, and yet it can be selected and queried: `SELECT *, rowid ... WHERE rowid = 1`. - -Some GRDB methods will automatically use this hidden column when a table has no explicit primary key: - -```swift -// SELECT * FROM event WHERE rowid = 1 -let event = try Event.fetchOne(db, id: 1) - -// DELETE FROM book WHERE rowid = 1 -try Book.deleteOne(db, id: 1) -``` - - -#### Exposing the RowID Column - -**By default, a record type that wraps a table without any explicit primary key doesn't know about the hidden rowid column.** - -Without primary key, records don't have any identity, and the [persistence method](#persistence-methods) can behave in undesired fashion: `update()` throws errors, `save()` always performs insertions and may break constraints, `exists()` is always false. - -When SQLite won't let you provide an explicit primary key (as in [full-text](Documentation/FullTextSearch.md) tables, for example), you may want to make your record type fully aware of the hidden rowid column: - -1. Have the `databaseSelection` static property (from the [TableRecord] protocol) return the hidden rowid column: - - ```swift - struct Event : TableRecord { - static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] - } - - // When you subclass Record, you need an override: - class Book : Record { - override class var databaseSelection: [any SQLSelectable] { - [AllColumns(), Column.rowID] - } - } - ``` - - GRDB will then select the `rowid` column by default: - - ```swift - // SELECT *, rowid FROM event - let events = try Event.fetchAll(db) - ``` - -2. Have `init(row:)` from the [FetchableRecord] protocol consume the "rowid" column: - - ```swift - struct Event : FetchableRecord { - var id: Int64? - - init(row: Row) { - id = row[Column.rowID] // or `row[.rowID]` with Swift 5.5+ - } - } - ``` - - Your fetched records will then know their ids: - - ```swift - let event = try Event.fetchOne(db)! - event.id // some value - ``` - -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 { - var id: Int64? - - func encode(to container: inout PersistenceContainer) { - container[Column.rowID] = id // or `container[.rowID]` with Swift 5.5+ - container["message"] = message - container["date"] = date - } - - // Update auto-incremented id upon successful insertion - mutating func didInsert(_ inserted: InsertionSuccess) { - id = inserted.rowID - } - } - ``` - - You will then be able to track your record ids, update them, or check for their existence: - - ```swift - let event = Event(message: "foo", date: Date()) - - // Insertion sets the record id: - try event.insert(db) - event.id // some value - - // Record can be updated: - event.message = "bar" - try event.update(db) - - // Record knows if it exists: - event.exists(db) // true - ``` - - ### Beyond FetchableRecord **Some GRDB users eventually discover that the [FetchableRecord] protocol does not fit all situations.** Use cases that are not well handled by FetchableRecord include: @@ -4401,7 +4281,7 @@ This is the list of record methods, along with their required protocols. The [Re | `record.databaseChanges` | [Record](#record-class) | | | `record.updateChanges(db)` | [Record](#record-class) | | -¹ All unique keys are supported: primary keys (single-column, composite, [implicit RowID](#the-implicit-rowid-primary-key)) and unique indexes: +¹ All unique keys are supported: primary keys (single-column, composite, [`rowid`](https://www.sqlite.org/rowidtable.html)) and unique indexes: ```swift try Player.fetchOne(db, id: 1) // Player? @@ -5429,7 +5309,7 @@ try Player.fetchOne(db, key: ["email": "arthur@example.com"]) // Play try Citizenship.fetchOne(db, key: ["citizenId": 1, "countryCode": "FR"]) // Citizenship? ``` -When the table has no explicit primary key, GRDB uses the [hidden "rowid" column](#the-implicit-rowid-primary-key): +When the table has no explicit primary key, GRDB uses the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html): ```swift // SELECT * FROM document WHERE rowid = 1 @@ -5573,7 +5453,7 @@ try Player.deleteOne(db, key: ["email": "arthur@example.com"]) try Citizenship.deleteOne(db, key: ["citizenId": 1, "countryCode": "FR"]) ``` -When the table has no explicit primary key, GRDB uses the [hidden "rowid" column](#the-implicit-rowid-primary-key): +When the table has no explicit primary key, GRDB uses the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html): ```swift // DELETE FROM document WHERE rowid = 1 @@ -8588,7 +8468,6 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests]. [Embedding SQL in Query Interface Requests]: #embedding-sql-in-query-interface-requests [Full-Text Search]: Documentation/FullTextSearch.md [Migrations]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations -[The Implicit RowID Primary Key]: #the-implicit-rowid-primary-key [The userInfo Dictionary]: #the-userinfo-dictionary [JSON Columns]: #json-columns [FetchableRecord]: #fetchablerecord-protocol From 35e60f2b97b38ee93b711555a1c61de26218192a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 14:48:43 +0100 Subject: [PATCH 58/69] Precision --- GRDB/Documentation.docc/DatabaseSchema.md | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index 2d6ae1575..d1743166f 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -107,7 +107,7 @@ struct Player: Decodable, FetchableRecord { var creationDate: Date // Required CodingKeys customization because - // column are not named like Swift properties + // columns are not named like Swift properties enum CodingKeys: String, CodingKey { case id, fullName = "full_name", score, creationDate = "creation_date" } @@ -221,15 +221,26 @@ try db.create(table: "player") { t in t.column("name", .text).notNull() } ``` -☝️ **If the primary key follows a different naming convention**, `Identifiable` record types will need an extra property: +☝️ **If the primary key follows a different naming convention**, `Identifiable` record types will need a custom `CodingKeys` enum, or an extra property: ```swift -struct Player { - var uuid: String +// Custom coding keys +struct Player: Codable, Identifiable { + var id: String var name: String + + // Required CodingKeys customization because + // columns are not named like Swift properties + enum CodingKeys: String, CodingKey { + case id = "uuid", name + } } -extension Player: Identifiable { +// Extra property +struct Player: Identifiable { + var uuid: String + var name: String + // Required because the primary key column is not 'id' var id: String { uuid } } @@ -275,6 +286,8 @@ try db.create( > on: "team", columns: ["name"], > options: .unique) > ``` +> +> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See for the detailed procedure. ☝️ **If a table misses unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error: From ef019bb9dacbbf185630846dc50a7d902f54d566 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 15:05:45 +0100 Subject: [PATCH 59/69] CHANGELOG --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f00475837..01fd9bd1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -103,12 +103,12 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Version -- **New**: The `Configuration.readQoS` and `writeQoS` properties return the effective quality of service of read-only and write database accesses. This helps application code avoid priority inversion and similar scheduling misuses when needed. +- **New**: `DatabaseReader.configuration.readQoS` and `writeQoS` return the effective quality of service of read-only and write database accesses. This helps application code avoid priority inversion and similar scheduling misuses when needed. - **New**: `DatabaseReader.configuration.maximumReaderCount` returns the effective capacity for concurrent reads, so that application code can adapt when needed. - **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime. - **New**: `Database.registerAccess(to:)` has `ValueObservation` track a region. This helps building optimized observations of a constant database region with `ValueObservation.trackingConstantRegion(_:)`. -- **New**: Open several connections to the same in-memory databases with `DatabaseQueue(named:)`. -- **New**: `TableDefinition` has new `primaryKey` methods that fix [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls) by adding NOT NULL constraints to primary key columns. Previous techniques for defining the primary key are preserved for backwards compatibility, but their use is not recommended. +- **New**: Open several connections to the same in-memory database with `DatabaseQueue(named:)`. +- **New**: `TableDefinition` has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended. - **New**: [#1293](https://github.com/groue/GRDB.swift/pull/1293) by [@groue](https://github.com/groue): Enable concurrent reads from a WAL snapshot. ## 6.3.1 From 5302b98a151a3442c8158ff03238e927a033b5e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 15:12:57 +0100 Subject: [PATCH 60/69] http -> https --- Documentation/AssociationsBasics.md | 2 +- Documentation/GRDB5MigrationGuide.md | 2 +- Documentation/GoodPracticesForDesigningRecordTypes.md | 2 +- Documentation/ReleaseProcess.md | 2 +- Documentation/WhyAdoptGRDB.md | 8 ++++---- GRDB/Documentation.docc/Documentation.md | 2 +- README.md | 10 +++++----- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 320880fa7..4786bf92d 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -511,7 +511,7 @@ When using class names composed of two or more words, the table name should use | Mouse | mouse | `mouse`, `mice`, `maxMouseSize` | | Person | person | `person`, `people`, `personCount` | -If your application relies on non-English names, GRDB may generate unexpected identifiers. If this happens, please [open an issue](http://github.com/groue/GRDB.swift/issues). +If your application relies on non-English names, GRDB may generate unexpected identifiers. If this happens, please [open an issue](https://github.com/groue/GRDB.swift/issues). See [The Structure of a Joined Request] for more information. diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index 41ef70dd5..46ca2117e 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -501,7 +501,7 @@ let publisher = observation [ValueObservation]: ../README.md#valueobservation [DatabaseRegionObservation]: ../README.md#databaseregionobservation -[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB +[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB [removeDuplicates]: ../README.md#valueobservationremoveduplicates [Custom SQL functions]: ../README.md#custom-sql-functions [Batch updates]: ../README.md#update-requests diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index a681e6fc8..953a0e252 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -812,7 +812,7 @@ Instead, have a look at [Database Observation]: [PersistableRecord]: ../README.md#persistablerecord-protocol [Database Observation]: ../README.md#database-changes-observation [ValueObservation]: ../README.md#valueobservation -[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB +[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB [TransactionObserver]: ../README.md#transactionobserver-protocol [Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself [Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables diff --git a/Documentation/ReleaseProcess.md b/Documentation/ReleaseProcess.md index 0ae106b56..e8aa77fb7 100644 --- a/Documentation/ReleaseProcess.md +++ b/Documentation/ReleaseProcess.md @@ -21,7 +21,7 @@ To release a new GRDB version: - Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags` - Push to the master & development branch - `pod trunk push --allow-warnings GRDB.swift.podspec` -- Update http://github.com/groue/WWDCCompanion +- Update https://github.com/groue/WWDCCompanion - Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance): `make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb` diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 062895a40..212a121b0 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -292,14 +292,14 @@ Happy GRDB! :gift: [FCModel]: https://github.com/marcoarment/FCModel [ValueObservation]: ../README.md#valueobservation [Fluent]: https://github.com/vapor/fluent -[FMDB]: http://github.com/ccgus/fmdb -[GRDB]: http://github.com/groue/GRDB.swift +[FMDB]: https://github.com/ccgus/fmdb +[GRDB]: https://github.com/groue/GRDB.swift [PersistableRecord]: ../README.md#records [Realm]: http://realm.io [FetchableRecord]: ../README.md#records -[SQLite.swift]: http://github.com/stephencelis/SQLite.swift +[SQLite.swift]: https://github.com/stephencelis/SQLite.swift [StORM]: https://www.perfect.org/docs/StORM.html -[Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery +[Swift-Kuery]: https://github.com/IBM-Swift/Swift-Kuery [TableRecord]: ../README.md#records [TransactionObserver]: ../README.md#transactionobserver-protocol [query interface]: ../README.md#the-query-interface diff --git a/GRDB/Documentation.docc/Documentation.md b/GRDB/Documentation.docc/Documentation.md index ad7eac38a..e6531907b 100644 --- a/GRDB/Documentation.docc/Documentation.md +++ b/GRDB/Documentation.docc/Documentation.md @@ -12,7 +12,7 @@ It has robust concurrency primitives, so that multi-threaded applications can ef It grants your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to. -Compared to [SQLite.swift](http://github.com/stephencelis/SQLite.swift) or [FMDB](http://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications. +Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMDB](https://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications. ## Topics diff --git a/README.md b/README.md index 3f10a8627..867718343 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ GRDB provides raw access to SQL and advanced SQLite features, because one sometimes enjoys a sharp tool. It has robust concurrency primitives, so that multi-threaded applications can efficiently use their databases. It grants your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to. -Compared to [SQLite.swift](http://github.com/stephencelis/SQLite.swift) or [FMDB](http://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications. +Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMDB](https://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications. It comes with [up-to-date documentation](#documentation), [general guides](#general-guides--good-practices), and it is [fast](https://github.com/groue/GRDB.swift/wiki/Performance). @@ -80,9 +80,9 @@ Programming tools for both database beginners and SQLite experts: In-depth integration with our programming environment: - [Swift Concurrency](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency): `try await` your database. -- [SwiftUI](http://github.com/groue/GRDBQuery): Access and observe the database from your SwiftUI views. +- [SwiftUI](https://github.com/groue/GRDBQuery): Access and observe the database from your SwiftUI views. - [Combine](Documentation/Combine.md): Access and observe the database with Combine publishers. -- [RxSwift](http://github.com/RxSwiftCommunity/RxGRDB): Access and observe the database with RxSwift observables. +- [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB): Access and observe the database with RxSwift observables. ## Usage @@ -8352,7 +8352,7 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [@alextrob](https://github.com/alextrob), [@alexwlchan](https://github.com/alexwlchan), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@eburns-vmware](https://github.com/eburns-vmware), [@felixscheinost](https://github.com/felixscheinost), [@fpillet](http://github.com/fpillet), [@gcox](https://github.com/gcox), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@guidedways](https://github.com/guidedways), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@holsety](https://github.com/holsety), [@jroselightricks](https://github.com/jroselightricks), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@layoutSubviews](https://github.com/layoutSubviews), [@mallman](https://github.com/mallman), [@MartinP7r](https://github.com/MartinP7r), [@Marus](https://github.com/Marus), [@mattgallagher](https://github.com/mattgallagher), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@pp5x](https://github.com/pp5x), [@professordeng](https://github.com/professordeng), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@sberrevoets](https://github.com/sberrevoets), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@steipete](https://github.com/steipete), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@tternes](https://github.com/tternes), [@valexa](https://github.com/valexa), [@wuyuehyang](https://github.com/wuyuehyang), [@ZevEisenberg](https://github.com/ZevEisenberg), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. +- [@alextrob](https://github.com/alextrob), [@alexwlchan](https://github.com/alexwlchan), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@eburns-vmware](https://github.com/eburns-vmware), [@felixscheinost](https://github.com/felixscheinost), [@fpillet](https://github.com/fpillet), [@gcox](https://github.com/gcox), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@guidedways](https://github.com/guidedways), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@holsety](https://github.com/holsety), [@jroselightricks](https://github.com/jroselightricks), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@layoutSubviews](https://github.com/layoutSubviews), [@mallman](https://github.com/mallman), [@MartinP7r](https://github.com/MartinP7r), [@Marus](https://github.com/Marus), [@mattgallagher](https://github.com/mattgallagher), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@pp5x](https://github.com/pp5x), [@professordeng](https://github.com/professordeng), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@sberrevoets](https://github.com/sberrevoets), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@steipete](https://github.com/steipete), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@tternes](https://github.com/tternes), [@valexa](https://github.com/valexa), [@wuyuehyang](https://github.com/wuyuehyang), [@ZevEisenberg](https://github.com/ZevEisenberg), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [@kali](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. @@ -8480,7 +8480,7 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests]. [TableRecord]: #tablerecord-protocol [ValueObservation]: #valueobservation [DatabaseRegionObservation]: #databaseregionobservation -[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB +[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB [DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol [DatabaseRegion]: #databaseregion [SQL Interpolation]: Documentation/SQLInterpolation.md From e3cc15707accb4375362f352043d91235bb3256d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 18:27:26 +0100 Subject: [PATCH 61/69] Move ValueObservation documentation to DocC --- Documentation/AssociationsBasics.md | 1 - Documentation/Combine.md | 10 +- Documentation/CustomSQLiteBuilds.md | 2 +- .../DemoApps/GRDBAsyncDemo/README.md | 2 +- .../DemoApps/GRDBCombineDemo/README.md | 2 +- Documentation/DemoApps/GRDBDemoiOS/README.md | 4 +- Documentation/GRDB5MigrationGuide.md | 4 +- .../GoodPracticesForDesigningRecordTypes.md | 2 +- Documentation/WhyAdoptGRDB.md | 2 +- GRDB/Core/TransactionObserver.swift | 39 +- .../Documentation.docc/DatabaseObservation.md | 11 + GRDB/ValueObservation/Reducers/Map.swift | 14 + .../Reducers/RemoveDuplicates.swift | 41 + .../SharedValueObservation.swift | 32 +- GRDB/ValueObservation/ValueObservation.swift | 398 +++++++++- README.md | 724 ++---------------- 16 files changed, 553 insertions(+), 735 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 4786bf92d..a714f6ebe 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -3009,7 +3009,6 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Codable Records]: ../README.md#codable-records [persistence methods]: ../README.md#persistence-methods [database observation tools]: ../README.md#database-changes-observation -[ValueObservation]: ../README.md#valueobservation [FAQ]: ../README.md#faq-associations [common table expressions]: CommonTableExpressions.md [Common Table Expressions]: CommonTableExpressions.md diff --git a/Documentation/Combine.md b/Documentation/Combine.md index aa0647d24..657569afa 100644 --- a/Documentation/Combine.md +++ b/Documentation/Combine.md @@ -226,11 +226,11 @@ This publisher has the same behavior as ValueObservation: - It notifies an initial value before the eventual changes. - It may coalesce subsequent changes into a single notification. -- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](../README.md#valueobservationremoveduplicates) GRDB operator also. +- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also. - It only completes when it is cancelled. - By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously. - This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservation scheduler](../README.md#valueobservation-scheduling). + This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservationscheduler). For example, the `.immediate` scheduler makes sure the initial value is notified immediately when the publisher is subscribed. It can help your application update the user interface without having to wait for any asynchronous notifications: @@ -248,8 +248,6 @@ This publisher has the same behavior as ValueObservation: Note that the `.immediate` scheduler requires that the publisher is subscribed from the main thread. It raises a fatal error otherwise. -See [ValueObservation Scheduling](../README.md#valueobservation-scheduling) for more information. - #### `SharedValueObservation.publisher()` @@ -390,8 +388,8 @@ let cancellable = hallOfFamePublisher.sink( [DatabaseRegionObservation]: ../README.md#databaseregionobservation [Demo Application]: DemoApps/GRDBCombineDemo/README.md [SQLite]: http://sqlite.org -[ValueObservation]: ../README.md#valueobservation -[SharedValueObservation]: ../README.md#valueobservation-sharing +[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation +[SharedValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sharedvalueobservation [`DatabaseRegionObservation.publisher(in:)`]: #databaseregionobservationpublisherin [`ValueObservation.publisher(in:scheduling:)`]: #valueobservationpublisherinscheduling [`SharedValueObservation.publisher()`]: #sharedvalueobservationpublisher diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index 7873c5852..66f0515c3 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -21,7 +21,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal 2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`. - It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](../README.md#valueobservation) when you use a [Database Pool](../README.md#database-pools). + It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) when you use a [Database Pool](../README.md#database-pools). 3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory. diff --git a/Documentation/DemoApps/GRDBAsyncDemo/README.md b/Documentation/DemoApps/GRDBAsyncDemo/README.md index 5740eee91..6fc5a85e2 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/README.md +++ b/Documentation/DemoApps/GRDBAsyncDemo/README.md @@ -13,7 +13,7 @@ The topics covered in this demo are: - How to setup a database in an iOS app. - How to define a simple [Codable Record](../../../README.md#codable-records). -- How to track database changes and animate a SwiftUI List with an async sequence built from [ValueObservation](../../../README.md#valueobservation). +- How to track database changes and animate a SwiftUI List with an async sequence built from [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation). - How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md). - How to feed SwiftUI previews with a transient database. diff --git a/Documentation/DemoApps/GRDBCombineDemo/README.md b/Documentation/DemoApps/GRDBCombineDemo/README.md index a51bbe7c0..5bb162284 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/README.md +++ b/Documentation/DemoApps/GRDBCombineDemo/README.md @@ -13,7 +13,7 @@ The topics covered in this demo are: - How to setup a database in an iOS app. - How to define a simple [Codable Record](../../../README.md#codable-records). -- How to track database changes and animate a SwiftUI List with [ValueObservation](../../../README.md#valueobservation) Combine publishers. +- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) Combine publishers. - How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md). - How to feed SwiftUI previews with a transient database. diff --git a/Documentation/DemoApps/GRDBDemoiOS/README.md b/Documentation/DemoApps/GRDBDemoiOS/README.md index 210022c97..098f37d79 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/README.md +++ b/Documentation/DemoApps/GRDBDemoiOS/README.md @@ -13,14 +13,14 @@ The topics covered in this demo are: - How to setup a database in an iOS app. - How to define a simple [Codable Record](../../../README.md#codable-records). -- How to track database changes and animate a table view with [ValueObservation](../../../README.md#valueobservation). +- How to track database changes and animate a table view with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation). - How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md). **Files of interest:** - [AppDatabase.swift](GRDBDemoiOS/AppDatabase.swift) - `AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes. + `AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) in order to let the application observe database changes. - [Persistence.swift](GRDBDemoiOS/Persistence.swift) diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index 46ca2117e..2bb4ce4d9 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -499,10 +499,10 @@ let publisher = observation This change is innocuous for database boolean values that are `0`, `1`, or `NULL`. However, it is a breaking change for all other database values. -[ValueObservation]: ../README.md#valueobservation +[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation [DatabaseRegionObservation]: ../README.md#databaseregionobservation [RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB -[removeDuplicates]: ../README.md#valueobservationremoveduplicates +[removeDuplicates]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates() [Custom SQL functions]: ../README.md#custom-sql-functions [Batch updates]: ../README.md#update-requests [SQL Interpolation]: SQLInterpolation.md diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 953a0e252..9befa53bc 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -811,7 +811,7 @@ Instead, have a look at [Database Observation]: [GRDB concurrency rules]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency [PersistableRecord]: ../README.md#persistablerecord-protocol [Database Observation]: ../README.md#database-changes-observation -[ValueObservation]: ../README.md#valueobservation +[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation [RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB [TransactionObserver]: ../README.md#transactionobserver-protocol [Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 212a121b0..1cc6e22af 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -290,7 +290,7 @@ Happy GRDB! :gift: [DatabasePool]: ../README.md#database-pools [Diesel]: http://diesel.rs [FCModel]: https://github.com/marcoarment/FCModel -[ValueObservation]: ../README.md#valueobservation +[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation [Fluent]: https://github.com/vapor/fluent [FMDB]: https://github.com/ccgus/fmdb [GRDB]: https://github.com/groue/GRDB.swift diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 6df6651b8..4b15170a9 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -42,19 +42,42 @@ extension Database { /// Registers closures to be executed after the next or current /// transaction completes. /// - /// For example: + /// This method helps synchronizing the database with other resources, + /// such as files, or system services. + /// + /// In the example below, a `CLLocationManager` starts monitoring a + /// `CLRegion` if and only if it has successfully been stored in + /// the database: /// /// ```swift - /// try dbQueue.write { db in - /// db.afterNextTransaction { _ in - /// print("success") + /// /// Inserts a region in the database, and start monitoring upon + /// /// successful insertion. + /// func startMonitoring(_ db: Database, region: CLRegion) throws { + /// // Make sure database is inside a transaction + /// try db.inSavepoint { + /// + /// // Save the region in the database + /// try insert(...) + /// + /// // Start monitoring if and only if the insertion is + /// // eventually committed to disk + /// db.afterNextTransaction { _ in + /// // locationManager prefers the main queue: + /// DispatchQueue.main.async { + /// locationManager.startMonitoring(for: region) + /// } + /// } + /// + /// return .commit /// } - /// ... - /// } // prints "success" + /// } /// ``` /// - /// Closure are executed in a protected dispatch queue, serialized will all - /// database updates. + /// The method above won't trigger the location manager if the transaction + /// is eventually rollbacked (explicitly, or because of an error). + /// + /// The `onCommit` and `onRollback` closures are executed in the writer + /// dispatch queue, serialized will all database updates. /// /// - precondition: Database connection is not read-only. /// - parameter onCommit: A closure executed on transaction commit. diff --git a/GRDB/Documentation.docc/DatabaseObservation.md b/GRDB/Documentation.docc/DatabaseObservation.md index 1fddaa39b..e2ce7e5a2 100644 --- a/GRDB/Documentation.docc/DatabaseObservation.md +++ b/GRDB/Documentation.docc/DatabaseObservation.md @@ -2,6 +2,17 @@ Observe database changes and transactions. +## Overview + +**SQLite notifies its host application of changes performed to the database, as well of transaction commits and rollbacks.** + +GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways: + +- ``ValueObservation``: Get notified when database values change. +- ``DatabaseRegionObservation``: Get notified when a transaction impacts a database region. +- ``Database/afterNextTransaction(onCommit:onRollback:)``: Handle transactions commits or rollbacks, one by one. +- ``TransactionObserver``: The low-level protocol that supports all database observation features. + ## Topics ### Observing Database Values diff --git a/GRDB/ValueObservation/Reducers/Map.swift b/GRDB/ValueObservation/Reducers/Map.swift index c8f1debb7..b69984b24 100644 --- a/GRDB/ValueObservation/Reducers/Map.swift +++ b/GRDB/ValueObservation/Reducers/Map.swift @@ -2,6 +2,20 @@ extension ValueObservation { /// Transforms all values from the upstream observation with a /// provided closure. /// + /// For example: + /// + /// ```swift + /// // Turn an observation of Player? into an observation of UIImage? + /// let observation = ValueObservation + /// .tracking { db in try Player.fetchOne(db, id: 42) } + /// .map { player in player?.image } + /// ``` + /// + /// The `transform` closure does not run on the main thread, and does not + /// block any database access This makes the `map` operator a tool that + /// helps reducing database contention + /// (see ). + /// /// - parameter transform: A closure that takes one value as its parameter /// and returns a new value. public func map(_ transform: @escaping (Reducer.Value) throws -> T) diff --git a/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift b/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift index 8311458a5..df1eb0ab2 100644 --- a/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift @@ -14,6 +14,47 @@ extension ValueObservation { extension ValueObservation where Reducer.Value: Equatable { /// Notifies only values that don’t match the previously observed value. + /// + /// For example: + /// + /// ```swift + /// // An observation of distinct Player? + /// let observation = ValueObservation + /// .tracking { db in try Player.fetchOne(db, id: 42) } + /// .removeDuplicates() + /// ``` + /// + /// > Tip: When the observed value does not adopt `Equatable`, and it is + /// > impractical to provide a custom comparison function, you can observe + /// > distinct raw database values such as ``Row`` or ``DatabaseValue``, + /// > before converting them to the desired type. For example, the previous + /// > observation can be rewritten as below: + /// > + /// > ```swift + /// > // An observation of distinct `Player?` + /// > let request = Player.filter(id: 42) + /// > let observation = ValueObservation + /// > .tracking { db in try Row.fetchOne(db, request) } + /// > .removeDuplicates() + /// > .map { row in try row.map(Player.init(row:)) } + /// > ``` + /// > + /// > This technique is also available for requests that + /// > involve associations: + /// > + /// > ```swift + /// > struct TeamInfo: Decodable, FetchableRecord { + /// > var team: Team + /// > var players: [Player] + /// > } + /// > + /// > // An observation of distinct `[TeamInfo]` + /// > 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 try rows.map(TeamInfo.init(row:)) } + /// > ``` public func removeDuplicates() -> ValueObservation> { diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index 2732c077b..cbcf065eb 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -59,7 +59,29 @@ extension ValueObservation { /// A shared observation starts observing the database as soon as it is /// subscribed. You can choose if database observation should stop, or not, /// when its number of subscriptions drops down to zero, with the `extent` - /// parameter. + /// parameter: + /// + /// ```swift + /// // The default: stops observing the database when the number of + /// // subscriptions drops down to zero, and restart database observation + /// // on the next subscription. + /// // + /// // Database errors can be recovered by resubscribing to the + /// // shared observation. + /// let sharedObservation = ValueObservation + /// .tracking { db in try Player.fetchAll(db) } + /// .shared(in: dbQueue, extent: .whileObserved) + /// + /// // Only stops observing the database when the shared observation + /// // is deinitialized, and all subscriptions are cancelled. + /// // + /// // This extent prevents the shared observation from recovering + /// // from database errors. To recover from database errors, create a new + /// // shared SharedValueObservation instance. + /// let sharedObservation = ValueObservation + /// .tracking { db in try Player.fetchAll(db) } + /// .shared(in: dbQueue, extent: .observationLifetime) + /// ``` /// /// By default, fresh values are dispatched asynchronously on the /// main dispatch queue. You can change this behavior by providing a @@ -68,7 +90,9 @@ extension ValueObservation { /// For example, the ``ValueObservationScheduler/immediate`` scheduler /// notifies all values on the main dispatch queue, and notifies the first /// one immediately when the - /// ``SharedValueObservation/start(onError:onChange:)`` method is called: + /// ``SharedValueObservation/start(onError:onChange:)`` method is called. + /// The `immediate` scheduling requires that the observation starts from the + /// main thread (a fatal error is raised otherwise): /// /// ```swift /// let observation = ValueObservation.tracking { db in @@ -82,9 +106,9 @@ extension ValueObservation { /// let cancellable = try sharedObservation.start { error in /// // handle error /// } onChange: { (players: [Player]) in - /// print("fresh players: \(players)") + /// print("Fresh players: \(players)") /// } - /// // <- here "fresh players" is already printed. + /// // <- here "Fresh players" is already printed. /// ``` /// /// Note that the `.immediate` scheduler requires that the observation is diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 54b5292f7..9db7ef096 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -7,21 +7,298 @@ import Foundation /// `ValueObservation` tracks changes in the results of database requests, and /// notifies fresh values whenever the database changes. /// -/// For example: +/// ## Overview +/// +/// Tracked changes are insertions, updates, and deletions that impact the +/// tracked value, whether performed with raw SQL, or . +/// 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). +/// +/// Changes to internal system tables (such as `sqlite_master`) and changes to +/// [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables are +/// not notified. +/// +/// ## ValueObservation Usage +/// +/// 1. Make sure that a unique database connection, ``DatabaseQueue`` or +/// ``DatabasePool``, is kept open during the whole duration of +/// the observation. +/// +/// `ValueObservation` does not notify changes performed by +/// external connections. +/// See +/// for more information. +/// +/// 2. Create a `ValueObservation` with a closure that fetches the +/// observed value: +/// +/// ```swift +/// let observation = ValueObservation.tracking { db in +/// // Fetch and return the observed value +/// } +/// +/// // For example, an observation of [Player], which tracks all players: +/// let observation = ValueObservation.tracking { db in +/// try Player.fetchAll(db) +/// } +/// +/// // The same observation, using shorthand notation: +/// let observation = ValueObservation.tracking(Player.fetchAll) +/// ``` +/// +/// There is no limit on the values that can be observed. An observation +/// can perform multiple requests, from multiple database tables, and use +/// raw SQL. See ``tracking(_:)`` for some examples. +/// +/// 3. Start the observation in order to be notified of changes: +/// +/// ```swift +/// let cancellable = observation.start(in: dbQueue) { error in +/// // Handle error +/// } onChange: { (players: [Player]) in +/// print("Fresh players", players) +/// } +/// ``` +/// +/// 4. Stop the observation by calling the ``DatabaseCancellable/cancel()`` +/// method on the object returned by the `start` method. Cancellation is +/// automatic when the cancellable is deallocated: +/// +/// ```swift +/// cancellable.cancel() +/// ``` +/// +/// `ValueObservation` can also be turned into an async sequence, a Combine +/// publisher, or an RxSwift observable (see the companion library +/// [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)): +/// +/// - Async sequence: +/// +/// ```swift +/// do { +/// for try await players in observation.values(in: dbQueue) { +/// print("Fresh players", players) +/// } +/// } catch { +/// // Handle error +/// } +/// ``` +/// +/// - Combine Publisher: +/// +/// ```swift +/// let cancellable = observation.publisher(in: dbQueue).sink { completion in +/// // Handle completion +/// } receiveValue: { (players: [Player]) in +/// print("Fresh players", players) +/// } +/// ``` +/// +/// ## ValueObservation Behavior +/// +/// `ValueObservation` notifies an initial value before the eventual changes. +/// +/// `ValueObservation` only notifies changes committed to disk. +/// +/// By default, `ValueObservation` notifies a fresh value whenever any component +/// of its fetched value is modified (any fetched column, row, etc.). This can +/// be configured: +/// see . +/// +/// By default, `ValueObservation` notifies the initial value, as well as +/// eventual changes and errors, on the main dispatch queue, asynchronously. +/// This can be configured: +/// see . +/// +/// `ValueObservation` may coalesce subsequent changes into a +/// single notification. +/// +/// `ValueObservation` may notify consecutive identical values. You can filter +/// out the undesired duplicates with the ``removeDuplicates()`` method. +/// +/// Starting an observation retains the database connection, until it is +/// stopped. As long as the observation is active, the database connection +/// won't be deallocated. +/// +/// The database observation stops when the cancellable returned by the `start` +/// method is cancelled or deallocated, or if an error occurs. +/// +/// Take care that there are use cases that `ValueObservation` is unfit for. +/// For example, an application may need to process absolutely all changes, +/// and avoid any coalescing. An application may also need to process changes +/// before any further modifications could be performed in the database file. In +/// those cases, the application needs to track *individual transactions*, not +/// values: use ``DatabaseRegionObservation``. If you need to process +/// changes before they are committed to disk, use ``TransactionObserver``. +/// +/// ## ValueObservation Scheduling +/// +/// By default, `ValueObservation` notifies the initial value, as well as +/// eventual changes and errors, on the main dispatch queue, asynchronously: /// /// ```swift -/// // Track all players -/// let observation = ValueObservation.tracking { db in -/// try Player.fetchAll(db) -/// } -/// -/// let cancellable = try observation.start(in: dbQueue) { error in -/// // handle error -/// } onChange: { (players: [Player]) in -/// print("Fresh players: \(players)") +/// // The default scheduling +/// let cancellable = observation.start(in: dbQueue) { error in +/// // Called asynchronously on the main dispatch queue +/// } onChange: { value in +/// // Called asynchronously on the main dispatch queue +/// print("Fresh value", value) /// } /// ``` /// +/// You can change this behavior by adding a `scheduling` argument to the +/// `start()` method. +/// +/// For example, the ``ValueObservationScheduler/immediate`` scheduler +/// notifies all values on the main dispatch queue, and notifies the first +/// one immediately when the observation starts. +/// +/// It is very useful in graphic applications, because you can configure views +/// right away, without waiting for the initial value to be fetched eventually. +/// You don't have to implement any empty or loading screen, or to prevent some +/// undesired initial animation. +/// +/// The `immediate` scheduling requires that the observation starts from the +/// main dispatch queue (a fatal error is raised otherwise): +/// +/// ```swift +/// let cancellable = observation.start(in: dbQueue, scheduling: .immediate) { error in +/// // Called on the main dispatch queue +/// } onChange: { value in +/// // Called on the main dispatch queue +/// print("Fresh value", value) +/// } +/// // <- Here "Fresh value" has already been printed. +/// ``` +/// +/// The other built-in scheduler ``ValueObservationScheduler/async(onQueue:)`` +/// asynchronously schedules values and errors on the dispatch queue of +/// your choice. +/// +/// ## ValueObservation Sharing +/// +/// Sharing a `ValueObservation` spares database resources. When a database +/// change happens, a fresh value is fetched only once, and then notified to +/// all clients of the shared observation. +/// +/// You build a shared observation with ``shared(in:scheduling:extent:)``: +/// +/// ```swift +/// // SharedValueObservation<[Player]> +/// let sharedObservation = ValueObservation +/// .tracking { db in try Player.fetchAll(db) } +/// .shared(in: dbQueue) +/// ``` +/// +/// `ValueObservation` and `SharedValueObservation` are nearly identical, but +/// the latter has no operator such as `map`. As a replacement, you may +/// for example use Combine apis: +/// +/// ```swift +/// let cancellable = try sharedObservation +/// .publisher() // Turn shared observation into a Combine Publisher +/// .map { ... } // The map operator from Combine +/// .sink(...) +/// ``` +/// +/// +/// ## Specifying the Tracked Region +/// +/// While the standard ``tracking(_:)`` method lets you track changes to a +/// fetched value and receive any changes to it, sometimes your use case might +/// require more granular control. +/// +/// Consider a scenario where you'd like to get a specific Player's row, but +/// only when their `score` column changes. You can use +/// ``tracking(region:fetch:)`` to do just that: +/// +/// ```swift +/// let observation = ValueObservation.tracking( +/// // Define what database region constitutes a "change" +/// region: Player.select(Column("score")).filter(id: 1), +/// // Define what to fetch upon such change +/// fetch: { db in try Player.fetchOne(db, id: 1) } +/// ) +/// ``` +/// +/// This overload of `ValueObservation` lets you entirely separate the +/// **observed region** from the **fetched value** itself, providing utmost +/// flexibility. See ``DatabaseRegionConvertible`` for more information about +/// the regions that can be tracked. +/// +/// ## ValueObservation Performance +/// +/// This section further describes runtime aspects of `ValueObservation`, and +/// provides some optimization tips for demanding applications. +/// +/// **`ValueObservation` is triggered by database transactions that may modify +/// the tracked value.** +/// +/// Precisely speaking, `ValueObservation` tracks changes in a +/// ``DatabaseRegion``, not changes in values. +/// +/// For example, if you track the maximum score of players, all transactions +/// that impact the `score` column of the `player` database table (any update, +/// insertion, or deletion) trigger the observation, even if the maximum score +/// itself is not changed. +/// +/// You can filter out undesired duplicate notifications with the +/// ``removeDuplicates()`` method. +/// +/// **ValueObservation can create database contention.** In other words, active +/// observations take a toll on the constrained database resources. When +/// triggered by impactful transactions, observations fetch fresh values, and +/// can delay read and write database accesses of other application components. +/// +/// When needed, you can help GRDB optimize observations and reduce +/// database contention: +/// +/// > Tip: Stop observations when possible. +/// > +/// > For example, if a `UIViewController` needs to display database values, it +/// > can start the observation in `viewWillAppear`, and stop it in +/// > `viewWillDisappear`. +/// > +/// > In a SwiftUI application, you can profit from the +/// > [GRDBQuery](https://github.com/groue/GRDBQuery) companion library, and its +/// > [`View.queryObservation(_:)`](https://swiftpackageindex.com/groue/grdbquery/documentation/grdbquery/queryobservation) +/// > method. +/// +/// > Tip: Share observations when possible. +/// > +/// > Each call to `ValueObservation.start` method triggers independent values +/// > refreshes. When several components of your app are interested in the same +/// > value, consider sharing the observation +/// > with ``shared(in:scheduling:extent:)``. +/// +/// > Tip: Use a ``DatabasePool``, because it can perform multi-threaded +/// > database accesses. +/// +/// > Tip: When the observation processes some raw fetched values, use the +/// > ``map(_:)`` operator: +/// > +/// > ```swift +/// > // Plain observation +/// > let observation = ValueObservation.tracking { db -> MyValue in +/// > let players = try Player.fetchAll(db) +/// > return computeMyValue(players) +/// > } +/// > +/// > // Optimized observation +/// > let observation = ValueObservation +/// > .tracking { db try Player.fetchAll(db) } +/// > .map { players in computeMyValue(players) } +/// > ``` +/// > +/// > The `map` operator helps reducing database contention because it performs +/// > its job without blocking database accesses. +/// +/// > Tip: When the observation tracks a constant database region, create an +/// > optimized observation with the ``trackingConstantRegion(_:)`` method. See +/// > the documentation of this method for more information about what +/// > constitutes a "constant region", and the nature of the optimization. +/// /// ## Topics /// /// ### Creating a ValueObservation @@ -69,11 +346,22 @@ public struct ValueObservation { var events = ValueObservationEvents() /// A boolean value indicating whether the observation requires write access - /// when it fetch fresh values. + /// when it fetches fresh values. /// - /// The default is false. Setting it to true can disable scheduling - /// optimizations when the observation is started in - /// a ``DatabasePool``. + /// The `requiresWriteAccess` property is false by default. When true, a + /// `ValueObservation` has a write access to the database, and its fetches + /// are automatically wrapped in a savepoint: + /// + /// ```swift + /// var observation = ValueObservation.tracking { db in + /// // write access allowed + /// ... + /// } + /// observation.requiresWriteAccess = true + /// ``` + /// + /// Setting the `requiresWriteAccess` flag can disable scheduling + /// optimizations when the observation is started in a ``DatabasePool``. public var requiresWriteAccess = false var trackingMode: ValueObservationTrackingMode @@ -155,7 +443,7 @@ extension ValueObservation: Refinable { /// let cancellable = try observation.start(in: dbQueue) { error in /// // handle error /// } onChange: { (players: [Player]) in - /// print("fresh players: \(players)") + /// print("Fresh players: \(players)") /// } /// ``` /// @@ -165,21 +453,19 @@ extension ValueObservation: Refinable { /// /// For example, the ``ValueObservationScheduler/immediate`` scheduler /// notifies all values on the main dispatch queue, and notifies the first - /// one immediately when the ``start(in:scheduling:onError:onChange:)`` - /// method is called: + /// one immediately when the observation starts. The `immediate` scheduling + /// requires that the observation starts from the main dispatch queue (a + /// fatal error is raised otherwise): /// /// ```swift /// let cancellable = try observation.start(in: dbQueue, scheduling: .immediate) { error in /// // handle error /// } onChange: { (players: [Player]) in - /// print("fresh players: \(players)") + /// print("Fresh players: \(players)") /// } - /// // <- here "fresh players" is already printed. + /// // <- here "Fresh players" is already printed. /// ``` /// - /// Note that the `.immediate` scheduler requires that the observation is - /// subscribed from the main thread. It raises a fatal error otherwise. - /// /// - parameter reader: A DatabaseReader. /// - parameter scheduler: A ValueObservationScheduler. By default, fresh /// values are dispatched asynchronously on the main queue. @@ -209,7 +495,7 @@ extension ValueObservation: Refinable { /// Performs the specified closures when observation events occur. /// - /// All closures run on unspecified dispatch queues - don't make + /// All closures run on unspecified dispatch queues: don't make /// any assumption. /// /// - parameters: @@ -257,6 +543,30 @@ extension ValueObservation: Refinable { } /// Prints log messages for all observation events. + /// + /// For example: + /// + /// ```swift + /// let cancellable = ValueObservation + /// .tracking(Player.fetchCount) + /// .print("Observe player count") + /// .start(in: dbQueue, onError: { _ in }, onChange: { _ in }) + /// + /// // Prints: + /// // Observe player count: start + /// // Observe player count: fetch + /// // Observe player count: tracked region: player(*) + /// // Observe player count: value: 0 + /// // Observe player count: database did change + /// // Observe player count: fetch + /// // Observe player count: value: 1 + /// ``` + /// + /// - parameter prefix: A string —- which defaults to empty -— with which to + /// prefix all log messages. + /// - parameter stream: A stream for text output that receives messages, and + /// which directs output to the console by default. A custom stream can be + /// used to log messages to other destinations. public func print( _ prefix: String = "", to stream: TextOutputStream? = nil) @@ -432,7 +742,7 @@ extension ValueObservation { /// let cancellable = publisher.sink { completion in /// // handle completion /// } receiveValue: { (players: [Player]) in - /// print("fresh players: \(players)") + /// print("Fresh players: \(players)") /// } /// ``` /// @@ -442,7 +752,9 @@ extension ValueObservation { /// /// For example, the ``ValueObservationScheduler/immediate`` scheduler /// notifies all values on the main dispatch queue, and notifies the first - /// one immediately when the publisher is subscribed: + /// one immediately when the observation starts. The `immediate` scheduling + /// requires that the observation starts from the main dispatch queue (a + /// fatal error is raised otherwise): /// /// ```swift /// let publisher = observation.publisher(in: dbQueue, scheduling: .immediate) @@ -450,14 +762,11 @@ extension ValueObservation { /// let cancellable = publisher.sink { completion in /// // handle completion /// } receiveValue: { (players: [Player]) in - /// print("fresh players: \(players)") + /// print("Fresh players: \(players)") /// } - /// // <- here "fresh players" is already printed. + /// // <- here "Fresh players" is already printed. /// ``` /// - /// Note that the `.immediate` scheduler requires that the publisher is - /// subscribed from the main thread. It raises a fatal error otherwise. - /// /// - parameter reader: A DatabaseReader. /// - parameter scheduler: A ValueObservationScheduler. By default, fresh /// values are dispatched asynchronously on the main dispatch queue. @@ -872,6 +1181,35 @@ extension ValueObservation { /// } /// ``` /// + /// An observation can perform multiple requests, from multiple database + /// tables, and even use raw SQL: + /// + /// ```swift + /// struct HallOfFame { + /// var totalPlayerCount: Int + /// var bestPlayers: [Player] + /// } + /// + /// // An observation of HallOfFame + /// let observation = ValueObservation.tracking { db -> HallOfFame in + /// let totalPlayerCount = try Player.fetchCount(db) + /// + /// let bestPlayers = try Player + /// .order(Column("score").desc) + /// .limit(10) + /// .fetchAll(db) + /// + /// return HallOfFame( + /// totalPlayerCount: totalPlayerCount, + /// bestPlayers: bestPlayers) + /// } + /// + /// // An observation of the maximum score + /// let observation = ValueObservation.tracking { db in + /// try Int.fetchOne(db, sql: "SELECT MAX(score) FROM player") + /// } + /// ``` + /// /// - parameter fetch: The closure that fetches the observed value. public static func tracking( _ fetch: @escaping (Database) throws -> Value) diff --git a/README.md b/README.md index 867718343..a60b36593 100644 --- a/README.md +++ b/README.md @@ -5918,640 +5918,6 @@ 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. -## 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.afterNextTransaction(onCommit:onRollback:)` method. - -```swift -try dbQueue.write { db in - db.afterNextTransaction { db in - print("successful commit") - } - ... -} // prints "successful commit" -``` - -**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: - -```swift -/// Inserts a region in the database, and start monitoring upon -/// successful insertion. -func startMonitoring(_ db: Database, region: CLRegion) throws { - // Make sure database is inside a transaction - try db.inSavepoint { - - // Save the region in the database - try insert(...) - - // Start monitoring if and only if the insertion is - // eventually committed - db.afterNextTransaction { _ in - // locationManager prefers the main queue: - DispatchQueue.main.async { - locationManager.startMonitoring(for: region) - } - } - - return .commit - } -} -``` - -The method above won't trigger the location manager if the transaction is eventually rollbacked (explicitly, or because of an error), as in the sample code below: - -```swift -try dbQueue.write { db in - // success - try startMonitoring(db, region) - - // On error, the transaction is rollbacked, the region is not inserted, and - // the location manager is not invoked. - try failableMethod(db) -} -``` - - -## ValueObservation - -**ValueObservation tracks changes in database values**. It automatically notifies your application with fresh values whenever changes are committed in the database. - -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). - -> **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. - -- [ValueObservation Usage](#valueobservation-usage) -- [ValueObservation Scheduling](#valueobservation-scheduling) -- [ValueObservation Operators](#valueobservation-operators): [map](#valueobservationmap), [removeDuplicates](#valueobservationremoveduplicates), ... -- [ValueObservation Sharing](#valueobservation-sharing) -- [Specifying the Region Tracked by ValueObservation](#specifying-the-region-tracked-by-valueobservation) -- [ValueObservation Performance](#valueobservation-performance) -- :blue_book: [Combine Publisher](Documentation/Combine.md#database-observation) - -### ValueObservation Usage - -1. Make sure that a unique [database connection](#database-connections) is kept open during the whole duration of the observation. - - ValueObservation does not notify changes performed by external connections. - -2. Define a ValueObservation by providing a function that fetches the observed value. - - ```swift - let observation = ValueObservation.tracking { db in - /* fetch and return the observed value */ - } - - // For example, an observation of [Player], which tracks all players: - let observation = ValueObservation.tracking { db in - try Player.fetchAll(db) - } - - // The same observation, using shorthand notation: - let observation = ValueObservation.tracking(Player.fetchAll) - ``` - - The observation can perform multiple requests, from multiple database tables, and even use raw SQL. - -
- Example of a more complex ValueObservation - - ```swift - struct HallOfFame { - var totalPlayerCount: Int - var bestPlayers: [Player] - } - - // An observation of HallOfFame - let observation = ValueObservation.tracking { db -> HallOfFame in - let totalPlayerCount = try Player.fetchCount(db) - - let bestPlayers = try Player - .order(Column("score").desc) - .limit(10) - .fetchAll(db) - - return HallOfFame( - totalPlayerCount: totalPlayerCount, - bestPlayers: bestPlayers) - } - ``` - -
- -
- Example of a SQL ValueObservation - - ```swift - // An observation of the maximum score - let observation = ValueObservation.tracking { db in - try Int.fetchOne(db, sql: "SELECT MAX(score) FROM player") - } - ``` - -
- -3. Start the observation in order to be notified of changes: - - ```swift - // Start observing the database - let cancellable: DatabaseCancellable = observation.start( - in: dbQueue, // or dbPool - onError: { error in print("players could not be fetched") }, - onChange: { (players: [Player]) in print("fresh players", players) }) - ``` - -4. 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() - ``` - -**As a convenience**, ValueObservation can be turned into an async sequence, a Combine publisher, or an RxSwift observable: - -
- Async sequence example - -[**:fire: EXPERIMENTAL**](#what-are-experimental-features) - -```swift -let observation = ValueObservation.tracking(Player.fetchAll) -for try await players in observation.values(in: dbQueue) { - print("fresh players", players) -} -``` - -
- -
- Combine example - -```swift -import Combine -import GRDB - -let observation = ValueObservation.tracking(Player.fetchAll) - -let cancellable = observation.publisher(in: dbQueue).sink( - receiveCompletion: { completion in ... }, - receiveValue: { (players: [Player]) in - print("fresh players", players) - }) -``` - -See [Combine Support] for more information. - -
- -
- RxSwift example - -```swift -import GRDB -import RxGRDB -import RxSwift - -let observation = ValueObservation.tracking(Player.fetchAll) - -let disposable = observation.rx.observe(in: dbQueue).subscribe( - onNext: { (players: [Player]) in - print("fresh players", players) - }, - onError: { error in ... }) -``` - -See the companion library [RxGRDB] for more information. - -
- -**Generally speaking**: - -- ValueObservation notifies an initial value before the eventual changes. -- ValueObservation only notifies changes committed to disk. -- By default, ValueObservation notifies a fresh value whenever any of its component is modified (any fetched column, row, etc.). This can be [configured](#specifying-the-region-tracked-by-valueobservation). -- By default, ValueObservation notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously. This can be [configured](#valueobservation-scheduling). -- ValueObservation may coalesce subsequent changes into a single notification. -- ValueObservation may notify consecutive identical values. You can filter out the undesired duplicates with the [removeDuplicates](#valueobservationremoveduplicates) method. -- Starting an observation retains the database connection, until it is stopped. As long as the observation is active, the database connection won't be deallocated. -- The database observation stops when any of those conditions is met: - - The cancellable returned by the `start` method is cancelled or deinitialized. - - An error occurs. - -Take care that there are use cases that ValueObservation is unfit for. For example, your application may need to process absolutely all changes, and avoid any coalescing. It may also need to process changes before any further modifications are performed in the database file. In those cases, you need to track *individual transactions*, not values. See [DatabaseRegionObservation]. If you need to process uncommitted changes, see [TransactionObserver](#transactionobserver-protocol). - - -### ValueObservation Scheduling - -By default, ValueObservation notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously: - -```swift -// The default scheduling -let cancellable = observation.start( - in: dbQueue, - onError: { error in ... }, // called asynchronously on the main thread - onChange: { value in print("fresh value") }) // called asynchronously on the main thread -``` - -You can change this behavior by adding a `scheduling` argument to the `start()` method. - -For example, `scheduling: .immediate` makes sure the initial value is notified immediately when the observation starts. It helps your application update the user interface without having to wait for any asynchronous notifications: - -```swift -class PlayersViewController: UIViewController { - private var cancellable: DatabaseCancellable? - - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - - // Start observing the database - let observation = ValueObservation.tracking(Player.fetchAll) - cancellable = observation.start( - in: dbQueue, - scheduling: .immediate, // <- immediate scheduler - onError: { error in ... }, - onChange: { [weak self] (players: [Player]) in - guard let self else { return } - self.updateView(players) - }) - // <- Here the view has already been updated. - } - - override func viewWillDisappear(_ animated: Bool) { - super.viewWillDisappear(animated) - - // Stop observing the database - cancellable?.cancel() - } - - private func updateView(_ players: [Player]) { ... } -} -``` - -Note that the `.immediate` scheduling requires that the observation starts from the main thread. A fatal error is raised otherwise. - -The other built-in scheduler `.async(onQueue:)` asynchronously schedules values and errors on the dispatch queue of your choice: - -```swift -let queue: DispatchQueue = ... -let cancellable = observation.start( - in: dbQueue, - scheduling: .async(onQueue: queue) - onError: { error in ... }, // called asynchronously on queue - onChange: { value in print("fresh value") }) // called asynchronously on queue -``` - - -### ValueObservation Operators - -**Operators** are methods that transform and configure value observations so that they better fit the needs of your application. - -- [ValueObservation.map](#valueobservationmap) -- [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) -- [ValueObservation.requiresWriteAccess](#valueobservationrequireswriteaccess) - -**Debugging Operators** - -- [ValueObservation.handleEvents](#valueobservationhandleevents) -- [ValueObservation.print](#valueobservationprint) - - -#### ValueObservation.map - -The `map` operator transforms the values notified by a ValueObservation. - -For example: - -```swift -// Turn an observation of Player? into an observation of UIImage? -let observation = ValueObservation - .tracking { db in try Player.fetchOne(db, id: 42) } - .map { player in player?.image } -``` - -The transformation function does not block any database access. This makes the `map` operator a tool which helps reducing [database contention](#valueobservation-performance). - - -#### ValueObservation.removeDuplicates - -The `removeDuplicates()` and `removeDuplicates(by:)` operators filter out consecutive equal values: - -For example: - -```swift -// An observation of distinct Player? -let observation = ValueObservation - .tracking { db in try Player.fetchOne(db, id: 42) } - .removeDuplicates() -``` - -:bulb: **Tip**: When the observed value does not adopt Equatable, and it is impractical to provide a custom comparison function, you can observe distinct raw database values such as [Row](#row-queries) or [DatabaseValue](#databasevalue), before converting them to the desired type. For example, the previous observation can be rewritten as below: - -```swift -// An observation of distinct Player? -let request = Player.filter(id: 42) -let observation = ValueObservation - .tracking { db in try Row.fetchOne(db, request) } - .removeDuplicates() // Row adopts Equatable - .map { row in try row.map(Player.init(row:) } -``` - -This technique is also available for requests that involve [Associations]: - -```swift -struct TeamInfo: Decodable, FetchableRecord { - var team: Team - var players: [Player] -} - -// An observation of distinct [TeamInfo] -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 try rows.map(TeamInfo.init(row:) } -``` - - -#### ValueObservation.requiresWriteAccess - -The `requiresWriteAccess` property is false by default. When true, a ValueObservation has a write access to the database, and its fetches are automatically wrapped in a [savepoint](#transactions-and-savepoints): - -```swift -var observation = ValueObservation.tracking { db in - // write access allowed - ... -} -observation.requiresWriteAccess = true -``` - -When you use a [database pool](#database-pools), this flag has a performance hit. - - -#### ValueObservation.handleEvents - -The `handleEvents` operator lets your application observe the lifetime of a ValueObservation: - -```swift -let observation = ValueObservation - .tracking { db in ... } - .handleEvents( - willStart: { - // The observation starts. - }, - willFetch: { - // The observation will perform a database fetch. - }, - willTrackRegion: { databaseRegion in - // The observation starts tracking a database region. - }, - databaseDidChange: { - // The observation was impacted by a database change. - }, - didReceiveValue: { value in - // A fresh value was observed. - // NOTE: This closure runs on an unspecified DispatchQueue. - }, - didFail: { error in - // The observation completes with an error. - }, - didCancel: { - // The observation was cancelled. - }) -``` - -See also [ValueObservation.print](#valueobservationprint). - - -#### ValueObservation.print - -The `print` operator logs messages for all ValueObservation events. - -```swift -let observation = ValueObservation - .tracking { db in ... } - .print() -``` - -See also [ValueObservation.handleEvents](#valueobservationhandleevents). - - -### ValueObservation Sharing - -[**:fire: EXPERIMENTAL**](#what-are-experimental-features) - -**Sharing a ValueObservation allows several components of your app to be notified of database changes, in an efficient way.** - -A shared observation spares database resources. For example, when a database change happens, a fresh value is fetched only once, and then notified to all subscriptions. - -Usage: - -```swift -// SharedValueObservation<[Player]> -let sharedObservation = ValueObservation - .tracking { db in try Player.fetchAll(db) } - .shared(in: dbQueue) -// ~~~~~~~~~~~~~~~~~~~~ - -let cancellable = try sharedObservation.start( - onError: { error in ... }, - onChange: { players: [Player] in - print("fresh players: \(players)") - }) -``` - -The sharing only applies if you start observing the database from the same `SharedValueObservation` instance: - -```swift -// NOT shared -let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) -let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) - -// Shared -let sharedObservation = ValueObservation.tracking { db in ... }.shared(in: dbQueue) -let cancellable1 = sharedObservation.start(...) -let cancellable2 = sharedObservation.start(...) -``` - -By default, fresh values are dispatched asynchronously on the main queue. You can change this behavior (see [ValueObservation Scheduling](#valueobservation-scheduling) for more information): - -```swift -let sharedObservation = ValueObservation - .tracking { db in try Player.fetchAll(db) } - .shared(in: dbQueue, scheduling: .immediate) -// ~~~~~~~~~~~~~~~~~~~~~~ -``` - -A shared observation starts observing the database as soon as it is subscribed. You can choose if database observation should stop, or not, when its number of subscriptions drops down to zero, with the `extent` parameter: - -```swift -// The default: stops observing the database when the number of subscriptions -// drops down to zero, and restart database observation on the next subscription. -// -// Database errors can be recovered by resubscribing to the shared observation. -let sharedObservation = ValueObservation - .tracking { db in try Player.fetchAll(db) } - .shared(in: dbQueue, extent: .whileObserved) -// ~~~~~~~~~~~~~~~~~~~~~~ - -// Only stops observing the database when the shared observation is deinitialized, -// and all subscriptions are cancelled. -// -// This extent prevents the shared observation from recovering from database -// errors. To recover from database errors, create a new shared -// SharedValueObservation instance. -let sharedObservation = ValueObservation - .tracking { db in try Player.fetchAll(db) } - .shared(in: dbQueue, extent: .observationLifetime) -// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -``` - -> **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) -> let cancellable = try sharedObservation -> .publisher() // Turn shared observation into a Combine Publisher -> .map { ... } // The map operator from Combine -> .sink(...) -> ``` - - -### Specifying the Region Tracked by ValueObservation - -While the standard `ValueObservation.tracking { db in ... }` method lets you track changes to a fetched value and receive any changes to it, sometimes your use case might require more granular control. - -Consider a scenario where you'd like to get a specific Player's row, but only when their `score` column changes. You can use `tracking(region:fetch:)` to do just that: - -```swift -let observation = ValueObservation.tracking( - // Define what database region constitutes a "change" - region: Player.select(Column("score")).filter(id: 1), - // Define what to fetch upon such change - fetch: { db in try Player.fetchOne(db, id: 1) } -) -``` - -This overload of `ValueObservation` lets you entirely separate the **observed region** from the **fetched value** itself, providing utmost flexibility. See [DatabaseRegionConvertible] for more information. - -### ValueObservation Performance - -This chapter further describes runtime aspects of ValueObservation, and provides some optimization tips for demanding applications. - - -**ValueObservation is triggered by database transactions that may modify the tracked value.** - -For example, if you track the maximum score of players, all transactions that impact the `score` column of the `player` database table (any update, insertion, or deletion) trigger the observation, even if the maximum score itself is not changed. - -You can filter out undesired duplicate notifications with the [removeDuplicates](#valueobservationremoveduplicates) method. - - -**ValueObservation can create database contention.** In other words, active observations take a toll on the constrained database resources. When triggered by impactful transactions, observations fetch fresh values, and can delay read and write database accesses of other application components. - -When needed, you can help GRDB optimize observations and reduce database contention: - -1. :bulb: **Tip**: Stop observations when possible. - - For example, if a UIViewController needs to display database values, it can start the observation in `viewWillAppear`, and stop it in `viewWillDisappear`. Check the sample code [above](#valueobservation-scheduling). - -2. :bulb: **Tip**: Share observations when possible. - - Each call to `ValueObservation.start` method triggers independent values refreshes. When several components of your app are interested in the same value, consider [sharing the observation](#valueobservation-sharing). - -3. :bulb: **Tip**: Use a [database pool](#database-pools), because it can perform multi-threaded database accesses. - -4. :bulb: **Tip**: When the observation processes some raw fetched values, use the [`map`](#valueobservationmap) operator: - - ```swift - // Plain observation - let observation = ValueObservation.tracking { db -> MyValue in - let players = try Player.fetchAll(db) - return computeMyValue(players) - } - - // Optimized observation - let observation = ValueObservation - .tracking { db try Player.fetchAll(db) } - .map { players in computeMyValue(players) } - ``` - - The `map` operator helps reducing database contention because it performs its job without blocking concurrent database reads. - -4. :bulb: **Tip**: When the observation tracks a constant database region, create an optimized observation with the `ValueObservation.trackingConstantRegion(_:)` method. - - The optimization only kicks in when the observation is started from a [database pool](#database-pools): fresh values are fetched concurrently, and do not block database writes. - - The `ValueObservation.trackingConstantRegion(_:)` has a precondition: the observed requests must fetch from a single and constant database region. The tracked region is made of tables, columns, and, when possible, rowids of individual rows. All changes that happen outside of this region do not impact the observation. - - For example: - - ```swift - // Tracks the full 'player' table (only) - let observation = ValueObservation.trackingConstantRegion { db -> [Player] in - try Player.fetchAll(db) - } - - // Tracks the row with id 42 in the 'player' table (only) - let observation = ValueObservation.trackingConstantRegion { db -> Player? in - try Player.fetchOne(db, id: 42) - } - - // Tracks the 'score' column in the 'player' table (only) - let observation = ValueObservation.trackingConstantRegion { db -> Int? in - try Player.select(max(Column("score"))).fetchOne(db) - } - - // Tracks both the 'player' and 'team' tables (only) - let observation = ValueObservation.trackingConstantRegion { db -> ([Team], [Player]) in - let teams = try Team.fetchAll(db) - let players = try Player.fetchAll(db) - return (teams, players) - } - ``` - - When you want to observe a varying database region, make sure you use the plain `ValueObservation.tracking(_:)` method instead, or else some changes will not be notified. - - For example, consider those three observations below that depend on some user preference. They all track a varying region, and must use `ValueObservation.tracking(_:)`: - - ```swift - // Does not always track the same row in the player table. - let observation = ValueObservation.tracking { db -> Player? in - let pref = try Preference.fetchOne(db) ?? .default - return try Player.fetchOne(db, id: pref.favoritePlayerId) - } - - // Only tracks the 'user' table if there are some blocked emails. - let observation = ValueObservation.tracking { db -> [User] in - let pref = try Preference.fetchOne(db) ?? .default - let blockedEmails = pref.blockedEmails - return try User.filter(blockedEmails.contains(Column("email"))).fetchAll(db) - } - - // Sometimes tracks the 'food' table, and sometimes the 'beverage' table. - let observation = ValueObservation.tracking { db -> Int in - let pref = try Preference.fetchOne(db) ?? .default - switch pref.selection { - case .food: return try Food.fetchCount(db) - case .beverage: return try Beverage.fetchCount(db) - } - } - ``` - - When you are in doubt, add the [`print()` method](#valueobservationprint) to your observation before starting it, and look in your application logs for lines that start with `tracked region`. Make sure the printed database region covers the changes you expect to be tracked. - -
- Examples of tracked regions - - - `empty`: The empty region, which tracks nothing and never triggers the observation. - - `player(*)`: The full `player` table - - `player(id,name)`: The `id` and `name` columns of the `player` table - - `player(id,name)[1]`: The `id` and `name` columns of the row with id 1 in the `player` table - - `player(*),preference(*)`: Both the full `player` and `preference` tables - -
- - ## DatabaseRegionObservation **DatabaseRegionObservation notifies all [transactions](#transactions-and-savepoints) that impact the tracked [requests](#requests).** @@ -8360,18 +7726,54 @@ Sample Code [URIs don't change: people change them.](https://www.w3.org/Provider/Style/URI) +#### Adding support for missing SQL functions or operators + +This chapter was renamed to [Embedding SQL in Query Interface Requests]. + +#### Advanced DatabasePool + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). + +#### After Commit Hook + +This chapter was replaced with [Transaction Hook]. + +#### Asynchronous APIs + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). + #### Changes Tracking This chapter has been renamed [Record Comparison]. +#### Concurrency + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). + #### Customized Decoding of Database Rows This chapter has been renamed [Beyond FetchableRecord]. +#### Customizing the Persistence Methods + +This chapter was replaced with [Persistence Callbacks]. + +#### Database Snapshots + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). + +#### DatabaseWriter and DatabaseReader Protocols + +This chapter was removed. See the references of [DatabaseReader](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasereader) and [DatabaseWriter](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasewriter). + #### Dealing with External Connections This chapter has been superseded by the [Sharing a Database] guide. +#### Differences between Database Queues and Pools + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). + #### Enabling FTS5 Support This chapter has [moved](Documentation/FullTextSearch.md#enabling-fts5-support). @@ -8386,6 +7788,10 @@ The [Database Observation] chapter describes the other ways to observe the datab This chapter has [moved](Documentation/FullTextSearch.md). +#### Guarantees and Rules + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). + #### Migrations This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations). @@ -8406,53 +7812,17 @@ This protocol has been renamed [FetchableRecord] in GRDB 3.0. This protocol has been renamed [TableRecord] in GRDB 3.0. -#### Customizing the Persistence Methods - -This chapter was replaced with [Persistence Callbacks]. - -#### After Commit Hook - -This chapter was replaced with [Transaction Hook]. - -#### ValueObservation and DatabaseRegionObservation - -This chapter has been superseded by [ValueObservation] and [DatabaseRegionObservation]. - -#### Concurrency - -This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). - -#### Guarantees and Rules - -This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). - -#### Differences between Database Queues and Pools - -This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). - -#### Advanced DatabasePool - -This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). - -#### Database Snapshots - -This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). - -#### DatabaseWriter and DatabaseReader Protocols - -This chapter was removed. See the references of [DatabaseReader](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasereader) and [DatabaseWriter](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasewriter). - -#### Asynchronous APIs - -This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). - #### Unsafe Concurrency APIs This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). -### Adding support for missing SQL functions or operators +#### ValueObservation -This chapter was renamed to [Embedding SQL in Query Interface Requests]. +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation). + +#### ValueObservation and DatabaseRegionObservation + +This chapter has been superseded by [ValueObservation] and [DatabaseRegionObservation]. [Associations]: Documentation/AssociationsBasics.md [Beyond FetchableRecord]: #beyond-fetchablerecord @@ -8478,7 +7848,7 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests]. [Persistence Callbacks]: #persistence-callbacks [persistence callbacks]: #persistence-callbacks [TableRecord]: #tablerecord-protocol -[ValueObservation]: #valueobservation +[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation [DatabaseRegionObservation]: #databaseregionobservation [RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB [DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol From fed4833764bcc7b6d9e1d5d70c9523f7f0ebbd4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Nov 2022 18:45:48 +0100 Subject: [PATCH 62/69] Move DatabaseRegionObservation documentation to DocC --- Documentation/Combine.md | 2 +- Documentation/GRDB5MigrationGuide.md | 2 +- Documentation/QueryInterfaceOrganization.md | 2 +- GRDB/Core/DatabaseRegionObservation.swift | 84 +++++++++++++- README.md | 117 +------------------- 5 files changed, 87 insertions(+), 120 deletions(-) diff --git a/Documentation/Combine.md b/Documentation/Combine.md index 657569afa..97bd766bb 100644 --- a/Documentation/Combine.md +++ b/Documentation/Combine.md @@ -385,7 +385,7 @@ let cancellable = hallOfFamePublisher.sink( [Database Changes Observation]: ../README.md#database-changes-observation [Database Observation]: #database-observation [Combine and Data Consistency]: #combine-and-data-consistency -[DatabaseRegionObservation]: ../README.md#databaseregionobservation +[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation [Demo Application]: DemoApps/GRDBCombineDemo/README.md [SQLite]: http://sqlite.org [ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index 2bb4ce4d9..6062e56e4 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -500,7 +500,7 @@ let publisher = observation [ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation -[DatabaseRegionObservation]: ../README.md#databaseregionobservation +[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation [RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB [removeDuplicates]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates() [Custom SQL functions]: ../README.md#custom-sql-functions diff --git a/Documentation/QueryInterfaceOrganization.md b/Documentation/QueryInterfaceOrganization.md index bbb04b82d..9c33e6aff 100644 --- a/Documentation/QueryInterfaceOrganization.md +++ b/Documentation/QueryInterfaceOrganization.md @@ -608,7 +608,7 @@ myRequest(Player.select(...).filter(...)) [Column]: #column [ColumnExpression]: #columnexpression [DatabaseRegionConvertible]: #databaseregionconvertible -[DatabaseRegionObservation]: ../README.md#databaseregionobservation +[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation [DatabaseValue]: #databasevalue [DatabaseValueConvertible]: #databasevalueconvertible [DerivableRequest]: #derivablerequest diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 9e87d403f..a8b1c4d88 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -6,19 +6,95 @@ import Foundation /// `DatabaseRegionObservation` tracks transactions that modify a /// database region. /// -/// For example: +/// ## Overview +/// +/// Tracked changes are insertions, updates, and deletions that impact the +/// tracked region, whether performed with raw SQL, or . +/// 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). +/// +/// Changes to internal system tables (such as `sqlite_master`) and changes to +/// [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables are +/// not notified. +/// +/// `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`. +/// +/// ## DatabaseRegionObservation Usage +/// +/// Create a `DatabaseRegionObservation` with one or several requests to track: /// /// ```swift -/// // Track the player table +/// // Tracks the full player table /// let observation = DatabaseRegionObservation(tracking: Player.all()) +/// ``` /// +/// Then start the observation from a ``DatabaseQueue`` or ``DatabasePool``: +/// +/// ```swift /// let cancellable = try observation.start(in: dbQueue) { error in -/// // handle error +/// // Handle error /// } onChange: { (db: Database) in -/// print("A modification of the player table has just been committed.") +/// print("Players were changed") /// } /// ``` /// +/// Enjoy the changes notifications: +/// +/// ```swift +/// try dbQueue.write { db in +/// try Player(name: "Arthur").insert(db) +/// } +/// // Prints "Players were changed" +/// ``` +/// +/// You stop the observation by calling the ``DatabaseCancellable/cancel()`` +/// method on the object returned by the `start` method. Cancellation is +/// automatic when the cancellable is deallocated: +/// +/// ```swift +/// cancellable.cancel() +/// ``` +/// +/// `DatabaseRegionObservation` can also be turned into a Combine publisher, or +/// an RxSwift observable (see the companion library +/// [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)): +/// +/// ```swift +/// let cancellable = observation.publisher(in: dbQueue).sink { completion in +/// // Handle completion +/// } receiveValue: { (db: Database) in +/// print("Players were changed") +/// } +/// ``` +/// +/// 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: .fullDatabase) +/// ``` +/// /// ## Topics /// /// ### Creating DatabaseRegionObservation diff --git a/README.md b/README.md index a60b36593..06122fa9c 100644 --- a/README.md +++ b/README.md @@ -5908,125 +5908,16 @@ Database Changes Observation GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways: +- [ValueObservation]: Get notified when database values change. +- [DatabaseRegionObservation]: Get notified when a transaction impacts a database region. - [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. +- [TransactionObserver Protocol](#transactionobserver-protocol): The low-level protocol that supports all database observation features. - :blue_book: [Combine Support]: Automated tracking of database changes, with [Combine]. - :blue_book: [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift). 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. -## DatabaseRegionObservation - -**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). - -> **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. - - -### DatabaseRegionObservation Usage - -Define an observation by providing one or several requests to track: - -```swift -// 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 cancellable = try observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { (db: Database) in - print("Players were changed") - }) -} -``` - -Enjoy the changes notifications: - -```swift -try dbQueue.write { db in - try Player(name: "Arthur").insert(db) -} -// Prints "Players were changed" -``` - -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 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: .fullDatabase) -``` - -**As a convenience**, DatabaseRegionObservation can be turned into a Combine publisher, or an RxSwift observable: - -
- Combine example - -```swift -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") - }) -``` - -See [Combine Support] for more information. - -
- -
- RxSwift example - -```swift -import GRDB -import RxGRDB -import RxSwift - -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 The `TransactionObserver` protocol lets you **observe individual database changes and transactions**: @@ -7849,7 +7740,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [persistence callbacks]: #persistence-callbacks [TableRecord]: #tablerecord-protocol [ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation -[DatabaseRegionObservation]: #databaseregionobservation +[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation [RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB [DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol [DatabaseRegion]: #databaseregion From 409bd3bb26ba5d2045567d9abb6a6046c5001c45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 28 Nov 2022 08:27:12 +0100 Subject: [PATCH 63/69] Move Database Observation documentation to DocC --- Documentation/AssociationsBasics.md | 2 +- Documentation/Combine.md | 2 +- Documentation/CustomSQLiteBuilds.md | 2 +- Documentation/FetchedRecordsController.md | 2 +- Documentation/GRDB5MigrationGuide.md | 2 +- .../GoodPracticesForDesigningRecordTypes.md | 6 +- Documentation/QueryInterfaceOrganization.md | 2 +- Documentation/WhyAdoptGRDB.md | 3 +- GRDB/Core/DatabaseRegion.swift | 29 ++ GRDB/Core/TransactionObserver.swift | 302 +++++++++++++- README.md | 376 +----------------- 11 files changed, 338 insertions(+), 390 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index a714f6ebe..7f8158d44 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -3008,7 +3008,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [PersistableRecord]: ../README.md#persistablerecord-protocol [Codable Records]: ../README.md#codable-records [persistence methods]: ../README.md#persistence-methods -[database observation tools]: ../README.md#database-changes-observation +[database observation tools]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation [FAQ]: ../README.md#faq-associations [common table expressions]: CommonTableExpressions.md [Common Table Expressions]: CommonTableExpressions.md diff --git a/Documentation/Combine.md b/Documentation/Combine.md index 97bd766bb..a9004214a 100644 --- a/Documentation/Combine.md +++ b/Documentation/Combine.md @@ -382,7 +382,7 @@ let cancellable = hallOfFamePublisher.sink( [Usage]: #usage [Asynchronous Database Access]: #asynchronous-database-access [Combine]: https://developer.apple.com/documentation/combine -[Database Changes Observation]: ../README.md#database-changes-observation +[Database Changes Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation [Database Observation]: #database-observation [Combine and Data Consistency]: #combine-and-data-consistency [DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index 66f0515c3..05718062b 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -5,7 +5,7 @@ By default, GRDB uses the version of SQLite that ships with the target operating **You can build GRDB with a custom build of [SQLite 3.39.3](https://www.sqlite.org/changes.html).** -A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks). +A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/v6.3.1/documentation/grdb/transactionobserver). GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need. diff --git a/Documentation/FetchedRecordsController.md b/Documentation/FetchedRecordsController.md index 23df660a3..baf6c945a 100644 --- a/Documentation/FetchedRecordsController.md +++ b/Documentation/FetchedRecordsController.md @@ -2,4 +2,4 @@ FetchedRecordsController has been removed in GRDB 5. -The [Database Observation](../README.md#database-changes-observation) chapter describes the other ways to observe the database. +See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for other ways to observe the database. diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index 6062e56e4..8ff58693f 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -510,4 +510,4 @@ let publisher = observation [SQLRequest]: ../README.md#custom-requests [QueryInterfaceRequest]: ../README.md#requests [Combine publishers]: Combine.md -[Database Observation]: ../README.md#database-changes-observation +[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 9befa53bc..60f4e73eb 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -810,10 +810,10 @@ Instead, have a look at [Database Observation]: [Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency [GRDB concurrency rules]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency [PersistableRecord]: ../README.md#persistablerecord-protocol -[Database Observation]: ../README.md#database-changes-observation +[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation [ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation [RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB -[TransactionObserver]: ../README.md#transactionobserver-protocol +[TransactionObserver]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver [Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself [Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables [Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details @@ -823,7 +823,7 @@ Instead, have a look at [Database Observation]: [How to Design Database Managers]: #how-to-design-database-managers [Observe the Database and Refetch when Needed]: #observe-the-database-and-refetch-when-needed [query interface]: ../README.md#the-query-interface -[observe database changes]: ../README.md#database-changes-observation +[observe database changes]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation [data protection]: ../README.md#data-protection [Embrace Errors]: #embrace-errors [Thread-Safety is also an Application Concern]: #thread-safety-is-also-an-application-concern diff --git a/Documentation/QueryInterfaceOrganization.md b/Documentation/QueryInterfaceOrganization.md index 9c33e6aff..f1c27f714 100644 --- a/Documentation/QueryInterfaceOrganization.md +++ b/Documentation/QueryInterfaceOrganization.md @@ -607,7 +607,7 @@ myRequest(Player.select(...).filter(...)) [association aggregates]: AssociationsBasics.md#association-aggregates [Column]: #column [ColumnExpression]: #columnexpression -[DatabaseRegionConvertible]: #databaseregionconvertible +[DatabaseRegionConvertible]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionconvertible [DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation [DatabaseValue]: #databasevalue [DatabaseValueConvertible]: #databasevalueconvertible diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 1cc6e22af..24cd883b3 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -149,7 +149,7 @@ Next, you choose the dispatch queue on which notifications happen (generally the Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, or SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported. -See [Database Observation](../README.md#database-changes-observation) for further information. +See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for further information. ### Non-blocking database reads @@ -301,7 +301,6 @@ Happy GRDB! :gift: [StORM]: https://www.perfect.org/docs/StORM.html [Swift-Kuery]: https://github.com/IBM-Swift/Swift-Kuery [TableRecord]: ../README.md#records -[TransactionObserver]: ../README.md#transactionobserver-protocol [query interface]: ../README.md#the-query-interface [associations]: AssociationsBasics.md [Codable records]: ../README.md#codable-records diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index a293aea6f..384a9e414 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -344,8 +344,37 @@ private struct TableRegion: Equatable { /// A type that operates on a specific ``DatabaseRegion``. /// +/// A `DatabaseRegionConvertible` instance feeds database observation tools such +/// as ``DatabaseRegionObservation`` and ``ValueObservation``: +/// +/// ```swift +/// // An observation triggered by all changes to the database +/// DatabaseRegionObservation(tracking: .fullDatabase) +/// +/// // An observation triggered by all changes to the 'player' table +/// DatabaseRegionObservation(tracking: Table("player")) +/// +/// // An observation triggered by all changes to the row +/// // with rowid 1 in the 'player' table +/// DatabaseRegionObservation(tracking: Player.filter(id: 1)) +/// +/// // An observation triggered by all changes to the 'score' column +/// // of the 'player' table +/// DatabaseRegionObservation(tracking: SQLRequest("SELECT score FROM player")) +/// ``` +/// +/// Specifying a region from a ``FetchRequest`` does not execute the request. +/// In the above example, `Player.filter(id: 1)` and `SELECT score FROM player` +/// are only compiled by SQLite, so that GRDB can understand the tables, rows, +/// and columns that constitute the database region. +/// /// ## Topics /// +/// ### Creating a DatabaseRegion +/// +/// - ``fullDatabase`` +/// - ``databaseRegion(_:)`` +/// /// ### Supporting Types /// /// - ``AnyDatabaseRegionConvertible`` diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 4b15170a9..e16a0f12d 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -739,36 +739,305 @@ class DatabaseObservationBroker { // MARK: - TransactionObserver -/// A type that tracks all database changes and transactions performed in +/// A type that tracks database changes and transactions performed in /// a database. /// +/// ## Overview +/// +/// `TransactionObserver` is the low-level protocol that supports all +/// features. +/// +/// A transaction observer is notified of individual changes (inserts, updates +/// and deletes), before they are committed to disk, as well as transaction +/// commits and rollbacks. +/// +/// ## Activate a Transaction Observer +/// /// An observer starts receiving change notifications after it has been added to /// a database connection with the /// ``DatabaseWriter/add(transactionObserver:extent:)`` `DatabaseWriter` method, -/// or the ``Database/add(transactionObserver:extent:)`` `Database` method. +/// or the ``Database/add(transactionObserver:extent:)`` `Database` method: /// -/// All observer methods are called in the writer dispatch queue, serialized -/// with all database updates (see ``DatabaseWriter``). +/// ```swift +/// let observer = MyObserver() +/// dbQueue.add(transactionObserver: observer) +/// ``` /// -/// Some changes and transactions are not notified: +/// By default, database holds weak references to its transaction observers: +/// they are not retained, and stop getting notifications after they are +/// deallocated. See for +/// more options. /// -/// - Transactions performed in read-only database connections. -/// - Changes and transactions performed by other database connections. -/// - Changes to internal system tables (such as `sqlite_master`). -/// - Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables -/// - 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). +/// ## Database Changes And Transactions +/// +/// Database changes are notified to the ``databaseDidChange(with:)`` callback. +/// 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). +/// +/// Transaction completions are notified to the ``databaseWillCommit()-7mksu``, +/// ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks. +/// +/// Read-only transactions, changes and transactions performed by external +/// database connections, 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) are +/// not notified. +/// +/// Notified changes are not actually written to disk until the transaction +/// commits, and the `databaseDidCommit` callback is called. On the other +/// side, `databaseDidRollback` confirms their invalidation: +/// +/// ```swift +/// try dbQueue.write { db in +/// try db.execute(sql: "INSERT ...") // 1. didChange +/// try db.execute(sql: "UPDATE ...") // 2. didChange +/// } // 3. willCommit, 4. didCommit +/// +/// try dbQueue.inTransaction { db in +/// try db.execute(sql: "INSERT ...") // 1. didChange +/// try db.execute(sql: "UPDATE ...") // 2. didChange +/// return .rollback // 3. didRollback +/// } +/// +/// try dbQueue.write { db in +/// try db.execute(sql: "INSERT ...") // 1. didChange +/// throw SomeError() +/// } // 2. didRollback +/// ``` +/// +/// Database statements that are executed outside of any explicit transaction +/// do not drop off the radar: +/// +/// ```swift +/// try dbQueue.writeWithoutTransaction { db in +/// try db.execute(sql: "INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit +/// try db.execute(sql: "UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit +/// } +/// ``` +/// +/// Changes that are on hold because of a +/// [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified +/// after the savepoint has been released. This makes sure that notified events +/// are only those that have an opportunity to be committed: +/// +/// ```swift +/// try dbQueue.inTransaction { db in +/// try db.execute(sql: "INSERT ...") // 1. didChange +/// +/// try db.execute(sql: "SAVEPOINT foo") +/// try db.execute(sql: "UPDATE ...") // delayed +/// try db.execute(sql: "UPDATE ...") // delayed +/// try db.execute(sql: "RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange +/// +/// try db.execute(sql: "SAVEPOINT bar") +/// try db.execute(sql: "UPDATE ...") // not notified +/// try db.execute(sql: "ROLLBACK TO SAVEPOINT bar") +/// try db.execute(sql: "RELEASE SAVEPOINT bar") +/// +/// return .commit // 4. willCommit, 5. didCommit +/// } +/// ``` +/// +/// Eventual errors thrown from `databaseWillCommit` are exposed to the +/// application code: +/// +/// ```swift +/// do { +/// try dbQueue.inTransaction { db in +/// ... +/// return .commit // 1. willCommit (throws), 2. didRollback +/// } +/// } catch { +/// // 3. The error thrown by the transaction observer. +/// } +/// ``` +/// +/// - Note: All callbacks are called in the writer dispatch queue, and +/// serialized with all database updates. +/// +/// - Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not +/// touch the SQLite database. This limitation does not apply to +/// `databaseDidCommit` and `databaseDidRollback` which can use their +/// database argument. +/// +/// ## Filtering Database Events +/// +/// **Transaction observers can choose the database changes they are +/// interested in.** +/// +/// The filtering happens in the ``observes(eventsOfKind:)`` method, which tells +/// whether the observer wants notifications of specific kinds of changes, +/// or not. +/// +/// The ``DatabaseEventKind`` argument of `observes(eventsOfKind:)` can +/// distinguish insertions from deletions and updates, and is also able to +/// tell the columns that are about to be changed. +/// +/// For example, an observer can focus on the changes that happen on the +/// "player" database table only: +/// +/// ```swift +/// class PlayerObserver: TransactionObserver { +/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { +/// // Only observe changes to the "player" table. +/// eventKind.tableName == "player" +/// } +/// +/// func databaseDidChange(with event: DatabaseEvent) { +/// // This method is only called for changes that happen to +/// // the "player" table. +/// } +/// } +/// ``` +/// +/// When the `observes(eventsOfKind:)` method returns false for all event kinds, +/// the observer is still notified of transactions. +/// +/// ## Observation Extent +/// +/// **You can specify how long an observer is notified of database changes +/// and transactions.** +/// +/// The `remove(transactionObserver:)` method explicitly stops notifications, +/// at any time: +/// +/// ```swift +/// // From a database queue or pool: +/// dbQueue.remove(transactionObserver: observer) +/// +/// // From a database connection: +/// dbQueue.inDatabase { db in +/// db.remove(transactionObserver: observer) +/// } +/// ``` +/// +/// Alternatively, use the `extent` parameter of the +/// `add(transactionObserver:extent:)` method: +/// +/// ```swift +/// let observer = MyObserver() +/// +/// // On a database queue or pool: +/// dbQueue.add(transactionObserver: observer) // default extent +/// dbQueue.add(transactionObserver: observer, extent: .observerLifetime) +/// dbQueue.add(transactionObserver: observer, extent: .nextTransaction) +/// dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) +/// +/// // On a database connection: +/// dbQueue.inDatabase { db in +/// db.add(transactionObserver: ...) +/// } +/// ``` +/// +/// - The default extent is `.observerLifetime`: the database holds a weak +/// reference to the observer, and the observation automatically ends when the +/// observer is deallocated. Meanwhile, the observer is notified of all changes +/// and transactions. +/// +/// - `.nextTransaction` activates the observer until the current or next +/// transaction completes. The database keeps a strong reference to the observer +/// until its `databaseDidCommit` or `databaseDidRollback` callback is called. +/// Hereafter the observer won't get any further notification. +/// +/// - `.databaseLifetime` has the database retain and notify the observer until +/// the database connection is closed. +/// +/// Finally, an observer can avoid processing database changes until the end +/// of the current transaction. After +/// ``stopObservingDatabaseChangesUntilNextTransaction()``, the +/// `databaseDidChange` callback will not be called until the current +/// transaction completes: +/// +/// ```swift +/// class PlayerObserver: TransactionObserver { +/// var playerTableWasModified = false +/// +/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { +/// eventKind.tableName == "player" +/// } +/// +/// func databaseDidChange(with event: DatabaseEvent) { +/// playerTableWasModified = true +/// +/// // It is pointless to keep on tracking further changes: +/// stopObservingDatabaseChangesUntilNextTransaction() +/// } +/// } +/// ``` +/// +/// ### Support for SQLite Pre-Update Hooks +/// +/// When SQLite is built with the `SQLITE_ENABLE_PREUPDATE_HOOK` option, +/// `TransactionObserver` gets an extra callback which lets you observe +/// individual column values in the rows modified by a transaction: +/// +/// ```swift +/// protocol TransactionObserver: AnyObject { +/// #if SQLITE_ENABLE_PREUPDATE_HOOK +/// /// Notifies before a database change (insert, update, or delete) +/// /// with change information (initial / final values for the row's +/// /// columns). +/// /// +/// /// The event is only valid for the duration of this method call. If you +/// /// need to keep it longer, store a copy: event.copy(). +/// func databaseWillChange(with event: DatabasePreUpdateEvent) +/// #endif +/// } +/// ``` +/// +/// This extra API can be activated in two ways: +/// +/// 1. Use the GRDB.swift CocoaPod with a custom compilation option, as below. +/// It uses the system SQLite, which is compiled with +/// `SQLITE_ENABLE_PREUPDATE_HOOK` support, but only on iOS 11.0+ (we don't +/// know the minimum version of macOS, tvOS, watchOS): +/// +/// ```ruby +/// pod 'GRDB.swift' +/// platform :ios, '11.0' # or above +/// +/// post_install do |installer| +/// installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target| +/// target.build_configurations.each do |config| +/// # Enable extra GRDB APIs +/// config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK" +/// # Enable extra SQLite APIs +/// config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1" +/// end +/// end +/// end +/// ``` +/// +/// **Warning**: make sure you use the right platform version! You will get +/// runtime errors on devices with a lower version. +/// +/// **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](http://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) +/// and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option. /// /// ## Topics /// -/// ### Handling Database Changes +/// ### Filtering Database Changes /// /// - ``observes(eventsOfKind:)`` +/// - ``DatabaseEventKind`` +/// +/// ### Handling Database Changes +/// /// - ``databaseDidChange(with:)`` /// - ``stopObservingDatabaseChangesUntilNextTransaction()`` /// - ``DatabaseEvent`` -/// - ``DatabaseEventKind`` /// /// ### Handling Transactions /// @@ -793,6 +1062,11 @@ public protocol TransactionObserver: AnyObject { /// } /// } /// ``` + /// + /// When this method returns true for deletion events, the observer + /// prevents the + /// [truncate optimization](https://www.sqlite.org/lang_delete.html#the_truncate_optimization) + /// from being applied. func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool /// Called when the database is changed by an insert, update, or diff --git a/README.md b/README.md index 06122fa9c..d00b91989 100644 --- a/README.md +++ b/README.md @@ -3864,7 +3864,7 @@ try player.insert(db) > } > ``` > -> **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](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) (this might change in a future release of SQLite). ### Beyond FetchableRecord @@ -5901,367 +5901,6 @@ let playerInfos = try dbQueue.read { db in > :bulb: In this chapter, we have learned how to use the `Decodable` protocol and its associated `CodingKeys` enum in order to dry up our code. -Database Changes Observation -============================ - -**SQLite notifies its host application of changes performed to the database, as well of transaction commits and rollbacks.** - -GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways: - -- [ValueObservation]: Get notified when database values change. -- [DatabaseRegionObservation]: Get notified when a transaction impacts a database region. -- [Transaction Hook](#transaction-hook): Handle transactions commits or rollbacks, one by one. -- [TransactionObserver Protocol](#transactionobserver-protocol): The low-level protocol that supports all database observation features. -- :blue_book: [Combine Support]: Automated tracking of database changes, with [Combine]. -- :blue_book: [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift). - -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. - - -## TransactionObserver Protocol - -The `TransactionObserver` protocol lets you **observe individual database changes and transactions**: - -```swift -protocol TransactionObserver : class { - /// Notifies a database change: - /// - event.kind (insert, update, or delete) - /// - event.tableName - /// - event.rowID - /// - /// For performance reasons, the event is only valid for the duration of - /// this method call. If you need to keep it longer, store a copy: - /// event.copy(). - func databaseDidChange(with event: DatabaseEvent) - - /// Filters the database changes that should be notified to the - /// `databaseDidChange(with:)` method. - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool - - /// An opportunity to rollback pending changes by throwing an error. - func databaseWillCommit() throws - - /// Database changes have been committed. - func databaseDidCommit(_ db: Database) - - /// Database changes have been rollbacked. - func databaseDidRollback(_ db: Database) -} -``` - -- [Activate a Transaction Observer](#activate-a-transaction-observer) -- [Database Changes And Transactions](#database-changes-and-transactions) -- [Filtering Database Events](#filtering-database-events) -- [Observation Extent](#observation-extent) -- [DatabaseRegion] -- [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks) - - -### Activate a Transaction Observer - -**To activate a transaction observer, add it to the database queue or pool:** - -```swift -let observer = MyObserver() -dbQueue.add(transactionObserver: observer) -``` - -By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deinitialized. See [Observation Extent](#observation-extent) for more options. - - -### Database Changes And Transactions - -**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). - -> **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**: 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: - -```swift -try dbQueue.write { db in - try db.execute(sql: "INSERT ...") // 1. didChange - try db.execute(sql: "UPDATE ...") // 2. didChange -} // 3. willCommit, 4. didCommit - -try dbQueue.inTransaction { db in - try db.execute(sql: "INSERT ...") // 1. didChange - try db.execute(sql: "UPDATE ...") // 2. didChange - return .rollback // 3. didRollback -} - -try dbQueue.write { db in - try db.execute(sql: "INSERT ...") // 1. didChange - throw SomeError() -} // 2. didRollback -``` - -Database statements that are executed outside of any transaction do not drop off the radar: - -```swift -try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit - try db.execute(sql: "UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit -} -``` - -Changes that are on hold because of a [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified after the savepoint has been released. This makes sure that notified events are only events that have an opportunity to be committed: - -```swift -try dbQueue.inTransaction { db in - try db.execute(sql: "INSERT ...") // 1. didChange - - try db.execute(sql: "SAVEPOINT foo") - try db.execute(sql: "UPDATE ...") // delayed - try db.execute(sql: "UPDATE ...") // delayed - try db.execute(sql: "RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange - - try db.execute(sql: "SAVEPOINT foo") - try db.execute(sql: "UPDATE ...") // not notified - try db.execute(sql: "ROLLBACK TO SAVEPOINT foo") - - return .commit // 4. willCommit, 5. didCommit -} -``` - - -**Eventual errors** thrown from `databaseWillCommit` are exposed to the application code: - -```swift -do { - try dbQueue.inTransaction { db in - ... - return .commit // 1. willCommit (throws), 2. didRollback - } -} catch { - // 3. The error thrown by the transaction observer. -} -``` - -> **Note**: all callbacks are called in a protected dispatch queue, and serialized with all database updates. -> -> **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. - -See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter. - - -### Filtering Database Events - -**Transaction observers can avoid being notified of database changes they are not interested in.** - -The filtering happens in the `observes(eventsOfKind:)` method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the "player" database table: - -```swift -class PlayerObserver: TransactionObserver { - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - // Only observe changes to the "player" table. - return eventKind.tableName == "player" - } - - func databaseDidChange(with event: DatabaseEvent) { - // This method is only called for changes that happen to - // the "player" table. - } -} -``` - -Generally speaking, the `observes(eventsOfKind:)` method can distinguish insertions from deletions and updates, and is also able to inspect the columns that are about to be changed: - -```swift -class PlayerScoreObserver: TransactionObserver { - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - // Only observe changes to the "score" column of the "player" table. - switch eventKind { - case .insert(let tableName): - return tableName == "player" - case .delete(let tableName): - return tableName == "player" - case .update(let tableName, let columnNames): - return tableName == "player" && columnNames.contains("score") - } - } -} -``` - -When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of commits and rollbacks (except during read-only database accesses): - -```swift -class PureTransactionObserver: TransactionObserver { - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - // Ignore all individual changes - return false - } - - func databaseDidChange(with event: DatabaseEvent) { /* Never called */ } - func databaseWillCommit() throws { /* Called before commit */ } - func databaseDidRollback(_ db: Database) { /* Called on rollback */ } - func databaseDidCommit(_ db: Database) { /* Called on commit */ } -} -``` - -For more information about event filtering, see [DatabaseRegion]. - - -### Observation Extent - -**You can specify how long an observer is notified of database changes and transactions.** - -The `remove(transactionObserver:)` method explicitly stops notifications, at any time: - -```swift -// From a database queue or pool: -dbQueue.remove(transactionObserver: observer) - -// From a database connection: -dbQueue.inDatabase { db in - db.remove(transactionObserver: observer) -} -``` - -Alternatively, use the `extent` parameter of the `add(transactionObserver:extent:)` method: - -```swift -let observer = MyObserver() - -// On a database queue or pool: -dbQueue.add(transactionObserver: observer) // default extent -dbQueue.add(transactionObserver: observer, extent: .observerLifetime) -dbQueue.add(transactionObserver: observer, extent: .nextTransaction) -dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) - -// On a database connection: -dbQueue.inDatabase { db in - db.add(transactionObserver: ...) -} -``` - -- The default extent is `.observerLifetime`: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deinitialized. Meanwhile, observer is notified of all changes and transactions. - -- `.nextTransaction` activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its `databaseDidCommit` or `databaseDidRollback` method is eventually called. Hereafter the observer won't get any further notification. - -- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed. - -Finally, an observer may ignore all database changes until the end of the current transaction: - -```swift -class PlayerObserver: TransactionObserver { - var playerTableWasModified = false - - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - eventKind.tableName == "player" - } - - func databaseDidChange(with event: DatabaseEvent) { - playerTableWasModified = true - - // It is pointless to keep on tracking further changes: - stopObservingDatabaseChangesUntilNextTransaction() - } -} -``` - -After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChange(with:)` method will not be notified of any change for the remaining duration of the current transaction. This helps GRDB optimize database observation. - - -### DatabaseRegion - -A `DatabaseRegion` is a reunion of database tables, and combination of columns and rows (identified by their rowid): - - |Table1 | |Table2 | |Table3 | |Table4 | |Table5 | - |-------| |-------| |-------| |-------| |-------| - |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | | - |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | | - |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | | - |x|x|x|x| |x| | | | | | | | | | | | | | | | | | | - -DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track changes in the database through the [TransactionObserver](#transactionobserver-protocol) protocol. - -**Note that observing a database region spots *potential* changes, not *actual* changes in the results of a request.** A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row. - -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://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregion/). - - -#### The DatabaseRegionConvertible Protocol - -**DatabaseRegionConvertible** is a protocol for all types that can turn into a [DatabaseRegion]: - -```swift -protocol DatabaseRegionConvertible { - func databaseRegion(_ db: Database) throws -> DatabaseRegion -} -``` - -All [requests](#requests) adopt this protocol, and this allows them to be observed with [DatabaseRegionObservation] and [ValueObservation]. - -For example: - -```swift -// An observation triggered by all changes to the database -DatabaseRegionObservation(tracking: .fullDatabase) - -// An observation triggered by all changes to the player table -DatabaseRegionObservation(tracking: Table("player")) - -// An observation triggered by all changes to the row with rowid 1 in the player table -DatabaseRegionObservation(tracking: Player.filter(id: 1)) - -// An observation triggered by all changes to the score column of the player table -DatabaseRegionObservation(tracking: SQLRequest("SELECT score FROM player")) -``` - -Note that specifying a region as a request _does not run the request_. In the above example, `Player.filter(id: 1)` and `SELECT score FROM player` are never executed. They are only _compiled_ by SQLite, so that GRDB understands the tables, rows, and columns that constitute the database region. - -### Support for SQLite Pre-Update Hooks - -When SQLite is built with the SQLITE_ENABLE_PREUPDATE_HOOK option, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction: - -```swift -protocol TransactionObserverType : class { - #if SQLITE_ENABLE_PREUPDATE_HOOK - /// Notifies before a database change (insert, update, or delete) - /// with change information (initial / final values for the row's - /// columns). - /// - /// The event is only valid for the duration of this method call. If you - /// need to keep it longer, store a copy: event.copy(). - func databaseWillChange(with event: DatabasePreUpdateEvent) - #endif -} -``` - -This extra API can be activated in two ways: - -1. Use the GRDB.swift CocoaPod with a custom compilation option, as below. It uses the system SQLite, which is compiled with SQLITE_ENABLE_PREUPDATE_HOOK support, but only on iOS 11.0+ (we don't know the minimum version of macOS, tvOS, watchOS): - - ```ruby - pod 'GRDB.swift' - platform :ios, '11.0' # or above - - post_install do |installer| - installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target| - target.build_configurations.each do |config| - # Enable extra GRDB APIs - config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK" - # Enable extra SQLite APIs - config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1" - end - end - end - ``` - - > **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version. - - > **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. - - Encryption ========== @@ -7649,6 +7288,10 @@ This chapter has been renamed [Beyond FetchableRecord]. This chapter was replaced with [Persistence Callbacks]. +#### Database Changes Observation + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation). + #### Database Snapshots This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). @@ -7703,6 +7346,10 @@ This protocol has been renamed [FetchableRecord] in GRDB 3.0. This protocol has been renamed [TableRecord] in GRDB 3.0. +#### TransactionObserver Protocol + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver). + #### Unsafe Concurrency APIs This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). @@ -7742,8 +7389,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation [DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation [RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB -[DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol -[DatabaseRegion]: #databaseregion +[DatabaseRegion]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregion [SQL Interpolation]: Documentation/SQLInterpolation.md [custom SQLite build]: Documentation/CustomSQLiteBuilds.md [Combine]: https://developer.apple.com/documentation/combine @@ -7752,7 +7398,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Demo Applications]: Documentation/DemoApps [Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing [FAQ]: #faq -[Database Observation]: #database-changes-observation +[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation [SQLRequest]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sqlrequest [SQL literal]: Documentation/SQLInterpolation.md#sql-literal [Identifiable]: https://developer.apple.com/documentation/swift/identifiable From 7343912ac320be9a28307dd12cebd0671ad94ff6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 28 Nov 2022 08:31:45 +0100 Subject: [PATCH 64/69] Fix broken links --- README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d00b91989..884fe7105 100644 --- a/README.md +++ b/README.md @@ -3248,7 +3248,7 @@ In the `MutablePersistableRecord` protocol, `willInsert` and `didInsert` are mut > > **Warning**: Callbacks are only invoked from persistence methods called on record instances. Callbacks are not invoked when you call a type method, perform a batch operations, or execute raw SQL. > -> **Warning**: When a `did***` callback is invoked, do not assume that the change is actually persisted on disk, because the database may still be inside an uncommitted transaction. When you need to handle transaction completions, use the [Transaction Hook](#transaction-hook). For example: +> **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 [afterNextTransaction(onCommit:onRollback:)](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)). For example: > > ```swift > struct PictureFile: PersistableRecord { @@ -7266,7 +7266,7 @@ This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/document #### After Commit Hook -This chapter was replaced with [Transaction Hook]. +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)). #### Asynchronous APIs @@ -7346,6 +7346,10 @@ This protocol has been renamed [FetchableRecord] in GRDB 3.0. This protocol has been renamed [TableRecord] in GRDB 3.0. +#### Transaction Hook + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)). + #### TransactionObserver Protocol This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver). From 65bd4d90c2c1ea927db5ae0c9eb6945d188b84b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 28 Nov 2022 08:36:30 +0100 Subject: [PATCH 65/69] Enhance DatabaseRegionObservation documentation --- GRDB/Core/DatabaseRegionObservation.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index a8b1c4d88..eb95739af 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -73,9 +73,9 @@ import Foundation /// } /// ``` /// -/// You can feed DatabaseRegionObservation with any type that conforms to -/// the ``DatabaseRegionConvertible`` protocol: requests, ``DatabaseRegion``, -/// ``Table``, etc. For example: +/// You can feed `DatabaseRegionObservation` with any type that conforms to +/// the ``DatabaseRegionConvertible`` protocol: ``FetchRequest``, +/// ``DatabaseRegion``, ``Table``, etc. For example: /// /// ```swift /// // Observe the score column of the 'player' table From 69e4706549c098f65c2afbbbdfd43e30c67764d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Mon, 28 Nov 2022 10:37:39 +0100 Subject: [PATCH 66/69] Expose CSQLite as a SPM product --- Package.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Package.swift b/Package.swift index 84fd49f6c..521f5799f 100644 --- a/Package.swift +++ b/Package.swift @@ -37,6 +37,7 @@ let package = Package( .watchOS(.v4), ], products: [ + .library(name: "CSQLite", targets: ["CSQLite"]), .library(name: "GRDB", targets: ["GRDB"]), .library(name: "GRDB-dynamic", type: .dynamic, targets: ["GRDB"]), ], From a27c34e635e88857ae628d7200154b7b2147869c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Mon, 28 Nov 2022 13:19:56 +0100 Subject: [PATCH 67/69] CHANGELOG --- CHANGELOG.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01fd9bd1c..9e5690444 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -103,13 +103,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Version +- **New**: [#1293](https://github.com/groue/GRDB.swift/pull/1293) by [@groue](https://github.com/groue): Enable concurrent reads from a WAL snapshot. +- **New**: [#1297](https://github.com/groue/GRDB.swift/pull/1297) by [@groue](https://github.com/groue): SPM: expose the CSQLite product. - **New**: `DatabaseReader.configuration.readQoS` and `writeQoS` return the effective quality of service of read-only and write database accesses. This helps application code avoid priority inversion and similar scheduling misuses when needed. - **New**: `DatabaseReader.configuration.maximumReaderCount` returns the effective capacity for concurrent reads, so that application code can adapt when needed. - **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime. - **New**: `Database.registerAccess(to:)` has `ValueObservation` track a region. This helps building optimized observations of a constant database region with `ValueObservation.trackingConstantRegion(_:)`. - **New**: Open several connections to the same in-memory database with `DatabaseQueue(named:)`. -- **New**: `TableDefinition` has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended. -- **New**: [#1293](https://github.com/groue/GRDB.swift/pull/1293) by [@groue](https://github.com/groue): Enable concurrent reads from a WAL snapshot. +- **New**: [`TableDefinition`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition)) has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended. ## 6.3.1 From cbd05c9037e315956dc258752997acb13e0d9d30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Mon, 28 Nov 2022 13:28:35 +0100 Subject: [PATCH 68/69] Fix documentation link --- Documentation/CustomSQLiteBuilds.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index 05718062b..5df56ab8f 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -5,7 +5,7 @@ By default, GRDB uses the version of SQLite that ships with the target operating **You can build GRDB with a custom build of [SQLite 3.39.3](https://www.sqlite.org/changes.html).** -A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/v6.3.1/documentation/grdb/transactionobserver). +A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver). GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need. From 72f56a1b03b0bc96c8e3984f0ced7919c56ee135 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Mon, 28 Nov 2022 13:29:23 +0100 Subject: [PATCH 69/69] v6.4.0 --- CHANGELOG.md | 5 ++++- GRDB.swift.podspec | 2 +- README.md | 4 ++-- Support/Info.plist | 2 +- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e5690444..eda40803d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 6.x Releases +- `6.4.x` Releases - [6.4.0](#640) - `6.3.x` Releases - [6.3.0](#630) - [6.3.1](#631) - `6.2.x` Releases - [6.2.0](#620) - `6.1.x` Releases - [6.1.0](#610) @@ -101,7 +102,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- -## Next Version +## 6.4.0 + +Released November 28, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.3.1...v6.4.0) - **New**: [#1293](https://github.com/groue/GRDB.swift/pull/1293) by [@groue](https://github.com/groue): Enable concurrent reads from a WAL snapshot. - **New**: [#1297](https://github.com/groue/GRDB.swift/pull/1297) by [@groue](https://github.com/groue): SPM: expose the CSQLite product. diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 11654db6e..35ae05b93 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '6.3.1' + s.version = '6.4.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/README.md b/README.md index 884fe7105..49cda67fe 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: November 11, 2022 • [version 6.3.1](https://github.com/groue/GRDB.swift/tree/v6.3.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) +**Latest release**: November 28, 2022 • [version 6.4.0](https://github.com/groue/GRDB.swift/tree/v6.4.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.19.3+ • Swift 5.7+ / Xcode 14+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.7+** | **v6.3.1** | +| **Swift 5.7+** | **v6.4.0** | | Swift 5.3 | [v5.26.1](https://github.com/groue/GRDB.swift/tree/v5.26.1) | | 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) | diff --git a/Support/Info.plist b/Support/Info.plist index 430b388d3..1cd426410 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 6.3.1 + 6.4.0 CFBundleSignature ???? CFBundleVersion