From f2c3c213cc25ffd539dbf5caca3cda185c4e0605 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 28 Oct 2018 17:04:36 +0100 Subject: [PATCH] Read-only observation is enforced. When not read-only, savepoint is enforced. --- GRDB/Core/DatabaseWriter.swift | 41 +++++- GRDB/Core/ValueObservation.swift | 41 ++---- .../ValueObservationReadonlyTests.swift | 105 +++++++++++++ .../ValueObservationReducerTests.swift | 138 +++++++++--------- 4 files changed, 221 insertions(+), 104 deletions(-) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 2b9875456..68506aa55 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -225,7 +225,18 @@ extension DatabaseWriter { var reducer = observation.reducer switch observation.scheduling { case .mainQueue: - if let value = try reducer.value(reducer.fetch(db)) { + // fetch + var fetchedValue: Reducer.Fetched! + if observation.isReadOnly { + fetchedValue = try db.readOnly { try reducer.fetch(db) } + } else { + try db.inSavepoint { + fetchedValue = try reducer.fetch(db) + return .commit + } + } + // reduce + if let value = reducer.value(fetchedValue) { if calledOnMainQueue { mainQueueValue = value } else { @@ -233,8 +244,21 @@ extension DatabaseWriter { } } case let .onQueue(queue, startImmediately: startImmediately): - if startImmediately, let value = try reducer.value(reducer.fetch(db)) { - queue.async { onChange(value) } + if startImmediately { + // fetch + var fetchedValue: Reducer.Fetched! + if observation.isReadOnly { + fetchedValue = try db.readOnly { try reducer.fetch(db) } + } else { + try db.inSavepoint { + fetchedValue = try reducer.fetch(db) + return .commit + } + } + // reduce + if let value = reducer.value(fetchedValue) { + queue.async { onChange(value) } + } } } @@ -242,7 +266,7 @@ extension DatabaseWriter { // The technique to fetch a fresh value after database has changed // depends on the observation.readonly flag: let fetch: (Database, Reducer) -> Future - if observation.readonly { + if observation.isReadOnly { fetch = { [unowned self] (_, reducer) in // Concurrent fetch self.concurrentRead { db in try reducer.fetch(db) } @@ -250,7 +274,14 @@ extension DatabaseWriter { } else { fetch = { (db, reducer) in // Synchronous fetch - Future(Result { try reducer.fetch(db) }) + Future(Result { + var fetchedValue: Reducer.Fetched! + try db.inTransaction { + fetchedValue = try reducer.fetch(db) + return .commit + } + return fetchedValue + }) } } let valueObserver = try ValueObserver( diff --git a/GRDB/Core/ValueObservation.swift b/GRDB/Core/ValueObservation.swift index a5e4fc2aa..8b490fa9a 100644 --- a/GRDB/Core/ValueObservation.swift +++ b/GRDB/Core/ValueObservation.swift @@ -283,13 +283,13 @@ public struct ValueObservation { /// each database change, and also when the observatioin starts, depending /// on the *initialDispatch* property. /// - /// When this closure needs to write in the database, set the *readonly* + /// When this closure needs to write in the database, set the *isReadOnly* /// flag to false. var reducer: Reducer /// Default is true. Set this property to false when the *fetch* closure /// requires write access, and should be executed inside a savepoint. - public var readonly: Bool = true + public var isReadOnly: Bool = true /// The extent of the database observation. The default is /// `.observerLifetime`: once started, the observation lasts until the @@ -392,18 +392,10 @@ public struct ValueObservation { reducer: Reducer) -> ValueObservation { - func region(_ db: Database) throws -> DatabaseRegion { - return try regions.reduce(into: DatabaseRegion()) { union, region in - try union.formUnion(region.databaseRegion(db)) - } - } - - return ValueObservation(observing: region, reducer: reducer) + return ValueObservation(observing: union(regions), reducer: reducer) } } -// MARK: - DatabaseRegionConvertible Observation - extension ValueObservation where Reducer == Void { /// Creates a ValueObservation which observes *regions*, and notifies the /// values returned by the *fetch* closure whenever one of the observed @@ -437,14 +429,8 @@ extension ValueObservation where Reducer == Void { fetch: @escaping (Database) throws -> Value) -> ValueObservation> { - func region(_ db: Database) throws -> DatabaseRegion { - return try regions.reduce(into: DatabaseRegion()) { union, region in - try union.formUnion(region.databaseRegion(db)) - } - } - return ValueObservation>( - observing: region, + observing: union(regions), reducer: ValueReducers.Raw(fetch)) } @@ -481,19 +467,22 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> where Value: Equatable { - func region(_ db: Database) throws -> DatabaseRegion { - return try regions.reduce(into: DatabaseRegion()) { union, region in - try union.formUnion(region.databaseRegion(db)) - } - } - return ValueObservation>( - observing: region, + observing: union(regions), reducer: ValueReducers.Unique(fetch)) } } -// MARK: - FetchRequest Observation +private func union(_ regions: [DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { + return { db in + try regions.reduce(into: DatabaseRegion()) { union, region in + try union.formUnion(region.databaseRegion(db)) + } + } +} + + +// MARK: - Count Observation extension ValueObservation where Reducer == Void { /// Creates a ValueObservation which observes *request*, and notifies a diff --git a/Tests/GRDBTests/ValueObservationReadonlyTests.swift b/Tests/GRDBTests/ValueObservationReadonlyTests.swift index 624fef9cd..384644843 100644 --- a/Tests/GRDBTests/ValueObservationReadonlyTests.swift +++ b/Tests/GRDBTests/ValueObservationReadonlyTests.swift @@ -13,4 +13,109 @@ import XCTest #endif class ValueObservationReadonlyTests: GRDBTestCase { + + func testReadOnlyObservation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + var observation = ValueObservation.observing(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + _ = try dbQueue.add(observation: observation) { count in + notificationExpectation.fulfill() + counts.append(count) + } + + try dbQueue.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) + } + + func testWriteObservationFailsByDefault() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + let observation = ValueObservation.observing(DatabaseRegion.fullDatabase, fetch: { db -> Int in + try db.execute("INSERT INTO t DEFAULT VALUES") + return 0 + }) + + do { + _ = try dbQueue.add( + observation: observation, + onError: { _ in fatalError() }, + onChange: { _ in fatalError() }) + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_READONLY) + XCTAssertEqual(error.message, "attempt to write a readonly database") + XCTAssertEqual(error.sql!, "INSERT INTO t DEFAULT VALUES") + XCTAssertEqual(error.description, "SQLite error 8 with statement `INSERT INTO t DEFAULT VALUES`: attempt to write a readonly database") + } + } + + func testWriteObservation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + var observation = ValueObservation.observing(DatabaseRegion.fullDatabase, fetch: { db -> Int in + try db.execute("CREATE TEMPORARY TABLE temp AS SELECT * FROM t") + let result = try Int.fetchOne(db, "SELECT COUNT(*) FROM temp")! + try db.execute("DROP TABLE temp") + return result + }) + observation.extent = .databaseLifetime + observation.isReadOnly = false + _ = try dbQueue.add(observation: observation) { count in + notificationExpectation.fulfill() + counts.append(count) + } + + try dbQueue.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) + } + + func testWriteObservationIsWrappedInSavepoint() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + } + + struct TestError: Error { } + var observation = ValueObservation.observing(DatabaseRegion.fullDatabase, fetch: { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + throw TestError() + }) + observation.isReadOnly = false + + do { + _ = try dbQueue.add( + observation: observation, + onError: { _ in fatalError() }, + onChange: { _ in fatalError() }) + XCTFail("Expected error") + } catch is TestError { + } + + let count = try dbQueue.read { try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! } + XCTAssertEqual(count, 0) + } } diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index 784d53e34..46f7055d0 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -48,10 +48,11 @@ class ValueObservationReducerTests: GRDBTestCase { // Create an observation let request = SQLRequest("SELECT * FROM t") - let observation = ValueObservation.observing(request, reducer: reducer) + var observation = ValueObservation.observing(request, reducer: reducer) + observation.extent = .databaseLifetime - // Start observation with default configuration - let observer = try dbQueue.add( + // Start observation + _ = try dbQueue.add( observation: observation, onError: { errors.append($0) @@ -62,57 +63,53 @@ class ValueObservationReducerTests: GRDBTestCase { notificationExpectation.fulfill() }) - // Default config stops when observer is deallocated: keep it alive for - // the duration of the test: - try withExtendedLifetime(observer) { + + // Test that default config synchronously notifies initial value + XCTAssertEqual(fetchCount, 1) + XCTAssertEqual(reduceCount, 1) + XCTAssertEqual(errors.count, 0) + XCTAssertEqual(changes, ["0"]) + + try dbQueue.inDatabase { db in + // Test a 1st notified transaction + try db.inTransaction { + try db.execute("INSERT INTO t DEFAULT VALUES") + return .commit + } - // Test that default config synchronously notifies initial value - XCTAssertEqual(fetchCount, 1) - XCTAssertEqual(reduceCount, 1) - XCTAssertEqual(errors.count, 0) - XCTAssertEqual(changes, ["0"]) + // Test an untracked transaction + try db.inTransaction { + try db.execute("CREATE TABLE ignored(a)") + return .commit + } - try dbQueue.inDatabase { db in - // Test a 1st notified transaction - try db.inTransaction { - try db.execute("INSERT INTO t DEFAULT VALUES") - return .commit - } - - // Test an untracked transaction - try db.inTransaction { - try db.execute("CREATE TABLE ignored(a)") - return .commit - } - - // Test a dropped transaction - dropNext = true - try db.inTransaction { - try db.execute("INSERT INTO t DEFAULT VALUES") - try db.execute("INSERT INTO t DEFAULT VALUES") - return .commit - } - - // Test a rollbacked transaction - try db.inTransaction { - try db.execute("INSERT INTO t DEFAULT VALUES") - return .rollback - } - - // Test a 2nd notified transaction - try db.inTransaction { - try db.execute("INSERT INTO t DEFAULT VALUES") - try db.execute("INSERT INTO t DEFAULT VALUES") - return .commit - } - } + // Test a dropped transaction + dropNext = true + try db.inTransaction { + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + return .commit + } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(fetchCount, 4) - XCTAssertEqual(reduceCount, 4) - XCTAssertEqual(errors.count, 0) - XCTAssertEqual(changes, ["0", "1", "5"]) + // Test a rollbacked transaction + try db.inTransaction { + try db.execute("INSERT INTO t DEFAULT VALUES") + return .rollback + } + + // Test a 2nd notified transaction + try db.inTransaction { + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + return .commit + } } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(fetchCount, 4) + XCTAssertEqual(reduceCount, 4) + XCTAssertEqual(errors.count, 0) + XCTAssertEqual(changes, ["0", "1", "5"]) } func testInitialError() throws { @@ -124,7 +121,7 @@ class ValueObservationReducerTests: GRDBTestCase { // Create an observation let observation = ValueObservation.observing(DatabaseRegion.fullDatabase, reducer: reducer) - // Start observation with default configuration + // Start observation do { let dbQueue = try makeDatabaseQueue() _ = try dbQueue.add( @@ -133,8 +130,6 @@ class ValueObservationReducerTests: GRDBTestCase { onChange: { _ in fatalError() }) XCTFail("Expected error") } catch is TestError { - } catch { - XCTFail("Unexpected error") } } @@ -162,10 +157,11 @@ class ValueObservationReducerTests: GRDBTestCase { value: { $0 }) // Create an observation - let observation = ValueObservation.observing(DatabaseRegion.fullDatabase, reducer: reducer) - - // Start observation with default configuration - let observer = try dbQueue.add( + var observation = ValueObservation.observing(DatabaseRegion.fullDatabase, reducer: reducer) + observation.extent = .databaseLifetime + + // Start observation + _ = try dbQueue.add( observation: observation, onError: { errors.append($0) @@ -176,22 +172,18 @@ class ValueObservationReducerTests: GRDBTestCase { notificationExpectation.fulfill() }) - // Default config stops when observer is deallocated: keep it alive for - // the duration of the test: - try withExtendedLifetime(observer) { - struct TestError: Error { } - nextError = TestError() - try dbQueue.write { db in - try db.execute("INSERT INTO t DEFAULT VALUES") - } - - try dbQueue.write { db in - try db.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errors.count, 1) - XCTAssertEqual(changes.count, 2) + struct TestError: Error { } + nextError = TestError() + try dbQueue.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") } + + try dbQueue.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(errors.count, 1) + XCTAssertEqual(changes.count, 2) } }