diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 169eacab3..ee5cfb156 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -523,6 +523,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } } + 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 + } + // MARK: - Authorizer func withAuthorizer(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T { diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 75650ea0b..d46a01cc7 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -868,19 +868,55 @@ extension DatabasePool: DatabaseReader { if scheduler.immediateInitialValue() { do { - // Fetch the initial value - let initialValue = try unsafeReentrantRead(observer.fetchInitialValue) + // Grab a snapshot of the state of the database and perform + // the initial fetch. + var initialValue: Reducer.Value! + var initialSnapshot: UnsafeMutablePointer? + + try unsafeReentrantRead { db in + // Transaction is needed for snapshotting + if db.isInsideTransaction { + initialSnapshot = try? db.takeVersionSnapshot() + initialValue = try observer.fetchInitialValue(db) + } else { + try db.inTransaction(.deferred) { + initialSnapshot = try? db.takeVersionSnapshot() + initialValue = try observer.fetchInitialValue(db) + return .commit + } + } + } + onChange(initialValue) // Now wait for the writer _weakAsyncWriteWithoutTransaction { db in + defer { + if let initialSnapshot = initialSnapshot { + sqlite3_snapshot_free(initialSnapshot) + } + } + guard let db = db else { return } if observer.isCompleted { return } + do { - // Don't miss eventual changes between the - // initial fetch and the writer access. - if let value = try observer.fetchValue(db) { - observer.notifyChange(value) + // Transaction is needed for snapshotting + try db.inTransaction(.deferred) { + var fetchNeeded = true + if let initialSnapshot = initialSnapshot { + do { + fetchNeeded = try db.wasChanged(since: initialSnapshot) + } catch { + } + } + + // Don't miss eventual changes between the + // initial fetch and the writer access. + if fetchNeeded, let value = try observer.fetchValue(db) { + observer.notifyChange(value) + } + return .commit } // Now we can start observation @@ -898,18 +934,15 @@ extension DatabasePool: DatabaseReader { guard let dbResult = dbResult else { return } guard let self = self else { return } if observer.isCompleted { return } + do { let db = try dbResult.get() - // Grab a snaphot of the state of the database when we - // perform the initial fetch. - // - // Since not all SQLite versions support snapshotting, - // ignore errors. + // Grab a snapshot of the state of the database and perform + // the initial fetch. var initialSnapshot = try? db.takeVersionSnapshot() - - // Fetch the initial value let initialValue = try observer.fetchInitialValue(db) + observer.notifyChange(initialValue) // Now wait for the writer @@ -927,33 +960,23 @@ extension DatabasePool: DatabaseReader { // Transaction is needed for snapshotting try db.inTransaction(.deferred) { var fetchNeeded = true - if initialSnapshot != nil { - // Grab a snaphot of the current state of the - // database. If it did not change since - // initial snapshot, then we do not need to - // perform a second fetch. - if let secondSnapshot = try? db.takeVersionSnapshot() { - // Compare snapshots - let cmp = sqlite3_snapshot_cmp(initialSnapshot, secondSnapshot) - assert(cmp <= 0, "Unexpected snapshot ordering") - fetchNeeded = cmp < 0 - sqlite3_snapshot_free(secondSnapshot) + if let initialSnapshot = initialSnapshot { + do { + fetchNeeded = try db.wasChanged(since: initialSnapshot) + } catch { } - - // Early free before the above defer { } - sqlite3_snapshot_free(initialSnapshot) - initialSnapshot = nil } + // Don't miss eventual changes between the + // initial fetch and the writer access. if fetchNeeded, let value = try observer.fetchValue(db) { observer.notifyChange(value) } - - // Now we can start observation - db.add(transactionObserver: observer, extent: .observerLifetime) - return .commit } + + // Now we can start observation + db.add(transactionObserver: observer, extent: .observerLifetime) } catch { observer.notifyErrorAndComplete(error) } diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 44130bbab..47f43c207 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -99,7 +99,9 @@ class ValueObservationTests: GRDBTestCase { XCTAssertEqual(observer.observedRegion!.description, "t(id,name)") // view is NOT tracked } - func testDisallowedSnapshotOptimization() throws { + // MARK: - Snapshot Optimization + + func testDisallowedSnapshotOptimizationWithAsyncScheduler() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") @@ -127,6 +129,7 @@ class ValueObservationTests: GRDBTestCase { 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) @@ -138,7 +141,47 @@ class ValueObservationTests: GRDBTestCase { } } - func testAllowedSnapshotOptimization() throws { + func testDisallowedSnapshotOptimizationWithImmediateScheduler() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + } + + // Force DatabasePool to perform two initial fetches, because between + // its first read access, and its write access that installs the + // transaction observer, some write did happen. + var needsChange = true + let observation = ValueObservation.tracking { db -> Int in + if needsChange { + needsChange = false + try dbPool.write { db in + try db.execute(sql: """ + INSERT INTO t DEFAULT VALUES; + DELETE FROM t; + """) + } + } + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")! + } + + 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: 1, handler: nil) + XCTAssertEqual(observedCounts, [0, 0]) + } + } + + func testAllowedSnapshotOptimizationWithAsyncScheduler() throws { try XCTSkipUnless(Database.sqliteCompileOptions.contains("ENABLE_SNAPSHOT"), "Snapshots not enabled") let dbPool = try makeDatabasePool() @@ -169,6 +212,50 @@ class ValueObservationTests: GRDBTestCase { 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]) + } + } + + func testAllowedSnapshotOptimizationWithImmediateScheduler() throws { + try XCTSkipUnless(Database.sqliteCompileOptions.contains("ENABLE_SNAPSHOT"), "Snapshots not enabled") + + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + } + + // Allow pool to perform a single initial fetch, because between + // its first read access, and its write access that installs the + // transaction observer, no write did happen. + var needsChange = true + let observation = ValueObservation.tracking { db -> Int in + if needsChange { + needsChange = false + DispatchQueue.main.asyncAfter(deadline: .now() + 1) { + try! dbPool.write { db in + try db.execute(sql: """ + INSERT INTO t DEFAULT VALUES; + """) + } + } + } + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")! + } + + 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)