From 38c0d68db70ce3507f7243a9f6ecbecfc3636596 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 22 Jun 2022 18:40:28 +0200 Subject: [PATCH 1/5] WALSnapshot SQLITE_ENABLE_SNAPSHOT is available from Xcode 14 :-) --- .../xcschemes/GRDBDemoWatchOS.xcscheme | 25 ++- GRDB.xcodeproj/project.pbxproj | 12 +- GRDB/Core/Database.swift | 32 ---- GRDB/Core/DatabaseSnapshot.swift | 29 +-- GRDB/Core/WALSnapshot.swift | 85 +++++++++ .../ValueConcurrentObserver.swift | 178 ++---------------- GRDBCustom.xcodeproj/project.pbxproj | 10 +- Tests/GRDBTests/ValueObservationTests.swift | 118 ++++++------ 8 files changed, 203 insertions(+), 286 deletions(-) create mode 100644 GRDB/Core/WALSnapshot.swift diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme index 237e9f7b3..4fbad19f2 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme @@ -78,8 +78,10 @@ debugDocumentVersioning = "YES" debugServiceExtension = "internal" allowLocationSimulation = "YES"> - + - + - + - + + + + + diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index e0d1d75e6..f48bd54f1 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -733,6 +733,10 @@ 56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; }; 56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; }; + 56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; }; + 56B7EE842863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; }; + 56B7EE852863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; }; + 56B7EE862863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; }; 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; }; 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; @@ -1595,6 +1599,7 @@ 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = ""; }; + 56B7EE822863781300C0525F /* WALSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshot.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; 56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = ""; }; @@ -2375,8 +2380,9 @@ 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, - 5605F1471C672E4000235C62 /* Support */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, + 56B7EE822863781300C0525F /* WALSnapshot.swift */, + 5605F1471C672E4000235C62 /* Support */, ); path = Core; sourceTree = ""; @@ -2976,6 +2982,7 @@ 565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */, 5656A8AF2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */, 565490C21D5AE236005622CB /* Row.swift in Sources */, + 56B7EE852863781300C0525F /* WALSnapshot.swift in Sources */, 565490C71D5AE236005622CB /* StatementColumnConvertible.swift in Sources */, 565490D91D5AE252005622CB /* Migration.swift in Sources */, 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */, @@ -3145,6 +3152,7 @@ 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 56DDDDF5242F87C60025E381 /* ValueObservationScheduler.swift in Sources */, + 56B7EE842863781300C0525F /* WALSnapshot.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, 56A2FA3B24424F4700E97D23 /* Export.swift in Sources */, 569BBA4F229170F900478429 /* Inflections+English.swift in Sources */, @@ -3753,6 +3761,7 @@ AAA4DCA5230F1E0600C74B15 /* FTS3TokenizerDescriptor.swift in Sources */, AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */, 56DDDDF7242F87C70025E381 /* ValueObservationScheduler.swift in Sources */, + 56B7EE862863781300C0525F /* WALSnapshot.swift in Sources */, AAA4DCA7230F1E0600C74B15 /* TableRecord.swift in Sources */, 56A2FA3D24424F4800E97D23 /* Export.swift in Sources */, AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */, @@ -4125,6 +4134,7 @@ 569BBA4E229170F800478429 /* Inflections+English.swift in Sources */, 5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */, 5617294E223533F40006E219 /* EncodableRecord.swift in Sources */, + 56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */, 5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */, 56A2FA3624424D2A00E97D23 /* Export.swift in Sources */, 56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 0b40f9955..46c2570a4 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -553,38 +553,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib _readOnlyDepth > 0 || configuration.readonly } - // MARK: - Snapshots - - #if SQLITE_ENABLE_SNAPSHOT - /// Returns a snapshot that must be freed with `sqlite3_snapshot_free`. - /// - /// See - func takeVersionSnapshot() throws -> UnsafeMutablePointer { - var snapshot: UnsafeMutablePointer? - let code = withUnsafeMutablePointer(to: &snapshot) { - sqlite3_snapshot_get(sqliteConnection, "main", $0) - } - guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: lastErrorMessage) - } - if let snapshot = snapshot { - return snapshot - } else { - throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite? - } - } - - func wasChanged(since initialSnapshot: UnsafeMutablePointer) throws -> Bool { - let secondSnapshot = try takeVersionSnapshot() - defer { - sqlite3_snapshot_free(secondSnapshot) - } - let cmp = sqlite3_snapshot_cmp(initialSnapshot, secondSnapshot) - assert(cmp <= 0, "Unexpected snapshot ordering") - return cmp < 0 - } - #endif - // MARK: - Recording of the selected region func recordingSelection(_ region: inout DatabaseRegion, _ block: () throws -> T) rethrows -> T { diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index bf44be266..e9d7a6ae4 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -14,14 +14,6 @@ public final class DatabaseSnapshot: DatabaseReader { serializedDatabase.configuration } -#if SQLITE_ENABLE_SNAPSHOT - typealias Version = UnsafeMutablePointer - // Support for ValueObservation in DatabasePool - let version: Version? -#else - typealias Version = Void -#endif - init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws { var configuration = DatabasePool.readerConfiguration(configuration) configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction @@ -31,8 +23,8 @@ public final class DatabaseSnapshot: DatabaseReader { configuration: configuration, defaultLabel: defaultLabel, purpose: purpose) - - let version: Version? = try serializedDatabase.sync { db in + + try serializedDatabase.sync { db in // Assert WAL mode let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode") guard journalMode == "wal" else { @@ -44,29 +36,12 @@ public final class DatabaseSnapshot: DatabaseReader { // Acquire snapshot isolation try db.internalCachedStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next() - - #if SQLITE_ENABLE_SNAPSHOT - // We must expect an error: https://www.sqlite.org/c3ref/snapshot_get.html - // > At least one transaction must be written to it first. - return try? db.takeVersionSnapshot() - #else - return nil - #endif } - - #if SQLITE_ENABLE_SNAPSHOT - self.version = version - #endif } deinit { // Leave snapshot isolation serializedDatabase.reentrantSync { db in - #if SQLITE_ENABLE_SNAPSHOT - if let version = version { - sqlite3_snapshot_free(version) - } - #endif try? db.commit() } } diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift new file mode 100644 index 000000000..a6a9088da --- /dev/null +++ b/GRDB/Core/WALSnapshot.swift @@ -0,0 +1,85 @@ +/// An instance of WALSnapshot records the state of a WAL mode database for some +/// specific point in history. +/// +/// We use `WALSnapshot` to help `ValueObservation` check for changes +/// that would happen between the initial fetch, and the start of the +/// actual observation. This class has no other purpose, and is not intended to +/// become public. +/// +/// It does not work with SQLCipher, because SQLCipher does not support +/// `SQLITE_ENABLE_SNAPSHOT` correctly: we have linker errors. +/// See . +/// +/// With custom SQLite builds, it only works if `SQLITE_ENABLE_SNAPSHOT` +/// is defined. +/// +/// With system SQLite, it can only work when the SDK exposes the C apis and +/// their availability, which means XCode 14 (identified with Swift 5.7). +/// +/// Yes, this is an awfully complex logic. +/// +/// See . +final class WALSnapshot { +#if GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7) + init?(_ db: Database) { + return nil + } + + func compare(_ other: WALSnapshot) -> CInt { + preconditionFailure("snapshots are not available") + } +#else + private let snapshot: UnsafeMutablePointer? + + /// Returns nil if `SQLITE_ENABLE_SNAPSHOT` is not enabled, or if an + /// error occurs. + init?(_ db: Database) { + var snapshot: UnsafeMutablePointer? + let code: CInt = withUnsafeMutablePointer(to: &snapshot) { +#if GRDBCUSTOMSQLITE + return sqlite3_snapshot_get(db.sqliteConnection, "main", $0) +#else + // iOS 10.0 is always true because our minimum requirement is iOS 11. + if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { + return sqlite3_snapshot_get(db.sqliteConnection, "main", $0) + } else { + return SQLITE_ERROR + } +#endif + } + guard code == SQLITE_OK, let snapshot = snapshot else { + return nil + } + self.snapshot = snapshot + } + + deinit { +#if GRDBCUSTOMSQLITE + sqlite3_snapshot_free(snapshot) +#else + // iOS 10.0 is always true because our minimum requirement is iOS 11. + if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { + sqlite3_snapshot_free(snapshot) + } +#endif + } + + /// Compares two WAL snapshots. + /// + /// `a.compare(b) < 0` iff a is older than b. + /// + /// See . + func compare(_ other: WALSnapshot) -> CInt { +#if GRDBCUSTOMSQLITE + return sqlite3_snapshot_cmp(snapshot, other.snapshot) +#else + // iOS 10.0 is always true because our minimum requirement is iOS 11. + if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { + return sqlite3_snapshot_cmp(snapshot, other.snapshot) + } else { + preconditionFailure("snapshots are not available") + } +#endif + } +#endif // GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7) +} diff --git a/GRDB/ValueObservation/ValueConcurrentObserver.swift b/GRDB/ValueObservation/ValueConcurrentObserver.swift index 6e0f3c2aa..028a4441f 100644 --- a/GRDB/ValueObservation/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/ValueConcurrentObserver.swift @@ -186,6 +186,9 @@ final class ValueConcurrentObserver { // 1. Start the observation without waiting for a write access (the expected // benefit of `DatabasePool`). // 2. Make sure we do not miss a change (a documented guarantee) +// +// Support for `SQLITE_ENABLE_SNAPSHOT` is implemented by our +// `WALSnapshot` class. extension ValueConcurrentObserver { // Starts the observation func start() -> DatabaseCancellable { @@ -234,7 +237,6 @@ extension ValueConcurrentObserver { } } -#if SQLITE_ENABLE_SNAPSHOT // MARK: - Starting the Observation (with SQLITE_ENABLE_SNAPSHOT) extension ValueConcurrentObserver { @@ -249,13 +251,16 @@ extension ValueConcurrentObserver { // // Fetch value & tracked region in a synchronous way. let initialSnapshot = try databaseAccess.dbPool.makeSnapshot() - let (fetchedValue, initialRegion): (Reducer.Fetched, DatabaseRegion) = try initialSnapshot.read { db in + let (fetchedValue, initialRegion, initialWALSnapshot) = try initialSnapshot.read { + db -> (Reducer.Fetched, DatabaseRegion, WALSnapshot?) in + // swiftlint:disable:previous closure_parameter_position + switch trackingMode { case let .constantRegion(regions): let fetchedValue = try databaseAccess.fetch(db) let region = try DatabaseRegion.union(regions)(db) let initialRegion = try region.observableRegion(db) - return (fetchedValue, initialRegion) + return (fetchedValue, initialRegion, WALSnapshot(db)) case .constantRegionRecordedFromSelection, .nonConstantRegionRecordedFromSelection: @@ -264,7 +269,7 @@ extension ValueConcurrentObserver { try databaseAccess.fetch(db) } let initialRegion = try region.observableRegion(db) - return (fetchedValue, initialRegion) + return (fetchedValue, initialRegion, WALSnapshot(db)) } } @@ -280,6 +285,7 @@ extension ValueConcurrentObserver { asyncStartObservation( from: databaseAccess, initialSnapshot: initialSnapshot, + initialWALSnapshot: initialWALSnapshot, initialRegion: initialRegion) return initialValue @@ -344,6 +350,7 @@ extension ValueConcurrentObserver { self.asyncStartObservation( from: databaseAccess, initialSnapshot: initialSnapshot, + initialWALSnapshot: WALSnapshot(db), initialRegion: initialRegion) } catch { self.notifyError(error) @@ -357,6 +364,7 @@ extension ValueConcurrentObserver { private func asyncStartObservation( from databaseAccess: DatabaseAccess, initialSnapshot: DatabaseSnapshot, + initialWALSnapshot: WALSnapshot?, initialRegion: DatabaseRegion) { databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in @@ -371,13 +379,17 @@ extension ValueConcurrentObserver { try writerDB.isolated(readOnly: true) { // Keep DatabaseSnaphot alive until we have compared // database versions. It prevents database checkpointing, - // and keeps versions (`sqlite3_snapshot`) valid + // and keeps WAL snapshots (`sqlite3_snapshot`) valid // and comparable. - let isModified: Bool = try withExtendedLifetime(initialSnapshot) { - guard let initialVersion = initialSnapshot.version else { + let isModified: Bool = withExtendedLifetime(initialSnapshot) { + guard let initialWALSnapshot = initialWALSnapshot, + let currentWALSnapshot = WALSnapshot(writerDB) + else { return true } - return try writerDB.wasChanged(since: initialVersion) + let ordering = initialWALSnapshot.compare(currentWALSnapshot) + assert(ordering <= 0, "Unexpected snapshot ordering") + return ordering < 0 } if isModified { @@ -438,156 +450,6 @@ extension ValueConcurrentObserver { } } -#else -// MARK: - Starting the Observation (without 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. - private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value { - // Start from a read access. The whole point of using a DatabasePool - // for observing the database is to be able to fetch the initial value - // without having to wait for an eventual long-running write - // transaction to complete. - // - // Fetch in a synchronous reentrant way, in case this method is called - // from a database access. - let fetchedValue = try databaseAccess.dbPool.unsafeReentrantRead { db in - try db.isolated(readOnly: true) { - try databaseAccess.fetch(db) - } - } - - // Reduce - let initialValue: Reducer.Value = reduceQueue.sync { - guard let initialValue = reducer._value(fetchedValue) else { - fatalError("Broken contract: reducer has no initial value") - } - return initialValue - } - - // Start observation - asyncStartObservation(from: databaseAccess) - - return initialValue - } - - /// Asynchronously starts the observation - /// - /// Unlike `syncStart()`, this method does notify the initial value or error. - private func asyncStart(from databaseAccess: DatabaseAccess) { - // Start from a read access. The whole point of using a DatabasePool - // for observing the database is to be able to fetch the initial value - // without having to wait for an eventual long-running write - // transaction to complete. - databaseAccess.dbPool.asyncRead { dbResult in - let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } - guard isNotifying else { return /* Cancelled */ } - - do { - // Fetch - let fetchedValue = try databaseAccess.fetch(dbResult.get()) - - // Reduce - // - // Reducing is performed asynchronously, so that we do not lock - // a database dispatch queue longer than necessary. - self.reduceQueue.async { - let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } - guard isNotifying else { return /* Cancelled */ } - - guard let initialValue = self.reducer._value(fetchedValue) else { - fatalError("Broken contract: reducer has no initial value") - } - - // Notify - self.scheduler.schedule { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange } - guard let onChange = onChangeOpt else { return /* Cancelled */ } - onChange(initialValue) - } - - // Start observation - self.asyncStartObservation(from: databaseAccess) - } - } catch { - self.notifyError(error) - } - } - } - - private func asyncStartObservation(from databaseAccess: DatabaseAccess) { - databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let eventsOpt = self.lock.synchronized { self.notificationCallbacks?.events } - guard let events = eventsOpt else { return /* Cancelled */ } - - // We don't know if database has changed or not. - // So we assume it did, so that we are sure that we do - // not miss a database change. - events.databaseDidChange?() - - do { - // Fetch - let fetchedValue: Reducer.Fetched - - switch self.trackingMode { - case let .constantRegion(regions): - fetchedValue = try writerDB.isolated(readOnly: true) { - try databaseAccess.fetch(writerDB) - } - let region = try DatabaseRegion.union(regions)(writerDB) - let observedRegion = try region.observableRegion(writerDB) - events.willTrackRegion?(observedRegion) - self.startObservation(writerDB, observedRegion: observedRegion) - - case .constantRegionRecordedFromSelection, - .nonConstantRegionRecordedFromSelection: - var region = DatabaseRegion() - fetchedValue = try writerDB.recordingSelection(®ion) { - try writerDB.isolated(readOnly: true) { - try databaseAccess.fetch(writerDB) - } - } - let observedRegion = try region.observableRegion(writerDB) - events.willTrackRegion?(observedRegion) - self.startObservation(writerDB, observedRegion: observedRegion) - } - - // Reduce - // - // Reducing is performed asynchronously, so that we do not lock - // the writer dispatch queue longer than necessary. - // - // Important: reduceQueue.async guarantees the same ordering - // between transactions and notifications! - self.reduceQueue.async { - let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } - guard isNotifying else { return /* Cancelled */ } - - let value = self.reducer._value(fetchedValue) - - // Notify - if let value = value { - self.scheduler.schedule { - // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ - let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange } - guard let onChange = onChangeOpt else { return /* Cancelled */ } - onChange(value) - } - } - } - } catch { - self.stopDatabaseObservation(writerDB) - self.notifyError(error) - } - } - } -} -#endif - // MARK: - Observing Database Transactions extension ValueConcurrentObserver: TransactionObserver { diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 75519a27c..3b2e7c5cf 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -214,6 +214,8 @@ 5653EB8120961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; 5653EB8220961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; }; 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 56564F3928637C9900A19E9F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56564F3828637C9900A19E9F /* WALSnapshot.swift */; }; + 56564F3A28637C9900A19E9F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56564F3828637C9900A19E9F /* WALSnapshot.swift */; }; 5656A7F622946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A7F422946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 5656A7F722946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A7F422946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 5656A8512295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8262295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift */; }; @@ -913,6 +915,7 @@ 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; + 56564F3828637C9900A19E9F /* WALSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshot.swift; sourceTree = ""; }; 5656A7F422946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationQueryInterfaceRequestTests.swift; sourceTree = ""; }; 5656A8262295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLInterpolation+QueryInterface.swift"; sourceTree = ""; }; 5656A8282295BD56001FF3FF /* FTS5+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS5+QueryInterface.swift"; sourceTree = ""; }; @@ -1830,8 +1833,9 @@ 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, - 5605F1471C672E4000235C62 /* Support */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, + 56564F3828637C9900A19E9F /* WALSnapshot.swift */, + 5605F1471C672E4000235C62 /* Support */, ); path = Core; sourceTree = ""; @@ -1961,8 +1965,8 @@ DC37742D19C8CC90004FCF85 /* GRDB */ = { isa = PBXGroup; children = ( - 56A2386F1B9C75030082EB20 /* Core */, 56A2FA3724424F4200E97D23 /* Export.swift */, + 56A2386F1B9C75030082EB20 /* Core */, 5614089D221596A100DAD589 /* Fixit */, 5698AC291D9E5A480056AF8C /* FTS */, 56A238911B9C750B0082EB20 /* Migration */, @@ -2360,6 +2364,7 @@ 56A6EB2526076F6A00C27594 /* SQL.swift in Sources */, 5656A8762295BD56001FF3FF /* RequestProtocols.swift in Sources */, 568ECB3625D91CEF00B71526 /* SQLSubquery.swift in Sources */, + 56564F3A28637C9900A19E9F /* WALSnapshot.swift in Sources */, 561729552235340E0006E219 /* EncodableRecord.swift in Sources */, 5656A87E2295BD56001FF3FF /* SQLAssociation.swift in Sources */, F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */, @@ -2731,6 +2736,7 @@ 56A6EB2426076F6A00C27594 /* SQL.swift in Sources */, 5656A8752295BD56001FF3FF /* RequestProtocols.swift in Sources */, 568ECB3525D91CEF00B71526 /* SQLSubquery.swift in Sources */, + 56564F3928637C9900A19E9F /* WALSnapshot.swift in Sources */, 561729562235340E0006E219 /* EncodableRecord.swift in Sources */, 5656A87D2295BD56001FF3FF /* SQLAssociation.swift in Sources */, F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */, diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 13848be8d..b7252bb2a 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -418,39 +418,38 @@ class ValueObservationTests: GRDBTestCase { return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")! } - #if SQLITE_ENABLE_SNAPSHOT - let expectation = self.expectation(description: "") - expectation.expectedFulfillmentCount = 2 - var observedCounts: [Int] = [] - let cancellable = observation.start( - in: dbPool, - scheduling: .async(onQueue: .main), - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - observedCounts.append(count) - expectation.fulfill() - }) - withExtendedLifetime(cancellable) { - waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, [0, 1]) - } + let expectedCounts: [Int] + #if GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7) + // Optimization not available + expectedCounts = [0, 0, 1] + #elseif GRDBCUSTOMSQLITE + // Optimization available + expectedCounts = [0, 1] #else - let expectation = self.expectation(description: "") - expectation.expectedFulfillmentCount = 3 - var observedCounts: [Int] = [] - let cancellable = observation.start( - in: dbPool, - scheduling: .async(onQueue: .main), - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - observedCounts.append(count) - expectation.fulfill() - }) - withExtendedLifetime(cancellable) { - waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, [0, 0, 1]) + if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { + // Optimization available + expectedCounts = [0, 1] + } else { + // Optimization not available + expectedCounts = [0, 0, 1] } #endif + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = expectedCounts.count + var observedCounts: [Int] = [] + let cancellable = observation.start( + in: dbPool, + scheduling: .async(onQueue: .main), + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { count in + observedCounts.append(count) + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 2, handler: nil) + XCTAssertEqual(observedCounts, expectedCounts) + } } func testAllowedSnapshotOptimizationWithImmediateScheduler() throws { @@ -477,39 +476,38 @@ class ValueObservationTests: GRDBTestCase { return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")! } - #if SQLITE_ENABLE_SNAPSHOT - let expectation = self.expectation(description: "") - expectation.expectedFulfillmentCount = 2 - var observedCounts: [Int] = [] - let cancellable = observation.start( - in: dbPool, - scheduling: .immediate, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - observedCounts.append(count) - expectation.fulfill() - }) - withExtendedLifetime(cancellable) { - waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, [0, 1]) - } + let expectedCounts: [Int] + #if GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7) + // Optimization not available + expectedCounts = [0, 0, 1] + #elseif GRDBCUSTOMSQLITE + // Optimization available + expectedCounts = [0, 1] #else - let expectation = self.expectation(description: "") - expectation.expectedFulfillmentCount = 3 - var observedCounts: [Int] = [] - let cancellable = observation.start( - in: dbPool, - scheduling: .immediate, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - observedCounts.append(count) - expectation.fulfill() - }) - withExtendedLifetime(cancellable) { - waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, [0, 0, 1]) + if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { + // Optimization available + expectedCounts = [0, 1] + } else { + // Optimization not available + expectedCounts = [0, 0, 1] } #endif + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = expectedCounts.count + var observedCounts: [Int] = [] + let cancellable = observation.start( + in: dbPool, + scheduling: .immediate, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { count in + observedCounts.append(count) + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 2, handler: nil) + XCTAssertEqual(observedCounts, expectedCounts) + } } // MARK: - Cancellation From 44ec3535c23aefe7eccde0293c92c5a67d332ba9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 22 Jun 2022 19:25:20 +0200 Subject: [PATCH 2/5] Documentation --- GRDB/ValueObservation/ValueConcurrentObserver.swift | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/GRDB/ValueObservation/ValueConcurrentObserver.swift b/GRDB/ValueObservation/ValueConcurrentObserver.swift index 028a4441f..57728ea2f 100644 --- a/GRDB/ValueObservation/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/ValueConcurrentObserver.swift @@ -250,6 +250,12 @@ extension ValueConcurrentObserver { // transaction to complete. // // Fetch value & tracked region in a synchronous way. + // + // TODO: we currently perform the initial read from a snapshot, 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. let initialSnapshot = try databaseAccess.dbPool.makeSnapshot() let (fetchedValue, initialRegion, initialWALSnapshot) = try initialSnapshot.read { db -> (Reducer.Fetched, DatabaseRegion, WALSnapshot?) in @@ -299,6 +305,12 @@ extension ValueConcurrentObserver { // for observing the database is to be able to fetch the initial value // without having to wait for an eventual long-running write // transaction to complete. + // + // TODO: we currently perform the initial read from a snapshot, 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. do { let initialSnapshot = try databaseAccess.dbPool.makeSnapshot() initialSnapshot.asyncRead { dbResult in From cc5196757ddb9fd2471bc487facc6fb334ce68ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 30 Jun 2022 19:22:23 +0200 Subject: [PATCH 3/5] Fix for Xcode 12.4 --- GRDB/Core/WALSnapshot.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index a6a9088da..6b2a2f62d 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -47,10 +47,10 @@ final class WALSnapshot { } #endif } - guard code == SQLITE_OK, let snapshot = snapshot else { + guard code == SQLITE_OK, let s = snapshot else { return nil } - self.snapshot = snapshot + self.snapshot = s } deinit { From b1b51c01f88adacc7daaf97cb56a01f9bdcfcf25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 30 Jun 2022 19:32:24 +0200 Subject: [PATCH 4/5] [skip-ci] Xcode drives me crazy --- .../xcschemes/GRDBDemoWatchOS.xcscheme | 25 +++++-------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme index 4fbad19f2..237e9f7b3 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme @@ -78,10 +78,8 @@ debugDocumentVersioning = "YES" debugServiceExtension = "internal" allowLocationSimulation = "YES"> - + - + - + - - - - - + From 0aa561e61cd5c10f554383c34b79eb0cacc1222d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 30 Jun 2022 19:32:35 +0200 Subject: [PATCH 5/5] [skip-ci] CHANGELOG --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9fbbca5cc..26960a101 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -92,6 +92,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## Next Version + +- **New**: [#1248](https://github.com/groue/GRDB.swift/pull/1248) by [@groue](https://github.com/groue): Avoid double notification of the initial value for ValueObservation on DatabasePool + + ## 5.25.0 Released June 11, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.24.1...v5.25.0)