From dd76cdffec4634ec6b39f333cb80e976b9eabe44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 20 Jun 2020 19:57:51 +0200 Subject: [PATCH 01/14] ValueObservation.handleEvents --- GRDB.xcodeproj/project.pbxproj | 10 +++ GRDB/Core/DatabasePool.swift | 50 ++++------- GRDB/Core/DatabaseQueue.swift | 16 +--- GRDB/Core/DatabaseReader.swift | 30 ++----- GRDB/Core/DatabaseSnapshot.swift | 10 +-- GRDB/Core/DatabaseWriter.swift | 31 +++---- GRDB/Utils/Utils.swift | 36 ++++++++ GRDB/ValueObservation/ValueObservation.swift | 83 ++++++++++++++++++- GRDB/ValueObservation/ValueObserver.swift | 63 ++++++++++---- .../ValueObservation/ValueReducer/Trace.swift | 19 +++++ GRDBCustom.xcodeproj/project.pbxproj | 6 ++ ...ValueObservationRegionRecordingTests.swift | 48 ++++++----- Tests/GRDBTests/ValueObservationTests.swift | 19 +++-- 13 files changed, 281 insertions(+), 140 deletions(-) create mode 100644 GRDB/ValueObservation/ValueReducer/Trace.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index fddc1c8fb..80c2ebee0 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -166,6 +166,10 @@ 563B071621862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */; }; 563B071821862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; 563B071921862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; + 563B8F92249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; }; + 563B8F93249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; }; + 563B8F94249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; }; + 563B8F95249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; }; 563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; }; 563C67B424628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; }; 563C67B524628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; }; @@ -1245,6 +1249,7 @@ 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = ""; }; 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; + 563B8F91249E6171007A48C9 /* Trace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = ""; }; 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = ""; }; 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; 563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; @@ -2209,6 +2214,7 @@ 56AACAA722ACED7100A40F2A /* Fetch.swift */, 5613ED3421A95A5C00DC7A68 /* Map.swift */, 564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */, + 563B8F91249E6171007A48C9 /* Trace.swift */, 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */, ); path = ValueReducer; @@ -2809,6 +2815,7 @@ 5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 5653EC142098738B00F46237 /* SQLGenerationContext.swift in Sources */, 56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, + 563B8F94249E6171007A48C9 /* Trace.swift in Sources */, 568D13212207213F00674B58 /* SQLQueryGenerator.swift in Sources */, 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */, 5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, @@ -2976,6 +2983,7 @@ 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, 564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, + 563B8F93249E6171007A48C9 /* Trace.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, 56E9FACC221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */, 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, @@ -3522,6 +3530,7 @@ AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */, AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */, AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */, + 563B8F95249E6171007A48C9 /* Trace.swift in Sources */, AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */, AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */, AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */, @@ -3860,6 +3869,7 @@ 5674A6FB1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5653EB0620944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */, 56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */, + 563B8F92249E6171007A48C9 /* Trace.swift in Sources */, 5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */, diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index d967d1f7e..b0849fb3c 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -808,33 +808,19 @@ extension DatabasePool: DatabaseReader { /// :nodoc: public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, - onError: @escaping (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) + scheduling scheduler: ValueObservationScheduler) -> DatabaseCancellable { if configuration.readonly { - return _addReadOnly( - observation: observation, - scheduling: scheduler, - onError: onError, - onChange: onChange) + return _addReadOnly(observation: observation, scheduling: scheduler) } if observation.requiresWriteAccess { - let observer = _addWriteOnly( - observation: observation, - scheduling: scheduler, - onError: onError, - onChange: onChange) + let observer = _addWriteOnly( observation: observation, scheduling: scheduler) return AnyDatabaseCancellable(cancel: observer.cancel) } - let observer = _addConcurrent( - observation: observation, - scheduling: scheduler, - onError: onError, - onChange: onChange) + let observer = _addConcurrent( observation: observation, scheduling: scheduler) return AnyDatabaseCancellable(cancel: observer.cancel) } @@ -842,9 +828,7 @@ extension DatabasePool: DatabaseReader { /// the writer. private func _addConcurrent( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, - onError: @escaping (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) + scheduling scheduler: ValueObservationScheduler) -> ValueObserver // For testability { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") @@ -853,14 +837,11 @@ extension DatabasePool: DatabaseReader { let reduceQueueLabel = configuration.identifier( defaultLabel: "GRDB", purpose: "ValueObservation") - let observer = ValueObserver( - requiresWriteAccess: observation.requiresWriteAccess, + let observer = ValueObserver( + observation: observation, writer: self, - reducer: observation.makeReducer(), - scheduling: scheduler, - reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel), - onError: onError, - onChange: onChange) + scheduler: scheduler, + reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel)) // Starting a concurrent observation means that we'll fetch the initial // value right away, without waiting for an access to the writer queue, @@ -901,11 +882,11 @@ extension DatabasePool: DatabaseReader { do { let initialSnapshot = try makeSnapshot() let initialValue = try initialSnapshot.read(observer.fetchInitialValue) - onChange(initialValue) + observation.events.onValue?(initialValue) add(observer: observer, from: initialSnapshot) } catch { - observer.cancel() - onError(error) + observer.complete() + observation.events.onError?(error) } } else { let label = configuration.identifier( @@ -963,8 +944,11 @@ extension DatabasePool: DatabaseReader { } } - if fetchNeeded, let value = try observer.fetchValue(db) { - observer.notifyChange(value) + if fetchNeeded { + observer.events.onDatabaseChange?() + if let value = try observer.fetchValue(db) { + observer.notifyChange(value) + } } return .commit } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 857c5d1e4..f256b1384 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -475,24 +475,14 @@ extension DatabaseQueue { /// :nodoc: public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, - onError: @escaping (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) + scheduling scheduler: ValueObservationScheduler) -> DatabaseCancellable { if configuration.readonly { - return _addReadOnly( - observation: observation, - scheduling: scheduler, - onError: onError, - onChange: onChange) + return _addReadOnly(observation: observation, scheduling: scheduler) } - let observer = _addWriteOnly( - observation: observation, - scheduling: scheduler, - onError: onError, - onChange: onChange) + let observer = _addWriteOnly(observation: observation, scheduling: scheduler) return AnyDatabaseCancellable(cancel: observer.cancel) } } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 58f079d11..5502801ab 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -246,17 +246,12 @@ public protocol DatabaseReader: AnyObject { /// method instead. /// /// - parameter observation: the stared observation - /// - parameter onError: a closure that is provided by eventual errors that happen - /// during observation - /// - parameter onChange: a closure that is provided fresh values /// - returns: a TransactionObserver /// /// :nodoc: func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, - onError: @escaping (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) + scheduling scheduler: ValueObservationScheduler) -> DatabaseCancellable } @@ -300,16 +295,15 @@ extension DatabaseReader { /// initial value. func _addReadOnly( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, - onError: @escaping (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) + scheduling scheduler: ValueObservationScheduler) -> DatabaseCancellable { if scheduler.immediateInitialValue() { do { - try onChange(unsafeReentrantRead(observation.fetchValue)) + let value = try unsafeReentrantRead(observation.fetchValue) + observation.events.onValue?(value) } catch { - onError(error) + observation.events.onError?(error) } return AnyDatabaseCancellable(cancel: { }) } else { @@ -327,9 +321,9 @@ extension DatabaseReader { scheduler.schedule { guard !isCancelled else { return } do { - try onChange(result.get()) + try observation.events.onValue?(result.get()) } catch { - onError(error) + observation.events.onError?(error) } } } @@ -418,15 +412,9 @@ public final class AnyDatabaseReader: DatabaseReader { /// :nodoc: public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, - onError: @escaping (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) + scheduling scheduler: ValueObservationScheduler) -> DatabaseCancellable { - base._add( - observation: observation, - scheduling: scheduler, - onError: onError, - onChange: onChange) + base._add(observation: observation, scheduling: scheduler) } } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 636d9df75..8e1ef093d 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -131,15 +131,9 @@ extension DatabaseSnapshot { /// :nodoc: public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, - onError: @escaping (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) + scheduling scheduler: ValueObservationScheduler) -> DatabaseCancellable { - _addReadOnly( - observation: observation, - scheduling: scheduler, - onError: onError, - onChange: onChange) + _addReadOnly(observation: observation, scheduling: scheduler) } } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 272201a45..61cdf6b4b 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -311,9 +311,7 @@ extension DatabaseWriter { /// A write-only observation only uses the serialized writer func _addWriteOnly( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, - onError: @escaping (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) + scheduling scheduler: ValueObservationScheduler) -> ValueObserver // For testability { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") @@ -321,14 +319,11 @@ extension DatabaseWriter { let reduceQueueLabel = configuration.identifier( defaultLabel: "GRDB", purpose: "ValueObservation") - let observer = ValueObserver( - requiresWriteAccess: observation.requiresWriteAccess, + let observer = ValueObserver( + observation: observation, writer: self, - reducer: observation.makeReducer(), - scheduling: scheduler, - reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel), - onError: onError, - onChange: onChange) + scheduler: scheduler, + reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel)) if scheduler.immediateInitialValue() { do { @@ -337,10 +332,10 @@ extension DatabaseWriter { db.add(transactionObserver: observer, extent: .observerLifetime) return initialValue } - onChange(initialValue) + observation.events.onValue?(initialValue) } catch { - observer.cancel() - onError(error) + observer.complete() + observation.events.onError?(error) } } else { _weakAsyncWriteWithoutTransaction { db in @@ -529,15 +524,9 @@ public final class AnyDatabaseWriter: DatabaseWriter { /// :nodoc: public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, - onError: @escaping (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) + scheduling scheduler: ValueObservationScheduler) -> DatabaseCancellable { - base._add( - observation: observation, - scheduling: scheduler, - onError: onError, - onChange: onChange) + base._add(observation: observation, scheduling: scheduler) } } diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 383db5bc5..20acae90f 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -134,3 +134,39 @@ func throwingFirstError(execute: () throws -> T, finally: () throws -> Void) } return result! } + +struct PrintOutputStream: TextOutputStream { + func write(_ string: String) { + Swift.print(string) + } +} + +func appendHandler(_ rhs: (() -> Void)?) -> ((() -> Void)?) -> (() -> Void)? { + guard let rhs = rhs else { + return { $0 } + } + return { lhs in + guard let lhs = lhs else { + return rhs + } + return { + lhs() + rhs() + } + } +} + +func appendHandler(_ rhs: ((T) -> Void)?) -> (((T) -> Void)?) -> ((T) -> Void)? { + guard let rhs = rhs else { + return { $0 } + } + return { lhs in + guard let lhs = lhs else { + return rhs + } + return { + lhs($0) + rhs($0) + } + } +} diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 226045280..e70adff44 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -16,6 +16,8 @@ import Dispatch /// print("Players have changed.") /// }) public struct ValueObservation { + var events = ValueObservationEvents() + /// The reducer is created when observation starts, and is triggered upon /// each database change. var makeReducer: () -> Reducer @@ -37,7 +39,16 @@ public struct ValueObservation { } } -extension ValueObservation { +struct ValueObservationEvents: Refinable { + var onStart: (() -> Void)? + var onTrackedRegion: ((DatabaseRegion) -> Void)? + var onDatabaseChange: (() -> Void)? + var onValue: ((Value) -> Void)? + var onError: ((Error) -> Void)? + var onCancel: (() -> Void)? +} + +extension ValueObservation: Refinable { // MARK: - Starting Observation @@ -88,7 +99,75 @@ extension ValueObservation { onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable { - reader._add(observation: self, scheduling: scheduler, onError: onError, onChange: onChange) + let observation = map(\.events) { eventHandler in + eventHandler + .map(\.onValue, appendHandler(onChange)) + .map(\.onError, appendHandler(onError)) + } + observation.events.onStart?() + return reader._add(observation: observation, scheduling: scheduler) + } + + // MARK: - Debugging + + /// Performs the specified closures when ValueObservation events occur. + /// + /// - parameters: + /// - onStart: A closure that executes when the observation starts. + /// Defaults to `nil`. + /// - onTrackedRegion: A closure that executes when the observation + /// start tracking a database region. Defaults to `nil`. + /// - onDatabaseChange: A closure that executes after the observation + /// was impacted by a database change. Defaults to `nil`. + /// - onFetch: A closure that executes when the observed value is + /// fetched. Defaults to `nil`. + /// - onValue: A closure that executes when the observation notifies a + /// fresh value. Defaults to `nil`. + /// - onError: A closure that executes when the observation fails. + /// Defaults to `nil`. + /// - onCancel: A closure that executes when the observation is + /// cancelled. Defaults to `nil`. + /// - returns: A `ValueObservation` that performs the specified closures + /// when ValueObservation events occur. + public func handleEvents( + onStart: (() -> Void)? = nil, + onTrackedRegion: ((DatabaseRegion) -> Void)? = nil, + onDatabaseChange: (() -> Void)? = nil, + onFetch: (() -> Void)? = nil, + onValue: ((Reducer.Value) -> Void)? = nil, + onError: ((Error) -> Void)? = nil, + onCancel: (() -> Void)? = nil) + -> ValueObservation> + { + self + .mapReducer { ValueReducers.Trace(base: $0, onFetch: onFetch ?? { }) } + .map(\.events) { eventHandler in + eventHandler + .map(\.onStart, appendHandler(onStart)) + .map(\.onTrackedRegion, appendHandler(onTrackedRegion)) + .map(\.onDatabaseChange, appendHandler(onDatabaseChange)) + .map(\.onValue, appendHandler(onValue)) + .map(\.onError, appendHandler(onError)) + .map(\.onCancel, appendHandler(onCancel)) + } + } + + /// Prints log messages for all ValueObservation events. + public func print( + _ prefix: String = "", + to stream: TextOutputStream? = nil) + -> ValueObservation> + { + let prefix = prefix.isEmpty ? "" : "\(prefix): " + var stream = stream ?? PrintOutputStream() + return handleEvents( + onStart: { stream.write("\(prefix)start") }, + onTrackedRegion: { stream.write("\(prefix)tracked region: \($0)") }, + onDatabaseChange: { stream.write("\(prefix)database did change") }, + onFetch: { stream.write("\(prefix)fetch") }, + onValue: { stream.write("\(prefix)value: \($0)") }, + onError: { stream.write("\(prefix)error: \($0)") }, + onCancel: { stream.write("\(prefix)cancel") }) } // MARK: - Fetching Values diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index 9a6be5a7d..7a9045cb7 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -3,35 +3,57 @@ import Foundation /// Support for ValueObservation. /// See DatabaseWriter.add(observation:onError:onChange:) final class ValueObserver { - private(set) var observedRegion: DatabaseRegion? // internal for testability + private(set) var observedRegion: DatabaseRegion? { // internal for testability + didSet { + if + let onTrackedRegion = events.onTrackedRegion, + let region = observedRegion, + region != oldValue + { + onTrackedRegion(region) + } + } + } var isCompleted: Bool { synchronized { _isCompleted } } + let events: ValueObservationEvents private var _isCompleted = false private var reducer: Reducer private let requiresWriteAccess: Bool private weak var writer: DatabaseWriter? private let scheduler: ValueObservationScheduler private let reduceQueue: DispatchQueue - private let onError: (Error) -> Void - private let onChange: (Reducer.Value) -> Void private var isChanged = false private var lock = NSRecursiveLock() // protects _isCompleted init( + events: ValueObservationEvents, + reducer: Reducer, requiresWriteAccess: Bool, writer: DatabaseWriter, - reducer: Reducer, - scheduling scheduler: ValueObservationScheduler, - reduceQueue: DispatchQueue, - onError: @escaping (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) + scheduler: ValueObservationScheduler, + reduceQueue: DispatchQueue) { - self.writer = writer + self.events = events self.reducer = reducer self.requiresWriteAccess = requiresWriteAccess + self.writer = writer self.scheduler = scheduler self.reduceQueue = reduceQueue - self.onError = onError - self.onChange = onChange + } + + convenience init( + observation: ValueObservation, + writer: DatabaseWriter, + scheduler: ValueObservationScheduler, + reduceQueue: DispatchQueue) + { + self.init( + events: observation.events, + reducer: observation.makeReducer(), + requiresWriteAccess: observation.requiresWriteAccess, + writer: writer, + scheduler: scheduler, + reduceQueue: reduceQueue) } } @@ -60,6 +82,8 @@ extension ValueObserver: TransactionObserver { isChanged = false if isCompleted { return } + events.onDatabaseChange?() + // 1. Fetch let fetchedValue: DatabaseFuture if requiresWriteAccess || needsRecordingSelectedRegion { @@ -119,19 +143,26 @@ extension ValueObserver { } } - func cancel() { + func complete() { synchronized { - // no harm if already completed _isCompleted = true writer?.remove(transactionObserver: self) } } + func cancel() { + synchronized { + if _isCompleted { return } + events.onCancel?() + complete() + } + } + func notifyChange(_ value: Reducer.Value) { if isCompleted { return } scheduler.schedule { if self.isCompleted { return } - self.onChange(value) + self.events.onValue?(value) } } @@ -142,12 +173,12 @@ extension ValueObserver { if self._isCompleted { return false } else { - self._isCompleted = true + self.complete() return true } } if shouldNotify { - self.onError(error) + self.events.onError?(error) } } } diff --git a/GRDB/ValueObservation/ValueReducer/Trace.swift b/GRDB/ValueObservation/ValueReducer/Trace.swift new file mode 100644 index 000000000..d46334f62 --- /dev/null +++ b/GRDB/ValueObservation/ValueReducer/Trace.swift @@ -0,0 +1,19 @@ +extension ValueReducers { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// :nodoc: + public struct Trace: _ValueReducer { + var base: Base + let onFetch: () -> Void + public var isSelectedRegionDeterministic: Bool { base.isSelectedRegionDeterministic } + + public func fetch(_ db: Database) throws -> Base.Fetched { + onFetch() + return try base.fetch(db) + } + + public mutating func value(_ fetched: Base.Fetched) -> Base.Value? { + base.value(fetched) + } + } +} diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index b9b54b162..7c90e2b5d 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -87,6 +87,8 @@ 563B071321862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */; }; 563B071B21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; 563B071C21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; + 563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; }; + 563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; }; 563C67B824628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; }; 563C67B924628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; }; 563DE4F8231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */; }; @@ -782,6 +784,7 @@ 563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = ""; }; 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; + 563B8F99249E74E5007A48C9 /* Trace.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = ""; }; 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = ""; }; 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; @@ -1711,6 +1714,7 @@ 56C0538A22ACEECD0029D27D /* Fetch.swift */, 56C0538E22ACEECD0029D27D /* Map.swift */, 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */, + 563B8F99249E74E5007A48C9 /* Trace.swift */, 56C0538C22ACEECD0029D27D /* ValueReducer.swift */, ); path = ValueReducer; @@ -2247,6 +2251,7 @@ 5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5656A8702295BD56001FF3FF /* Association.swift in Sources */, + 563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */, 5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */, 5656A88C2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */, 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, @@ -2585,6 +2590,7 @@ 5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5656A86F2295BD56001FF3FF /* Association.swift in Sources */, + 563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */, 5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */, 5656A88B2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */, 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index bb12cec56..6593a82f2 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -135,20 +135,21 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 4 - let observation = ValueObservation.trackingVaryingRegion { db -> Int in - let table = try String.fetchOne(db, sql: "SELECT name FROM source")! - return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! - } + var regions: [DatabaseRegion] = [] + let observation = ValueObservation + .trackingVaryingRegion({ db -> Int in + let table = try String.fetchOne(db, sql: "SELECT name FROM source")! + return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! + }) + .handleEvents(onTrackedRegion: { regions.append($0) }) - let observer = dbQueue._addWriteOnly( - observation: observation, - scheduling: .immediate, + let observer = observation.start( + in: dbQueue, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - results.append(count) - notificationExpectation.fulfill() - }) - XCTAssertEqual(observer.observedRegion!.description, "a(value),source(name)") + results.append(count) + notificationExpectation.fulfill() + }) try withExtendedLifetime(observer) { try dbQueue.inDatabase { db in @@ -163,7 +164,9 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(results, [0, 1, 2, 3]) - XCTAssertEqual(observer.observedRegion!.description, "b(value),source(name)") + XCTAssertEqual(regions.map(\.description), [ + "a(value),source(name)", + "b(value),source(name)"]) } } @@ -183,13 +186,16 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 4 - let observation = ValueObservation.trackingVaryingRegion { db -> Int in - let table = try String.fetchOne(db, sql: "SELECT name FROM source")! - return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! - } + var regions: [DatabaseRegion] = [] + let observation = ValueObservation + .trackingVaryingRegion({ db -> Int in + let table = try String.fetchOne(db, sql: "SELECT name FROM source")! + return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! + }) + .handleEvents(onTrackedRegion: { regions.append($0) }) - let observer = dbQueue._addWriteOnly( - observation: observation, + let observer = observation.start( + in: dbQueue, scheduling: .async(onQueue: .main), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in @@ -197,8 +203,6 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { notificationExpectation.fulfill() }) - // Can't test observedRegion because it is defined asynchronously - try withExtendedLifetime(observer) { try dbQueue.inDatabase { db in try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 @@ -212,7 +216,9 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(results, [0, 1, 2, 3]) - XCTAssertEqual(observer.observedRegion!.description, "b(value),source(name)") + XCTAssertEqual(regions.map(\.description), [ + "a(value),source(name)", + "b(value),source(name)"]) } } } diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index f51a26416..0b75a7695 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -90,13 +90,22 @@ class ValueObservationTests: GRDBTestCase { // Test that view v is not included in the observed region. // This optimization helps observation of views that feed from a // single table. - let observation = ValueObservation.tracking(request.fetchAll) - let observer = dbQueue._addWriteOnly( - observation: observation, - scheduling: .immediate, // So that we can test the observedRegion + var region: DatabaseRegion? + let expectation = self.expectation(description: "") + let observation = ValueObservation + .tracking(request.fetchAll) + .handleEvents(onTrackedRegion: { + region = $0 + expectation.fulfill() + }) + let observer = observation.start( + in: dbQueue, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { _ in }) - XCTAssertEqual(observer.observedRegion!.description, "t(id,name)") // view is NOT tracked + withExtendedLifetime(observer) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(region!.description, "t(id,name)") // view is NOT tracked + } } // MARK: - Snapshot Optimization From 2c90820f0f36b73b4a73c129a9264adb6282a216 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 20 Jun 2020 20:15:07 +0200 Subject: [PATCH 02/14] ValueObservation.handleEvents and .print documentation --- GRDB/ValueObservation/ValueObservation.swift | 2 +- README.md | 52 ++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index e70adff44..21885129c 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -116,7 +116,7 @@ extension ValueObservation: Refinable { /// - onStart: A closure that executes when the observation starts. /// Defaults to `nil`. /// - onTrackedRegion: A closure that executes when the observation - /// start tracking a database region. Defaults to `nil`. + /// starts tracking a database region. Defaults to `nil`. /// - onDatabaseChange: A closure that executes after the observation /// was impacted by a database change. Defaults to `nil`. /// - onFetch: A closure that executes when the observed value is diff --git a/README.md b/README.md index b182a8258..3dd6ee799 100644 --- a/README.md +++ b/README.md @@ -5494,6 +5494,11 @@ let cancellable = observation.start( - [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) - [ValueObservation.requiresWriteAccess](#valueobservationrequireswriteaccess) +**Debugging Operators** + +- [ValueObservation.handleEvents](#valueobservationhandleevents) +- [ValueObservation.print](#valueobservationprint) + #### ValueObservation.map @@ -5567,6 +5572,53 @@ 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 ValueObseration: + +```swift +let observation = ValueObservation + .tracking { db in ... } + .handleEvents( + onStart: { + // The observation starts + }, + onTrackedRegion: { databaseRegion in + // The observation starts tracking a database region + }, + onDatabaseChange: { + // The observation was impacted by a database change. + }, + onFetch: { + // The observation performs a database fetch. + }, + onValue: { value in + // The observation notifies a fresh value. + }, + onError: { error in + // The observation completes with an error. + }, + onCancel: { + // The observation is cancelled. + }) +``` + +See also [ValueObservation.print](#valueobservationprint). + + +#### ValueObservation.print + +The `print` operator logs messages for all ValueObservation events. + +```swift +let observation = ValueObservation + .tracking(Player.fetchAll) + .print() +``` + +See also [ValueObservation.handleEvents](#valueobservationhandleevents). + + ### ValueObservation Performance This chapter further describes runtime aspects of ValueObservation, and provides some optimization tips for demanding applications. From 7e7c232fc09ff4d2f499fa67e4ecd54b9fa91edc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 20 Jun 2020 22:09:28 +0200 Subject: [PATCH 03/14] Tests for ValueObservation.print() --- GRDB.xcodeproj/project.pbxproj | 8 + GRDBCustom.xcodeproj/project.pbxproj | 6 + README.md | 2 +- .../GRDBTests.xcodeproj/project.pbxproj | 10 +- .../GRDBTests.xcodeproj/project.pbxproj | 12 +- .../ValueObservationPrintTests.swift | 516 ++++++++++++++++++ 6 files changed, 548 insertions(+), 6 deletions(-) create mode 100644 Tests/GRDBTests/ValueObservationPrintTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 80c2ebee0..cdb1b07cf 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -170,6 +170,9 @@ 563B8F93249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; }; 563B8F94249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; }; 563B8F95249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; }; + 563B8FA1249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */; }; + 563B8FA2249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */; }; + 563B8FA3249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */; }; 563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; }; 563C67B424628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; }; 563C67B524628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; }; @@ -1250,6 +1253,7 @@ 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; 563B8F91249E6171007A48C9 /* Trace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = ""; }; + 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = ""; }; 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = ""; }; 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; 563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; @@ -1820,6 +1824,7 @@ 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */, 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */, + 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */, 5656A7F822946B33001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */, 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */, 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */, @@ -3147,6 +3152,7 @@ 56915783231BF28B00E1D237 /* PoolTests.swift in Sources */, 56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, + 563B8FA2249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */, 56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, @@ -3355,6 +3361,7 @@ 56915782231BF28B00E1D237 /* PoolTests.swift in Sources */, 56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */, 5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, + 563B8FA1249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */, 56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */, 5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, @@ -3694,6 +3701,7 @@ 56915784231BF28B00E1D237 /* PoolTests.swift in Sources */, AAA4DD88230F262000C74B15 /* DatabaseValueConvertibleFetchTests.swift in Sources */, AAA4DD89230F262000C74B15 /* DatabaseDateEncodingStrategyTests.swift in Sources */, + 563B8FA3249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */, AAA4DD8A230F262000C74B15 /* RecordPrimaryKeyRowIDTests.swift in Sources */, AAA4DD8B230F262000C74B15 /* ForeignKeyInfoTests.swift in Sources */, AAA4DD8C230F262000C74B15 /* AssociationChainSQLTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 7c90e2b5d..a8d566fed 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -89,6 +89,8 @@ 563B071C21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; 563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; }; 563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; }; + 563B8F9E249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */; }; + 563B8F9F249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */; }; 563C67B824628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; }; 563C67B924628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; }; 563DE4F8231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */; }; @@ -785,6 +787,7 @@ 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; 563B8F99249E74E5007A48C9 /* Trace.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = ""; }; + 563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = ""; }; 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = ""; }; 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; @@ -1326,6 +1329,7 @@ 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */, 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */, + 563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */, 5656A7F422946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */, 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */, 56677C24241E6EA20050755D /* ValueObservationRecorder.swift */, @@ -2415,6 +2419,7 @@ 5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 56677C28241E6EA20050755D /* ValueObservationRecorder.swift in Sources */, + 563B8F9F249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */, 5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2754,6 +2759,7 @@ 5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 56677C27241E6EA20050755D /* ValueObservationRecorder.swift in Sources */, + 563B8F9E249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */, 5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */, diff --git a/README.md b/README.md index 3dd6ee799..046d85353 100644 --- a/README.md +++ b/README.md @@ -5612,7 +5612,7 @@ The `print` operator logs messages for all ValueObservation events. ```swift let observation = ValueObservation - .tracking(Player.fetchAll) + .tracking { db in ... } .print() ``` diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index a39754704..35545ee0b 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -23,6 +23,8 @@ 561CFAAF2376EFBE000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAAC2376EFBD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; 561CFAB02376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAAD2376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift */; }; 561CFAB12376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAAD2376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift */; }; + 563B8FA8249E8B14007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA7249E8B14007A48C9 /* ValueObservationPrintTests.swift */; }; + 563B8FA9249E8B14007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA7249E8B14007A48C9 /* ValueObservationPrintTests.swift */; }; 563DE4FB231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; }; 563DE4FC231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; }; 564A1FDE226B89E1001F64F1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F27226B89CE001F64F1 /* MutablePersistableRecordDeleteTests.swift */; }; @@ -417,6 +419,7 @@ 561CFA8223735091000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = ""; }; 561CFAAC2376EFBD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; }; 561CFAAD2376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; }; + 563B8FA7249E8B14007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = ""; }; 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; 563F4CB9242F801A0052E96C /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; 564A1F1D226B876D001F64F1 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -661,6 +664,8 @@ 564A1F1F226B876D001F64F1 /* GRDBTests */ = { isa = PBXGroup; children = ( + 564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */, + 564A1F6F226B89D6001F64F1 /* Betty.jpeg */, 564A1F90226B89D9001F64F1 /* AnyCursorTests.swift */, 564A1F60226B89D4001F64F1 /* AssociationAggregateTests.swift */, 564A1F35226B89CF001F64F1 /* AssociationBelongsToDecodableRecordTests.swift */, @@ -693,7 +698,6 @@ 560714EF227DD1810091BB10 /* AssociationPrefetchingSQLTests.swift */, 564A1F3E226B89D0001F64F1 /* AssociationRowScopeSearchTests.swift */, 564A1FCF226B89E0001F64F1 /* AssociationTableAliasTestsSQLTests.swift */, - 564A1F6F226B89D6001F64F1 /* Betty.jpeg */, 564A1F8A226B89D9001F64F1 /* CGFloatTests.swift */, 564A1F61226B89D4001F64F1 /* ColumnExpressionTests.swift */, 564A1FAC226B89DC001F64F1 /* ColumnInfoTests.swift */, @@ -786,7 +790,6 @@ 564A1FC4226B89DE001F64F1 /* FTS5TokenizerTests.swift */, 564A1F43226B89D0001F64F1 /* FTS5WrapperTokenizerTests.swift */, 564A1FD5226B89E0001F64F1 /* GRDBTestCase.swift */, - 564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */, 564A1F86226B89D8001F64F1 /* IndexInfoTests.swift */, 564A1FCD226B89DF001F64F1 /* JoinSupportTests.swift */, 564A1FB8226B89DD001F64F1 /* MapCursorTests.swift */, @@ -851,6 +854,7 @@ 564A1F6C226B89D5001F64F1 /* ValueObservationDatabaseValueConvertibleTests.swift */, 564A1FC6226B89DF001F64F1 /* ValueObservationFetchTests.swift */, 564A1F59226B89D3001F64F1 /* ValueObservationMapTests.swift */, + 563B8FA7249E8B14007A48C9 /* ValueObservationPrintTests.swift */, 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */, 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */, 56C8123924279584004FBBFF /* ValueObservationRecorder.swift */, @@ -1227,6 +1231,7 @@ 564A208A226B89E1001F64F1 /* MutablePersistableRecordChangesTests.swift in Sources */, 564A2092226B89E1001F64F1 /* DatabasePoolConcurrencyTests.swift in Sources */, 564A1FE0226B89E1001F64F1 /* RowCopiedFromStatementTests.swift in Sources */, + 563B8FA8249E8B14007A48C9 /* ValueObservationPrintTests.swift in Sources */, 564A2007226B89E1001F64F1 /* FoundationDataTests.swift in Sources */, 564A201A226B89E1001F64F1 /* FTS4TableBuilderTests.swift in Sources */, 564A2059226B89E1001F64F1 /* DatabaseValueConversionTests.swift in Sources */, @@ -1430,6 +1435,7 @@ 564A2127226B8E18001F64F1 /* MutablePersistableRecordChangesTests.swift in Sources */, 564A2128226B8E18001F64F1 /* DatabasePoolConcurrencyTests.swift in Sources */, 564A2129226B8E18001F64F1 /* RowCopiedFromStatementTests.swift in Sources */, + 563B8FA9249E8B14007A48C9 /* ValueObservationPrintTests.swift in Sources */, 564A212A226B8E18001F64F1 /* FoundationDataTests.swift in Sources */, 564A212B226B8E18001F64F1 /* FTS4TableBuilderTests.swift in Sources */, 564A212C226B8E18001F64F1 /* DatabaseValueConversionTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 5074166e3..0fe5f02ad 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -23,6 +23,8 @@ 561CFAA92376EFAD000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA62376EFAD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; 561CFAAA2376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA72376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift */; }; 561CFAAB2376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA72376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift */; }; + 563B8FA5249E8AF6007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA4249E8AF6007A48C9 /* ValueObservationPrintTests.swift */; }; + 563B8FA6249E8AF6007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA4249E8AF6007A48C9 /* ValueObservationPrintTests.swift */; }; 563DE4FE231A9239005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */; }; 563DE4FF231A9239005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */; }; 563F4CB7242F80030052E96C /* ValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB6242F80030052E96C /* ValueObservationTests.swift */; }; @@ -421,6 +423,7 @@ 561CFA7F2373507D000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = ""; }; 561CFAA62376EFAD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; }; 561CFAA72376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; }; + 563B8FA4249E8AF6007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = ""; }; 563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; 563F4CB6242F80030052E96C /* ValueObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationTests.swift; sourceTree = ""; }; 564A1F1D226B876D001F64F1 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -666,6 +669,9 @@ 564A1F1F226B876D001F64F1 /* GRDBTests */ = { isa = PBXGroup; children = ( + 564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */, + 564A1F6F226B89D6001F64F1 /* Betty.jpeg */, + 564A2158226C8F24001F64F1 /* db.SQLCipher3 */, 564A1F90226B89D9001F64F1 /* AnyCursorTests.swift */, 564A1F60226B89D4001F64F1 /* AssociationAggregateTests.swift */, 564A1F35226B89CF001F64F1 /* AssociationBelongsToDecodableRecordTests.swift */, @@ -698,7 +704,6 @@ 560714F2227DD1AD0091BB10 /* AssociationPrefetchingSQLTests.swift */, 564A1F3E226B89D0001F64F1 /* AssociationRowScopeSearchTests.swift */, 564A1FCF226B89E0001F64F1 /* AssociationTableAliasTestsSQLTests.swift */, - 564A1F6F226B89D6001F64F1 /* Betty.jpeg */, 564A1F8A226B89D9001F64F1 /* CGFloatTests.swift */, 564A1F61226B89D4001F64F1 /* ColumnExpressionTests.swift */, 564A1FAC226B89DC001F64F1 /* ColumnInfoTests.swift */, @@ -751,7 +756,6 @@ 564A1F45226B89D0001F64F1 /* DatabaseValueTests.swift */, 564A1FC0226B89DE001F64F1 /* DatabaseWriterTests.swift */, 564A1FCC226B89DF001F64F1 /* DataMemoryTests.swift */, - 564A2158226C8F24001F64F1 /* db.SQLCipher3 */, 564A1F4B226B89D1001F64F1 /* DerivableRequestTests.swift */, 564A1FBB226B89DD001F64F1 /* DropFirstCursorTests.swift */, 564A1F6D226B89D5001F64F1 /* DropWhileCursorTests.swift */, @@ -792,7 +796,6 @@ 564A1FC4226B89DE001F64F1 /* FTS5TokenizerTests.swift */, 564A1F43226B89D0001F64F1 /* FTS5WrapperTokenizerTests.swift */, 564A1FD5226B89E0001F64F1 /* GRDBTestCase.swift */, - 564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */, 564A1F86226B89D8001F64F1 /* IndexInfoTests.swift */, 564A1FCD226B89DF001F64F1 /* JoinSupportTests.swift */, 564A1FB8226B89DD001F64F1 /* MapCursorTests.swift */, @@ -857,6 +860,7 @@ 564A1F6C226B89D5001F64F1 /* ValueObservationDatabaseValueConvertibleTests.swift */, 564A1FC6226B89DF001F64F1 /* ValueObservationFetchTests.swift */, 564A1F59226B89D3001F64F1 /* ValueObservationMapTests.swift */, + 563B8FA4249E8AF6007A48C9 /* ValueObservationPrintTests.swift */, 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */, 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */, 56C8122F24279549004FBBFF /* ValueObservationRecorder.swift */, @@ -1092,6 +1096,7 @@ 564A2049226B89E1001F64F1 /* DatabaseQueueReadOnlyTests.swift in Sources */, 564A1FF0226B89E1001F64F1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 564A1FEA226B89E1001F64F1 /* AssociationChainRowScopesTests.swift in Sources */, + 563B8FA5249E8AF6007A48C9 /* ValueObservationPrintTests.swift in Sources */, 564A207D226B89E1001F64F1 /* ValueObservationFetchTests.swift in Sources */, 564A203C226B89E1001F64F1 /* ValueObservationReadonlyTests.swift in Sources */, 564A203B226B89E1001F64F1 /* ValueObservationCountTests.swift in Sources */, @@ -1296,6 +1301,7 @@ 564A20A4226B8E18001F64F1 /* DatabaseQueueReadOnlyTests.swift in Sources */, 564A20A5226B8E18001F64F1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 564A20A6226B8E18001F64F1 /* AssociationChainRowScopesTests.swift in Sources */, + 563B8FA6249E8AF6007A48C9 /* ValueObservationPrintTests.swift in Sources */, 564A20A8226B8E18001F64F1 /* ValueObservationFetchTests.swift in Sources */, 564A20A9226B8E18001F64F1 /* ValueObservationReadonlyTests.swift in Sources */, 564A20AA226B8E18001F64F1 /* ValueObservationCountTests.swift in Sources */, diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift new file mode 100644 index 000000000..9b4f323d0 --- /dev/null +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -0,0 +1,516 @@ +import XCTest +import Dispatch +@testable import GRDB + +class ValueObservationPrintTests: GRDBTestCase { + class TestStream: TextOutputStream { + @LockedBox var strings: [String] = [] + func write(_ string: String) { + strings.append(string) + } + } + + // MARK: - Readonly + + func test_readonly_success_asynchronousScheduling() throws { + let dbPool = try makeDatabasePool(filename: "test") + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") + } + + func test(_ dbReader: DatabaseReader) throws { + let logger = TestStream() + let observation = ValueObservation + .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .print(to: logger) + + let expectation = self.expectation(description: "") + let cancellable = observation.start( + in: dbReader, + scheduling: .async(onQueue: .main), + onError: { _ in }, + onChange: { _ in expectation.fulfill() }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger.strings, [ + "start", + "fetch", + "value: 0"]) + } + } + + var config = dbConfiguration! + config.readonly = true + try test(makeDatabaseQueue(filename: "test", configuration: config)) + try test(makeDatabasePool(filename: "test", configuration: config)) + try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) + } + + func test_readonly_success_immediateScheduling() throws { + let dbPool = try makeDatabasePool(filename: "test") + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") + } + + func test(_ dbReader: DatabaseReader) throws { + let logger = TestStream() + let observation = ValueObservation + .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .print(to: logger) + + let expectation = self.expectation(description: "") + let cancellable = observation.start( + in: dbReader, + scheduling: .immediate, + onError: { _ in }, + onChange: { _ in expectation.fulfill() }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger.strings, [ + "start", + "fetch", + "value: 0"]) + } + } + + var config = dbConfiguration! + config.readonly = true + try test(makeDatabaseQueue(filename: "test", configuration: config)) + try test(makeDatabasePool(filename: "test", configuration: config)) + try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) + } + + func test_readonly_failure_asynchronousScheduling() throws { + _ = try makeDatabasePool(filename: "test") + + func test(_ dbReader: DatabaseReader) throws { + struct TestError: Error { } + let logger = TestStream() + let observation = ValueObservation + .tracking { _ in throw TestError() } + .print(to: logger) + + let expectation = self.expectation(description: "") + let cancellable = observation.start( + in: dbReader, + scheduling: .async(onQueue: .main), + onError: { _ in expectation.fulfill() }, + onChange: { _ in }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger.strings, [ + "start", + "fetch", + "error: TestError()"]) + } + } + + var config = dbConfiguration! + config.readonly = true + try test(makeDatabaseQueue(filename: "test", configuration: config)) + try test(makeDatabasePool(filename: "test", configuration: config)) + try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) + } + + func test_readonly_failure_immediateScheduling() throws { + _ = try makeDatabasePool(filename: "test") + + func test(_ dbReader: DatabaseReader) throws { + struct TestError: Error { } + let logger = TestStream() + let observation = ValueObservation + .tracking { _ in throw TestError() } + .print(to: logger) + + let expectation = self.expectation(description: "") + let cancellable = observation.start( + in: dbReader, + scheduling: .immediate, + onError: { _ in expectation.fulfill() }, + onChange: { _ in }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger.strings, [ + "start", + "fetch", + "error: TestError()"]) + } + } + + var config = dbConfiguration! + config.readonly = true + try test(makeDatabaseQueue(filename: "test", configuration: config)) + try test(makeDatabasePool(filename: "test", configuration: config)) + try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) + } + + // MARK: - Writeonly + + func test_writeonly_success_asynchronousScheduling() throws { + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") + } + + let logger = TestStream() + var observation = ValueObservation + .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .print(to: logger) + observation.requiresWriteAccess = true + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 2 + let cancellable = observation.start( + in: dbWriter, + scheduling: .async(onQueue: .main), + onError: { _ in }, + onChange: { _ in + try! dbWriter.write { db in + try db.execute(sql: "INSERT INTO player DEFAULT VALUES") + } + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger.strings.prefix(7), [ + "start", + "fetch", + "tracked region: player(*)", + "value: 0", + "database did change", + "fetch", + "value: 1"]) + } + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func test_writeonly_success_immediateScheduling() throws { + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") + } + + let logger = TestStream() + var observation = ValueObservation + .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .print(to: logger) + observation.requiresWriteAccess = true + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 2 + let cancellable = observation.start( + in: dbWriter, + scheduling: .immediate, + onError: { _ in }, + onChange: { _ in + try! dbWriter.write { db in + try db.execute(sql: "INSERT INTO player DEFAULT VALUES") + } + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger.strings.prefix(7), [ + "start", + "fetch", + "tracked region: player(*)", + "value: 0", + "database did change", + "fetch", + "value: 1"]) + } + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func test_writeonlyLate_immediateFailure_asynchronousScheduling() throws { + func test(_ dbWriter: DatabaseWriter) throws { + let logger = TestStream() + var observation = ValueObservation + .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .print(to: logger) + observation.requiresWriteAccess = true + + let expectation = self.expectation(description: "") + let cancellable = observation.start( + in: dbWriter, + scheduling: .async(onQueue: .main), + onError: { _ in expectation.fulfill() }, + onChange: { _ in }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger.strings, [ + "start", + "fetch", + "error: SQLite error 1 with statement `SELECT COUNT(*) FROM player`: no such table: player"]) + } + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func test_writeonlyLate_immediateFailure_immediateScheduling() throws { + func test(_ dbWriter: DatabaseWriter) throws { + let logger = TestStream() + var observation = ValueObservation + .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .print(to: logger) + observation.requiresWriteAccess = true + + let expectation = self.expectation(description: "") + let cancellable = observation.start( + in: dbWriter, + scheduling: .immediate, + onError: { _ in expectation.fulfill() }, + onChange: { _ in }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger.strings, [ + "start", + "fetch", + "error: SQLite error 1 with statement `SELECT COUNT(*) FROM player`: no such table: player"]) + } + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func test_writeonlyLate_lateFailure_asynchronousScheduling() throws { + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") + } + + let logger = TestStream() + var observation = ValueObservation + .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .print(to: logger) + observation.requiresWriteAccess = true + + let expectation = self.expectation(description: "") + let cancellable = observation.start( + in: dbWriter, + scheduling: .async(onQueue: .main), + onError: { _ in expectation.fulfill() }, + onChange: { _ in + try! dbWriter.write { db in + try db.execute(sql: """ + INSERT INTO player DEFAULT VALUES; + DROP TABLE player; + """) + } + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger.strings, [ + "start", + "fetch", + "tracked region: player(*)", + "value: 0", + "database did change", + "fetch", + "error: SQLite error 1 with statement `SELECT COUNT(*) FROM player`: no such table: player"]) + } + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func test_writeonlyLate_lateFailure_immediateScheduling() throws { + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") + } + + let logger = TestStream() + var observation = ValueObservation + .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .print(to: logger) + observation.requiresWriteAccess = true + + let expectation = self.expectation(description: "") + let cancellable = observation.start( + in: dbWriter, + scheduling: .immediate, + onError: { _ in expectation.fulfill() }, + onChange: { _ in + try! dbWriter.write { db in + try db.execute(sql: """ + INSERT INTO player DEFAULT VALUES; + DROP TABLE player; + """) + } + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger.strings, [ + "start", + "fetch", + "tracked region: player(*)", + "value: 0", + "database did change", + "fetch", + "error: SQLite error 1 with statement `SELECT COUNT(*) FROM player`: no such table: player"]) + } + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + // MARK: - Concurrent + + func test_concurrent_success_asynchronousScheduling() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") + } + + let logger = TestStream() + // 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 player DEFAULT VALUES; + DELETE FROM player; + """) + } + } + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player")! + }) + .print(to: logger) + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 2 + let cancellable = observation.start( + in: dbPool, + scheduling: .async(onQueue: .main), + onError: { _ in }, + onChange: { _ in expectation.fulfill() }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger.strings, [ + "start", + "fetch", + "tracked region: player(*)", + "value: 0", + "database did change", + "fetch", + "value: 0"]) + } + } + + func test_concurrent_success_immediateScheduling() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") + } + + let logger = TestStream() + // 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 player DEFAULT VALUES; + DELETE FROM player; + """) + } + } + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player")! + }) + .print(to: logger) + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 2 + let cancellable = observation.start( + in: dbPool, + scheduling: .immediate, + onError: { _ in }, + onChange: { _ in expectation.fulfill() }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger.strings, [ + "start", + "fetch", + "tracked region: player(*)", + "value: 0", + "database did change", + "fetch", + "value: 0"]) + } + } + + // MARK: - Varying Database Region + + func test_varyingRegion() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: """ + CREATE TABLE a(id INTEGER PRIMARY KEY); + CREATE TABLE b(id INTEGER PRIMARY KEY); + CREATE TABLE choice(t TEXT); + INSERT INTO choice (t) VALUES ('a'); + """) + } + + let logger = TestStream() + let observation = ValueObservation + .trackingVaryingRegion({ db -> Int in + let table = try String.fetchOne(db, sql: "SELECT t FROM choice")! + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM \(table)")! + }) + .print(to: logger) + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 3 + let cancellable = observation.start( + in: dbQueue, + scheduling: .async(onQueue: .main), + onError: { _ in }, + onChange: { _ in + try! dbQueue.write { db in + try db.execute(sql: """ + UPDATE choice SET t = 'b'; + INSERT INTO a DEFAULT VALUES; + INSERT INTO b DEFAULT VALUES; + """) + } + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger.strings.prefix(11), [ + "start", + "fetch", + "tracked region: a(*),choice(t)", + "value: 0", + "database did change", + "fetch", + "tracked region: b(*),choice(t)", + "value: 1", + "database did change", + "fetch", + "value: 2"]) + } + } +} From 5c4b282e27b4d30f296a81ad203c4aa761b5ff0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Jun 2020 09:17:12 +0200 Subject: [PATCH 04/14] Refactor ValueObservation events handling --- GRDB/Core/DatabasePool.swift | 26 +++- GRDB/Core/DatabaseQueue.swift | 13 +- GRDB/Core/DatabaseReader.swift | 18 ++- GRDB/Core/DatabaseSnapshot.swift | 8 +- GRDB/Core/DatabaseWriter.swift | 16 ++- GRDB/Utils/Utils.swift | 36 ++--- GRDB/ValueObservation/ValueObservation.swift | 51 ++++--- GRDB/ValueObservation/ValueObserver.swift | 17 ++- .../ValueObservation/ValueReducer/Trace.swift | 7 +- README.md | 3 +- .../ValueObservationPrintTests.swift | 136 ++++++++++++------ 11 files changed, 221 insertions(+), 110 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index b0849fb3c..c87f68af4 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -808,19 +808,29 @@ extension DatabasePool: DatabaseReader { /// :nodoc: public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler) + scheduling scheduler: ValueObservationScheduler, + onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable { if configuration.readonly { - return _addReadOnly(observation: observation, scheduling: scheduler) + return _addReadOnly( + observation: observation, + scheduling: scheduler, + onChange: onChange) } if observation.requiresWriteAccess { - let observer = _addWriteOnly( observation: observation, scheduling: scheduler) + let observer = _addWriteOnly( + observation: observation, + scheduling: scheduler, + onChange: onChange) return AnyDatabaseCancellable(cancel: observer.cancel) } - let observer = _addConcurrent( observation: observation, scheduling: scheduler) + let observer = _addConcurrent( + observation: observation, + scheduling: scheduler, + onChange: onChange) return AnyDatabaseCancellable(cancel: observer.cancel) } @@ -828,7 +838,8 @@ extension DatabasePool: DatabaseReader { /// the writer. private func _addConcurrent( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler) + scheduling scheduler: ValueObservationScheduler, + onChange: @escaping (Reducer.Value) -> Void) -> ValueObserver // For testability { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") @@ -841,7 +852,8 @@ extension DatabasePool: DatabaseReader { observation: observation, writer: self, scheduler: scheduler, - reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel)) + reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel), + onChange: onChange) // Starting a concurrent observation means that we'll fetch the initial // value right away, without waiting for an access to the writer queue, @@ -882,7 +894,7 @@ extension DatabasePool: DatabaseReader { do { let initialSnapshot = try makeSnapshot() let initialValue = try initialSnapshot.read(observer.fetchInitialValue) - observation.events.onValue?(initialValue) + onChange(initialValue) add(observer: observer, from: initialSnapshot) } catch { observer.complete() diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index f256b1384..b3d7db68f 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -475,14 +475,21 @@ extension DatabaseQueue { /// :nodoc: public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler) + scheduling scheduler: ValueObservationScheduler, + onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable { if configuration.readonly { - return _addReadOnly(observation: observation, scheduling: scheduler) + return _addReadOnly( + observation: observation, + scheduling: scheduler, + onChange: onChange) } - let observer = _addWriteOnly(observation: observation, scheduling: scheduler) + let observer = _addWriteOnly( + observation: observation, + scheduling: scheduler, + onChange: onChange) return AnyDatabaseCancellable(cancel: observer.cancel) } } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 5502801ab..5311ed1ac 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -251,7 +251,8 @@ public protocol DatabaseReader: AnyObject { /// :nodoc: func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler) + scheduling scheduler: ValueObservationScheduler, + onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable } @@ -295,13 +296,14 @@ extension DatabaseReader { /// initial value. func _addReadOnly( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler) + scheduling scheduler: ValueObservationScheduler, + onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable { if scheduler.immediateInitialValue() { do { let value = try unsafeReentrantRead(observation.fetchValue) - observation.events.onValue?(value) + onChange(value) } catch { observation.events.onError?(error) } @@ -321,7 +323,7 @@ extension DatabaseReader { scheduler.schedule { guard !isCancelled else { return } do { - try observation.events.onValue?(result.get()) + try onChange(result.get()) } catch { observation.events.onError?(error) } @@ -412,9 +414,13 @@ public final class AnyDatabaseReader: DatabaseReader { /// :nodoc: public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler) + scheduling scheduler: ValueObservationScheduler, + onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable { - base._add(observation: observation, scheduling: scheduler) + base._add( + observation: observation, + scheduling: scheduler, + onChange: onChange) } } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 8e1ef093d..52158d129 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -131,9 +131,13 @@ extension DatabaseSnapshot { /// :nodoc: public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler) + scheduling scheduler: ValueObservationScheduler, + onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable { - _addReadOnly(observation: observation, scheduling: scheduler) + _addReadOnly( + observation: observation, + scheduling: scheduler, + onChange: onChange) } } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 61cdf6b4b..de32fdef9 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -311,7 +311,8 @@ extension DatabaseWriter { /// A write-only observation only uses the serialized writer func _addWriteOnly( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler) + scheduling scheduler: ValueObservationScheduler, + onChange: @escaping (Reducer.Value) -> Void) -> ValueObserver // For testability { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") @@ -323,7 +324,8 @@ extension DatabaseWriter { observation: observation, writer: self, scheduler: scheduler, - reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel)) + reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel), + onChange: onChange) if scheduler.immediateInitialValue() { do { @@ -332,7 +334,7 @@ extension DatabaseWriter { db.add(transactionObserver: observer, extent: .observerLifetime) return initialValue } - observation.events.onValue?(initialValue) + onChange(initialValue) } catch { observer.complete() observation.events.onError?(error) @@ -524,9 +526,13 @@ public final class AnyDatabaseWriter: DatabaseWriter { /// :nodoc: public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler) + scheduling scheduler: ValueObservationScheduler, + onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable { - base._add(observation: observation, scheduling: scheduler) + base._add( + observation: observation, + scheduling: scheduler, + onChange: onChange) } } diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 20acae90f..878b9dedc 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -141,32 +141,32 @@ struct PrintOutputStream: TextOutputStream { } } -func appendHandler(_ rhs: (() -> Void)?) -> ((() -> Void)?) -> (() -> Void)? { - guard let rhs = rhs else { - return { $0 } - } - return { lhs in - guard let lhs = lhs else { - return rhs - } +/// Concatenates two functions +func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? { + switch (rhs, lhs) { + case let (rhs, nil): + return rhs + case let (nil, lhs): + return lhs + case let (rhs?, lhs?): return { - lhs() rhs() + lhs() } } } -func appendHandler(_ rhs: ((T) -> Void)?) -> (((T) -> Void)?) -> ((T) -> Void)? { - guard let rhs = rhs else { - return { $0 } - } - return { lhs in - guard let lhs = lhs else { - return rhs - } +/// Concatenates two functions +func concat(_ rhs: ((T) -> Void)?, _ lhs: ((T) -> Void)?) -> ((T) -> Void)? { + switch (rhs, lhs) { + case let (rhs, nil): + return rhs + case let (nil, lhs): + return lhs + case let (rhs?, lhs?): return { - lhs($0) rhs($0) + lhs($0) } } } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 21885129c..ad154f74d 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -16,7 +16,7 @@ import Dispatch /// print("Players have changed.") /// }) public struct ValueObservation { - var events = ValueObservationEvents() + var events = ValueObservationEvents() /// The reducer is created when observation starts, and is triggered upon /// each database change. @@ -34,16 +34,16 @@ public struct ValueObservation { func mapReducer(_ transform: @escaping (Reducer) -> R) -> ValueObservation { let makeReducer = self.makeReducer return ValueObservation( + events: events, makeReducer: { transform(makeReducer()) }, requiresWriteAccess: requiresWriteAccess) } } -struct ValueObservationEvents: Refinable { +struct ValueObservationEvents: Refinable { var onStart: (() -> Void)? var onTrackedRegion: ((DatabaseRegion) -> Void)? var onDatabaseChange: (() -> Void)? - var onValue: ((Value) -> Void)? var onError: ((Error) -> Void)? var onCancel: (() -> Void)? } @@ -99,13 +99,14 @@ extension ValueObservation: Refinable { onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable { - let observation = map(\.events) { eventHandler in - eventHandler - .map(\.onValue, appendHandler(onChange)) - .map(\.onError, appendHandler(onError)) + let observation = map(\.events) { events in + events.map(\.onError) { concat($0, onError) } } observation.events.onStart?() - return reader._add(observation: observation, scheduling: scheduler) + return reader._add( + observation: observation, + scheduling: scheduler, + onChange: onChange) } // MARK: - Debugging @@ -121,8 +122,10 @@ extension ValueObservation: Refinable { /// was impacted by a database change. Defaults to `nil`. /// - onFetch: A closure that executes when the observed value is /// fetched. Defaults to `nil`. - /// - onValue: A closure that executes when the observation notifies a - /// fresh value. Defaults to `nil`. + /// - onValue: A closure that executes on fresh values. Defaults + /// to `nil`. + /// + /// NOTE: This closure runs on an unspecified DispatchQueue. /// - onError: A closure that executes when the observation fails. /// Defaults to `nil`. /// - onCancel: A closure that executes when the observation is @@ -140,16 +143,24 @@ extension ValueObservation: Refinable { -> ValueObservation> { self - .mapReducer { ValueReducers.Trace(base: $0, onFetch: onFetch ?? { }) } - .map(\.events) { eventHandler in - eventHandler - .map(\.onStart, appendHandler(onStart)) - .map(\.onTrackedRegion, appendHandler(onTrackedRegion)) - .map(\.onDatabaseChange, appendHandler(onDatabaseChange)) - .map(\.onValue, appendHandler(onValue)) - .map(\.onError, appendHandler(onError)) - .map(\.onCancel, appendHandler(onCancel)) - } + .mapReducer({ reducer in + ValueReducers.Trace( + base: reducer, + // Adding the onFetch handler to the reducer is handy: we + // are sure not to miss any fetch. + onFetch: onFetch ?? { }, + // Adding the onValue handler to the reducer is necessary: + // the type of the value may change with the `map` operator. + onValue: onValue ?? { _ in }) + }) + .map(\.events, { events in + events + .map(\.onStart) { concat($0, onStart) } + .map(\.onTrackedRegion) { concat($0, onTrackedRegion) } + .map(\.onDatabaseChange) { concat($0, onDatabaseChange) } + .map(\.onError) { concat($0, onError) } + .map(\.onCancel) { concat($0, onCancel) } + }) } /// Prints log messages for all ValueObservation events. diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index 7a9045cb7..33abe0114 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -15,7 +15,7 @@ final class ValueObserver { } } var isCompleted: Bool { synchronized { _isCompleted } } - let events: ValueObservationEvents + let events: ValueObservationEvents private var _isCompleted = false private var reducer: Reducer private let requiresWriteAccess: Bool @@ -23,15 +23,17 @@ final class ValueObserver { private let scheduler: ValueObservationScheduler private let reduceQueue: DispatchQueue private var isChanged = false + private let onChange: (Reducer.Value) -> Void private var lock = NSRecursiveLock() // protects _isCompleted init( - events: ValueObservationEvents, + events: ValueObservationEvents, reducer: Reducer, requiresWriteAccess: Bool, writer: DatabaseWriter, scheduler: ValueObservationScheduler, - reduceQueue: DispatchQueue) + reduceQueue: DispatchQueue, + onChange: @escaping (Reducer.Value) -> Void) { self.events = events self.reducer = reducer @@ -39,13 +41,15 @@ final class ValueObserver { self.writer = writer self.scheduler = scheduler self.reduceQueue = reduceQueue + self.onChange = onChange } convenience init( observation: ValueObservation, writer: DatabaseWriter, scheduler: ValueObservationScheduler, - reduceQueue: DispatchQueue) + reduceQueue: DispatchQueue, + onChange: @escaping (Reducer.Value) -> Void) { self.init( events: observation.events, @@ -53,7 +57,8 @@ final class ValueObserver { requiresWriteAccess: observation.requiresWriteAccess, writer: writer, scheduler: scheduler, - reduceQueue: reduceQueue) + reduceQueue: reduceQueue, + onChange: onChange) } } @@ -162,7 +167,7 @@ extension ValueObserver { if isCompleted { return } scheduler.schedule { if self.isCompleted { return } - self.events.onValue?(value) + self.onChange(value) } } diff --git a/GRDB/ValueObservation/ValueReducer/Trace.swift b/GRDB/ValueObservation/ValueReducer/Trace.swift index d46334f62..80e749b37 100644 --- a/GRDB/ValueObservation/ValueReducer/Trace.swift +++ b/GRDB/ValueObservation/ValueReducer/Trace.swift @@ -5,6 +5,7 @@ extension ValueReducers { public struct Trace: _ValueReducer { var base: Base let onFetch: () -> Void + let onValue: (Base.Value) -> Void public var isSelectedRegionDeterministic: Bool { base.isSelectedRegionDeterministic } public func fetch(_ db: Database) throws -> Base.Fetched { @@ -13,7 +14,11 @@ extension ValueReducers { } public mutating func value(_ fetched: Base.Fetched) -> Base.Value? { - base.value(fetched) + guard let value = base.value(fetched) else { + return nil + } + onValue(value) + return value } } } diff --git a/README.md b/README.md index 046d85353..38cd226be 100644 --- a/README.md +++ b/README.md @@ -5593,7 +5593,8 @@ let observation = ValueObservation // The observation performs a database fetch. }, onValue: { value in - // The observation notifies a fresh value. + // A fresh value was observed. + // NOTE: This closure runs on an unspecified DispatchQueue. }, onError: { error in // The observation completes with an error. diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index 9b4f323d0..7cd52686a 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -10,6 +10,16 @@ class ValueObservationPrintTests: GRDBTestCase { } } + /// Helps dealing with various SQLite versions + private func region(sql: String, in dbReader: DatabaseReader) throws -> String { + try dbReader.read { db in + try db + .makeSelectStatement(sql: sql) + .databaseRegion + .description + } + } + // MARK: - Readonly func test_readonly_success_asynchronousScheduling() throws { @@ -21,7 +31,7 @@ class ValueObservationPrintTests: GRDBTestCase { func test(_ dbReader: DatabaseReader) throws { let logger = TestStream() let observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) let expectation = self.expectation(description: "") @@ -35,7 +45,7 @@ class ValueObservationPrintTests: GRDBTestCase { XCTAssertEqual(logger.strings, [ "start", "fetch", - "value: 0"]) + "value: nil"]) } } @@ -55,7 +65,7 @@ class ValueObservationPrintTests: GRDBTestCase { func test(_ dbReader: DatabaseReader) throws { let logger = TestStream() let observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) let expectation = self.expectation(description: "") @@ -69,7 +79,7 @@ class ValueObservationPrintTests: GRDBTestCase { XCTAssertEqual(logger.strings, [ "start", "fetch", - "value: 0"]) + "value: nil"]) } } @@ -154,10 +164,11 @@ class ValueObservationPrintTests: GRDBTestCase { let logger = TestStream() var observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) observation.requiresWriteAccess = true + let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbWriter) let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 let cancellable = observation.start( @@ -175,11 +186,11 @@ class ValueObservationPrintTests: GRDBTestCase { XCTAssertEqual(logger.strings.prefix(7), [ "start", "fetch", - "tracked region: player(*)", - "value: 0", + "value: nil", + "tracked region: \(expectedRegion)", "database did change", "fetch", - "value: 1"]) + "value: Optional(1)"]) } } @@ -195,10 +206,11 @@ class ValueObservationPrintTests: GRDBTestCase { let logger = TestStream() var observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) observation.requiresWriteAccess = true + let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbWriter) let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 let cancellable = observation.start( @@ -216,11 +228,11 @@ class ValueObservationPrintTests: GRDBTestCase { XCTAssertEqual(logger.strings.prefix(7), [ "start", "fetch", - "tracked region: player(*)", - "value: 0", + "value: nil", + "tracked region: \(expectedRegion)", "database did change", "fetch", - "value: 1"]) + "value: Optional(1)"]) } } @@ -232,7 +244,7 @@ class ValueObservationPrintTests: GRDBTestCase { func test(_ dbWriter: DatabaseWriter) throws { let logger = TestStream() var observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) observation.requiresWriteAccess = true @@ -247,7 +259,7 @@ class ValueObservationPrintTests: GRDBTestCase { XCTAssertEqual(logger.strings, [ "start", "fetch", - "error: SQLite error 1 with statement `SELECT COUNT(*) FROM player`: no such table: player"]) + "error: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"]) } } @@ -259,7 +271,7 @@ class ValueObservationPrintTests: GRDBTestCase { func test(_ dbWriter: DatabaseWriter) throws { let logger = TestStream() var observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) observation.requiresWriteAccess = true @@ -274,7 +286,7 @@ class ValueObservationPrintTests: GRDBTestCase { XCTAssertEqual(logger.strings, [ "start", "fetch", - "error: SQLite error 1 with statement `SELECT COUNT(*) FROM player`: no such table: player"]) + "error: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"]) } } @@ -290,10 +302,11 @@ class ValueObservationPrintTests: GRDBTestCase { let logger = TestStream() var observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) observation.requiresWriteAccess = true + let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbWriter) let expectation = self.expectation(description: "") let cancellable = observation.start( in: dbWriter, @@ -312,11 +325,11 @@ class ValueObservationPrintTests: GRDBTestCase { XCTAssertEqual(logger.strings, [ "start", "fetch", - "tracked region: player(*)", - "value: 0", + "value: nil", + "tracked region: \(expectedRegion)", "database did change", "fetch", - "error: SQLite error 1 with statement `SELECT COUNT(*) FROM player`: no such table: player"]) + "error: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"]) } } @@ -332,10 +345,11 @@ class ValueObservationPrintTests: GRDBTestCase { let logger = TestStream() var observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM player")! } + .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) observation.requiresWriteAccess = true + let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbWriter) let expectation = self.expectation(description: "") let cancellable = observation.start( in: dbWriter, @@ -354,11 +368,11 @@ class ValueObservationPrintTests: GRDBTestCase { XCTAssertEqual(logger.strings, [ "start", "fetch", - "tracked region: player(*)", - "value: 0", + "value: nil", + "tracked region: \(expectedRegion)", "database did change", "fetch", - "error: SQLite error 1 with statement `SELECT COUNT(*) FROM player`: no such table: player"]) + "error: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"]) } } @@ -380,7 +394,7 @@ class ValueObservationPrintTests: GRDBTestCase { // transaction observer, some write did happen. var needsChange = true let observation = ValueObservation - .tracking({ db -> Int in + .tracking({ db -> Int? in if needsChange { needsChange = false try dbPool.write { db in @@ -390,10 +404,11 @@ class ValueObservationPrintTests: GRDBTestCase { """) } } - return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player")! + return try Int.fetchOne(db, sql: "SELECT MAX(id) FROM player") }) .print(to: logger) + let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbPool) let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 let cancellable = observation.start( @@ -406,11 +421,11 @@ class ValueObservationPrintTests: GRDBTestCase { XCTAssertEqual(logger.strings, [ "start", "fetch", - "tracked region: player(*)", - "value: 0", + "value: nil", + "tracked region: \(expectedRegion)", "database did change", "fetch", - "value: 0"]) + "value: nil"]) } } @@ -426,7 +441,7 @@ class ValueObservationPrintTests: GRDBTestCase { // transaction observer, some write did happen. var needsChange = true let observation = ValueObservation - .tracking({ db -> Int in + .tracking({ db -> Int? in if needsChange { needsChange = false try dbPool.write { db in @@ -436,10 +451,11 @@ class ValueObservationPrintTests: GRDBTestCase { """) } } - return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player")! + return try Int.fetchOne(db, sql: "SELECT MAX(id) FROM player") }) .print(to: logger) + let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbPool) let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 let cancellable = observation.start( @@ -452,11 +468,11 @@ class ValueObservationPrintTests: GRDBTestCase { XCTAssertEqual(logger.strings, [ "start", "fetch", - "tracked region: player(*)", - "value: 0", + "value: nil", + "tracked region: \(expectedRegion)", "database did change", "fetch", - "value: 0"]) + "value: nil"]) } } @@ -475,12 +491,14 @@ class ValueObservationPrintTests: GRDBTestCase { let logger = TestStream() let observation = ValueObservation - .trackingVaryingRegion({ db -> Int in + .trackingVaryingRegion({ db -> Int? in let table = try String.fetchOne(db, sql: "SELECT t FROM choice")! - return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM \(table)")! + return try Int.fetchOne(db, sql: "SELECT MAX(id) FROM \(table)") }) .print(to: logger) + let expectedRegionA = try region(sql: "SELECT MAX(id) FROM a", in: dbQueue) + let expectedRegionB = try region(sql: "SELECT MAX(id) FROM b", in: dbQueue) let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 3 let cancellable = observation.start( @@ -502,15 +520,51 @@ class ValueObservationPrintTests: GRDBTestCase { XCTAssertEqual(logger.strings.prefix(11), [ "start", "fetch", - "tracked region: a(*),choice(t)", - "value: 0", + "value: nil", + "tracked region: \(expectedRegionA),choice(t)", "database did change", "fetch", - "tracked region: b(*),choice(t)", - "value: 1", + "tracked region: \(expectedRegionB),choice(t)", + "value: Optional(1)", "database did change", "fetch", - "value: 2"]) + "value: Optional(2)"]) + } + } + + // MARK: - Chains + + func test_chain() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") + } + + let logger1 = TestStream() + let logger2 = TestStream() + let observation = ValueObservation + .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } + .print(to: logger1) + .removeDuplicates() + .map { _ in "foo" } + .print("prefix", to: logger2) + + let expectation = self.expectation(description: "") + let cancellable = observation.start( + in: dbQueue, + scheduling: .async(onQueue: .main), + onError: { _ in }, + onChange: { _ in expectation.fulfill() }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger1.strings.prefix(3), [ + "start", + "fetch", + "value: nil"]) + XCTAssertEqual(logger2.strings.prefix(3), [ + "prefix: start", + "prefix: fetch", + "prefix: value: foo"]) } } } From 42cd8881a2c8025d4c900127238f588c8575725f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Jun 2020 10:14:41 +0200 Subject: [PATCH 05/14] ValueObserver.observedRegion can now be private --- GRDB/ValueObservation/ValueObserver.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index 33abe0114..f5169a759 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -3,7 +3,9 @@ import Foundation /// Support for ValueObservation. /// See DatabaseWriter.add(observation:onError:onChange:) final class ValueObserver { - private(set) var observedRegion: DatabaseRegion? { // internal for testability + var isCompleted: Bool { synchronized { _isCompleted } } + let events: ValueObservationEvents + private var observedRegion: DatabaseRegion? { didSet { if let onTrackedRegion = events.onTrackedRegion, @@ -14,8 +16,6 @@ final class ValueObserver { } } } - var isCompleted: Bool { synchronized { _isCompleted } } - let events: ValueObservationEvents private var _isCompleted = false private var reducer: Reducer private let requiresWriteAccess: Bool From 07de1d0105ea385ca563fc0f32132c10a1be3bd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Jun 2020 11:13:59 +0200 Subject: [PATCH 06/14] More ValueObservation event tests --- .../ValueObservationPrintTests.swift | 168 ++++++++++++++++-- 1 file changed, 155 insertions(+), 13 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index 7cd52686a..d65af66b8 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -240,7 +240,7 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabasePool()) } - func test_writeonlyLate_immediateFailure_asynchronousScheduling() throws { + func test_writeonly_immediateFailure_asynchronousScheduling() throws { func test(_ dbWriter: DatabaseWriter) throws { let logger = TestStream() var observation = ValueObservation @@ -267,7 +267,7 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabasePool()) } - func test_writeonlyLate_immediateFailure_immediateScheduling() throws { + func test_writeonly_immediateFailure_immediateScheduling() throws { func test(_ dbWriter: DatabaseWriter) throws { let logger = TestStream() var observation = ValueObservation @@ -294,7 +294,7 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabasePool()) } - func test_writeonlyLate_lateFailure_asynchronousScheduling() throws { + func test_writeonly_lateFailure_asynchronousScheduling() throws { func test(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") @@ -337,7 +337,7 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabasePool()) } - func test_writeonlyLate_lateFailure_immediateScheduling() throws { + func test_writeonly_lateFailure_immediateScheduling() throws { func test(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") @@ -532,9 +532,9 @@ class ValueObservationPrintTests: GRDBTestCase { } } - // MARK: - Chains + // MARK: - Variations - func test_chain() throws { + func test_prefix() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") @@ -544,10 +544,8 @@ class ValueObservationPrintTests: GRDBTestCase { let logger2 = TestStream() let observation = ValueObservation .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } - .print(to: logger1) - .removeDuplicates() - .map { _ in "foo" } - .print("prefix", to: logger2) + .print("", to: logger1) + .print("log", to: logger2) let expectation = self.expectation(description: "") let cancellable = observation.start( @@ -562,9 +560,153 @@ class ValueObservationPrintTests: GRDBTestCase { "fetch", "value: nil"]) XCTAssertEqual(logger2.strings.prefix(3), [ - "prefix: start", - "prefix: fetch", - "prefix: value: foo"]) + "log: start", + "log: fetch", + "log: value: foo"]) } } + + func test_chain() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") + } + + let logger1 = TestStream() + let logger2 = TestStream() + let observation = ValueObservation + .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } + .print(to: logger1) + .removeDuplicates() + .map { _ in "foo" } + .print(to: logger2) + + let expectation = self.expectation(description: "") + let cancellable = observation.start( + in: dbQueue, + scheduling: .async(onQueue: .main), + onError: { _ in }, + onChange: { _ in expectation.fulfill() }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(logger1.strings.prefix(3), [ + "start", + "fetch", + "value: nil"]) + XCTAssertEqual(logger2.strings.prefix(3), [ + "start", + "fetch", + "value: foo"]) + } + } + + func test_handleEvents() throws { + func waitFor(_ observation: ValueObservation) throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") + } + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 2 + let cancellable = observation.start( + in: dbQueue, + scheduling: .async(onQueue: .main), + onError: { _ in }, + onChange: { _ in + try! dbQueue.write { db in + try db.execute(sql: "INSERT INTO player DEFAULT VALUES") + } + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + } + } + + func waitForError(_ observation: ValueObservation) throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") + } + + let expectation = self.expectation(description: "") + let cancellable = observation.start( + in: dbQueue, + scheduling: .async(onQueue: .main), + onError: { _ in expectation.fulfill() }, + onChange: { _ in + try! dbQueue.write { db in + try db.execute(sql: """ + INSERT INTO player DEFAULT VALUES; + DROP TABLE player; + """) + } + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + } + } + + func waitForCancel(_ observation: ValueObservation) throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") + } + + let expectation = self.expectation(description: "") + let cancellable = observation.start( + in: dbQueue, + scheduling: .async(onQueue: .main), + onError: { _ in }, + onChange: { _ in + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + cancellable.cancel() + } + } + + let observation = ValueObservation.tracking { + try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") + } + + do { + let logger = TestStream() + try waitFor(observation.handleEvents(onStart: { logger.write("start") })) + XCTAssertEqual(logger.strings, ["start"]) + } + do { + let logger = TestStream() + try waitFor(observation.handleEvents(onTrackedRegion: { _ in logger.write("region") })) + XCTAssertEqual(logger.strings, ["region"]) + } + do { + let logger = TestStream() + try waitFor(observation.handleEvents(onDatabaseChange: { logger.write("change") })) + XCTAssertEqual(logger.strings.prefix(1), ["change"]) + } + do { + let logger = TestStream() + try waitFor(observation.handleEvents(onFetch: { logger.write("fetch") })) + XCTAssertEqual(logger.strings.prefix(2), ["fetch", "fetch"]) + } + do { + let logger = TestStream() + try waitFor(observation.handleEvents(onValue: { _ in logger.write("value") })) + XCTAssertEqual(logger.strings.prefix(2), ["value", "value"]) + } + do { + let logger = TestStream() + try waitForError(observation.handleEvents(onError: { _ in logger.write("error") })) + XCTAssertEqual(logger.strings, ["error"]) + } + do { + let logger = TestStream() + try waitFor(observation.handleEvents(onCancel: { logger.write("cancel") })) + XCTAssertEqual(logger.strings, ["cancel"]) + } + } + } From 006492a02cb1e14f7b9e9d591ef76ba64dcd1b10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Jun 2020 11:17:34 +0200 Subject: [PATCH 07/14] CHANGELOG --- CHANGELOG.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d07e9c987..d3b1c8e5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,7 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. - #### 5.x Releases @@ -70,9 +68,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... - + +- **New**: [#798](https://github.com/groue/GRDB.swift/pull/798): Debugging operators for ValueObservation ## 5.0.0-beta.5 From 9e37b6b68e70b232e44b96736f04a7fded1b85b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Jun 2020 11:20:07 +0200 Subject: [PATCH 08/14] CHANGELOG --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3b1c8e5e..38e3da85a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,6 +72,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: [#798](https://github.com/groue/GRDB.swift/pull/798): Debugging operators for ValueObservation +### Documentation Diff + +[ValueObservation Operators](README.md#valueobservation-operators) was extended with the documentation of the two new operators `handleEvents` and `print`. + + ## 5.0.0-beta.5 Released June 15, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.4...v5.0.0-beta.5) From d199f0da836a982843e04fd32fc59af19457a503 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Jun 2020 11:30:50 +0200 Subject: [PATCH 09/14] Cleanup --- Tests/GRDBTests/ValueObservationPrintTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index d65af66b8..9840fb14a 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -704,7 +704,7 @@ class ValueObservationPrintTests: GRDBTestCase { } do { let logger = TestStream() - try waitFor(observation.handleEvents(onCancel: { logger.write("cancel") })) + try waitForCancel(observation.handleEvents(onCancel: { logger.write("cancel") })) XCTAssertEqual(logger.strings, ["cancel"]) } } From 099d5a311e4d4321eeca0c9175e06f2016de6698 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Jun 2020 11:32:43 +0200 Subject: [PATCH 10/14] Cleanup --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 38cd226be..31f826dcc 100644 --- a/README.md +++ b/README.md @@ -5580,16 +5580,16 @@ The `handleEvents` operator lets your application observe the lifetime of a Valu let observation = ValueObservation .tracking { db in ... } .handleEvents( - onStart: { + onStart: { // The observation starts }, onTrackedRegion: { databaseRegion in // The observation starts tracking a database region }, - onDatabaseChange: { + onDatabaseChange: { // The observation was impacted by a database change. }, - onFetch: { + onFetch: { // The observation performs a database fetch. }, onValue: { value in From 0e12a9acba0d0e97037259d28aa5791de4c0deb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Jun 2020 11:36:46 +0200 Subject: [PATCH 11/14] Fix typo --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38e3da85a..75ea11b37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,7 +74,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ### Documentation Diff -[ValueObservation Operators](README.md#valueobservation-operators) was extended with the documentation of the two new operators `handleEvents` and `print`. +[ValueObservation Operators](README.md#valueobservation-operators) was extended with the documentation for the two new operators `handleEvents` and `print`. ## 5.0.0-beta.5 From e7b17ea0a9a182e9faa8faec68665a80bbe4862b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Jun 2020 11:38:40 +0200 Subject: [PATCH 12/14] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 31f826dcc..67507ccbd 100644 --- a/README.md +++ b/README.md @@ -5574,7 +5574,7 @@ 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 ValueObseration: +The `handleEvents` operator lets your application observe the lifetime of a ValueObservation: ```swift let observation = ValueObservation From 54adc18988bb8c2ed628b0ebfac1a533756d8af6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Jun 2020 12:15:43 +0200 Subject: [PATCH 13/14] Fix buggy test --- Tests/GRDBTests/ValueObservationPrintTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index 9840fb14a..bd221d842 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -562,7 +562,7 @@ class ValueObservationPrintTests: GRDBTestCase { XCTAssertEqual(logger2.strings.prefix(3), [ "log: start", "log: fetch", - "log: value: foo"]) + "log: value: nil"]) } } From 4e8b231c42bace6ce0d637de996241a24da0aa69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 22 Jun 2020 14:23:33 +0200 Subject: [PATCH 14/14] Rename handleEvents arguments --- GRDB/Core/DatabasePool.swift | 4 +- GRDB/Core/DatabaseReader.swift | 4 +- GRDB/Core/DatabaseWriter.swift | 2 +- GRDB/ValueObservation/ValueObservation.swift | 76 ++++---- GRDB/ValueObservation/ValueObserver.swift | 10 +- .../ValueObservation/ValueReducer/Trace.swift | 8 +- README.md | 24 +-- .../ValueObservationPrintTests.swift | 164 +++++++++--------- ...ValueObservationRegionRecordingTests.swift | 4 +- Tests/GRDBTests/ValueObservationTests.swift | 2 +- 10 files changed, 149 insertions(+), 149 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index c87f68af4..8cace9c57 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -898,7 +898,7 @@ extension DatabasePool: DatabaseReader { add(observer: observer, from: initialSnapshot) } catch { observer.complete() - observation.events.onError?(error) + observation.events.didFail?(error) } } else { let label = configuration.identifier( @@ -957,7 +957,7 @@ extension DatabasePool: DatabaseReader { } if fetchNeeded { - observer.events.onDatabaseChange?() + observer.events.databaseDidChange?() if let value = try observer.fetchValue(db) { observer.notifyChange(value) } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 5311ed1ac..845d79f30 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -305,7 +305,7 @@ extension DatabaseReader { let value = try unsafeReentrantRead(observation.fetchValue) onChange(value) } catch { - observation.events.onError?(error) + observation.events.didFail?(error) } return AnyDatabaseCancellable(cancel: { }) } else { @@ -325,7 +325,7 @@ extension DatabaseReader { do { try onChange(result.get()) } catch { - observation.events.onError?(error) + observation.events.didFail?(error) } } } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index de32fdef9..6ad451b4b 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -337,7 +337,7 @@ extension DatabaseWriter { onChange(initialValue) } catch { observer.complete() - observation.events.onError?(error) + observation.events.didFail?(error) } } else { _weakAsyncWriteWithoutTransaction { db in diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index ad154f74d..0dff83c2f 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -41,11 +41,11 @@ public struct ValueObservation { } struct ValueObservationEvents: Refinable { - var onStart: (() -> Void)? - var onTrackedRegion: ((DatabaseRegion) -> Void)? - var onDatabaseChange: (() -> Void)? - var onError: ((Error) -> Void)? - var onCancel: (() -> Void)? + var willStart: (() -> Void)? + var willTrackRegion: ((DatabaseRegion) -> Void)? + var databaseDidChange: (() -> Void)? + var didFail: ((Error) -> Void)? + var didCancel: (() -> Void)? } extension ValueObservation: Refinable { @@ -100,9 +100,9 @@ extension ValueObservation: Refinable { onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable { let observation = map(\.events) { events in - events.map(\.onError) { concat($0, onError) } + events.map(\.didFail) { concat($0, onError) } } - observation.events.onStart?() + observation.events.willStart?() return reader._add( observation: observation, scheduling: scheduler, @@ -114,52 +114,52 @@ extension ValueObservation: Refinable { /// Performs the specified closures when ValueObservation events occur. /// /// - parameters: - /// - onStart: A closure that executes when the observation starts. + /// - willStart: A closure that executes when the observation starts. /// Defaults to `nil`. - /// - onTrackedRegion: A closure that executes when the observation + /// - willFetch: A closure that executes when the observed value is + /// about to be fetched. Defaults to `nil`. + /// - willTrackRegion: A closure that executes when the observation /// starts tracking a database region. Defaults to `nil`. - /// - onDatabaseChange: A closure that executes after the observation + /// - databaseDidChange: A closure that executes after the observation /// was impacted by a database change. Defaults to `nil`. - /// - onFetch: A closure that executes when the observed value is - /// fetched. Defaults to `nil`. - /// - onValue: A closure that executes on fresh values. Defaults + /// - didReceiveValue: A closure that executes on fresh values. Defaults /// to `nil`. /// /// NOTE: This closure runs on an unspecified DispatchQueue. - /// - onError: A closure that executes when the observation fails. + /// - didFail: A closure that executes when the observation fails. /// Defaults to `nil`. - /// - onCancel: A closure that executes when the observation is + /// - didCancel: A closure that executes when the observation is /// cancelled. Defaults to `nil`. /// - returns: A `ValueObservation` that performs the specified closures /// when ValueObservation events occur. public func handleEvents( - onStart: (() -> Void)? = nil, - onTrackedRegion: ((DatabaseRegion) -> Void)? = nil, - onDatabaseChange: (() -> Void)? = nil, - onFetch: (() -> Void)? = nil, - onValue: ((Reducer.Value) -> Void)? = nil, - onError: ((Error) -> Void)? = nil, - onCancel: (() -> Void)? = nil) + willStart: (() -> Void)? = nil, + willFetch: (() -> Void)? = nil, + willTrackRegion: ((DatabaseRegion) -> Void)? = nil, + databaseDidChange: (() -> Void)? = nil, + didReceiveValue: ((Reducer.Value) -> Void)? = nil, + didFail: ((Error) -> Void)? = nil, + didCancel: (() -> Void)? = nil) -> ValueObservation> { self .mapReducer({ reducer in ValueReducers.Trace( base: reducer, - // Adding the onFetch handler to the reducer is handy: we + // Adding the willFetch handler to the reducer is handy: we // are sure not to miss any fetch. - onFetch: onFetch ?? { }, - // Adding the onValue handler to the reducer is necessary: + willFetch: willFetch ?? { }, + // Adding the didReceiveValue handler to the reducer is necessary: // the type of the value may change with the `map` operator. - onValue: onValue ?? { _ in }) + didReceiveValue: didReceiveValue ?? { _ in }) }) .map(\.events, { events in events - .map(\.onStart) { concat($0, onStart) } - .map(\.onTrackedRegion) { concat($0, onTrackedRegion) } - .map(\.onDatabaseChange) { concat($0, onDatabaseChange) } - .map(\.onError) { concat($0, onError) } - .map(\.onCancel) { concat($0, onCancel) } + .map(\.willStart) { concat($0, willStart) } + .map(\.willTrackRegion) { concat($0, willTrackRegion) } + .map(\.databaseDidChange) { concat($0, databaseDidChange) } + .map(\.didFail) { concat($0, didFail) } + .map(\.didCancel) { concat($0, didCancel) } }) } @@ -172,13 +172,13 @@ extension ValueObservation: Refinable { let prefix = prefix.isEmpty ? "" : "\(prefix): " var stream = stream ?? PrintOutputStream() return handleEvents( - onStart: { stream.write("\(prefix)start") }, - onTrackedRegion: { stream.write("\(prefix)tracked region: \($0)") }, - onDatabaseChange: { stream.write("\(prefix)database did change") }, - onFetch: { stream.write("\(prefix)fetch") }, - onValue: { stream.write("\(prefix)value: \($0)") }, - onError: { stream.write("\(prefix)error: \($0)") }, - onCancel: { stream.write("\(prefix)cancel") }) + willStart: { stream.write("\(prefix)will start") }, + willFetch: { stream.write("\(prefix)will fetch") }, + willTrackRegion: { stream.write("\(prefix)will track region: \($0)") }, + databaseDidChange: { stream.write("\(prefix)database did change") }, + didReceiveValue: { stream.write("\(prefix)did receive value: \($0)") }, + didFail: { stream.write("\(prefix)did fail: \($0)") }, + didCancel: { stream.write("\(prefix)did cancel") }) } // MARK: - Fetching Values diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index f5169a759..5eb3320f0 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -8,11 +8,11 @@ final class ValueObserver { private var observedRegion: DatabaseRegion? { didSet { if - let onTrackedRegion = events.onTrackedRegion, + let willTrackRegion = events.willTrackRegion, let region = observedRegion, region != oldValue { - onTrackedRegion(region) + willTrackRegion(region) } } } @@ -87,7 +87,7 @@ extension ValueObserver: TransactionObserver { isChanged = false if isCompleted { return } - events.onDatabaseChange?() + events.databaseDidChange?() // 1. Fetch let fetchedValue: DatabaseFuture @@ -158,8 +158,8 @@ extension ValueObserver { func cancel() { synchronized { if _isCompleted { return } - events.onCancel?() complete() + events.didCancel?() } } @@ -183,7 +183,7 @@ extension ValueObserver { } } if shouldNotify { - self.events.onError?(error) + self.events.didFail?(error) } } } diff --git a/GRDB/ValueObservation/ValueReducer/Trace.swift b/GRDB/ValueObservation/ValueReducer/Trace.swift index 80e749b37..8628f2e5d 100644 --- a/GRDB/ValueObservation/ValueReducer/Trace.swift +++ b/GRDB/ValueObservation/ValueReducer/Trace.swift @@ -4,12 +4,12 @@ extension ValueReducers { /// :nodoc: public struct Trace: _ValueReducer { var base: Base - let onFetch: () -> Void - let onValue: (Base.Value) -> Void + let willFetch: () -> Void + let didReceiveValue: (Base.Value) -> Void public var isSelectedRegionDeterministic: Bool { base.isSelectedRegionDeterministic } public func fetch(_ db: Database) throws -> Base.Fetched { - onFetch() + willFetch() return try base.fetch(db) } @@ -17,7 +17,7 @@ extension ValueReducers { guard let value = base.value(fetched) else { return nil } - onValue(value) + didReceiveValue(value) return value } } diff --git a/README.md b/README.md index 67507ccbd..5d336b464 100644 --- a/README.md +++ b/README.md @@ -5580,27 +5580,27 @@ The `handleEvents` operator lets your application observe the lifetime of a Valu let observation = ValueObservation .tracking { db in ... } .handleEvents( - onStart: { - // The observation starts + willStart: { + // The observation starts. }, - onTrackedRegion: { databaseRegion in - // The observation starts tracking a database region + willFetch: { + // The observation will perform a database fetch. }, - onDatabaseChange: { + willTrackRegion: { databaseRegion in + // The observation starts tracking a database region. + }, + databaseDidChange: { // The observation was impacted by a database change. }, - onFetch: { - // The observation performs a database fetch. - }, - onValue: { value in + didReceiveValue: { value in // A fresh value was observed. // NOTE: This closure runs on an unspecified DispatchQueue. }, - onError: { error in + didFail: { error in // The observation completes with an error. }, - onCancel: { - // The observation is cancelled. + didCancel: { + // The observation was cancelled. }) ``` diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index bd221d842..87fe78c3e 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -43,9 +43,9 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger.strings, [ - "start", - "fetch", - "value: nil"]) + "will start", + "will fetch", + "did receive value: nil"]) } } @@ -77,9 +77,9 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger.strings, [ - "start", - "fetch", - "value: nil"]) + "will start", + "will fetch", + "did receive value: nil"]) } } @@ -109,9 +109,9 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger.strings, [ - "start", - "fetch", - "error: TestError()"]) + "will start", + "will fetch", + "did fail: TestError()"]) } } @@ -141,9 +141,9 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger.strings, [ - "start", - "fetch", - "error: TestError()"]) + "will start", + "will fetch", + "did fail: TestError()"]) } } @@ -184,13 +184,13 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger.strings.prefix(7), [ - "start", - "fetch", - "value: nil", - "tracked region: \(expectedRegion)", + "will start", + "will fetch", + "did receive value: nil", + "will track region: \(expectedRegion)", "database did change", - "fetch", - "value: Optional(1)"]) + "will fetch", + "did receive value: Optional(1)"]) } } @@ -226,13 +226,13 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger.strings.prefix(7), [ - "start", - "fetch", - "value: nil", - "tracked region: \(expectedRegion)", + "will start", + "will fetch", + "did receive value: nil", + "will track region: \(expectedRegion)", "database did change", - "fetch", - "value: Optional(1)"]) + "will fetch", + "did receive value: Optional(1)"]) } } @@ -257,9 +257,9 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger.strings, [ - "start", - "fetch", - "error: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"]) + "will start", + "will fetch", + "did fail: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"]) } } @@ -284,9 +284,9 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger.strings, [ - "start", - "fetch", - "error: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"]) + "will start", + "will fetch", + "did fail: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"]) } } @@ -323,13 +323,13 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger.strings, [ - "start", - "fetch", - "value: nil", - "tracked region: \(expectedRegion)", + "will start", + "will fetch", + "did receive value: nil", + "will track region: \(expectedRegion)", "database did change", - "fetch", - "error: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"]) + "will fetch", + "did fail: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"]) } } @@ -366,13 +366,13 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger.strings, [ - "start", - "fetch", - "value: nil", - "tracked region: \(expectedRegion)", + "will start", + "will fetch", + "did receive value: nil", + "will track region: \(expectedRegion)", "database did change", - "fetch", - "error: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"]) + "will fetch", + "did fail: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"]) } } @@ -419,13 +419,13 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger.strings, [ - "start", - "fetch", - "value: nil", - "tracked region: \(expectedRegion)", + "will start", + "will fetch", + "did receive value: nil", + "will track region: \(expectedRegion)", "database did change", - "fetch", - "value: nil"]) + "will fetch", + "did receive value: nil"]) } } @@ -466,13 +466,13 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger.strings, [ - "start", - "fetch", - "value: nil", - "tracked region: \(expectedRegion)", + "will start", + "will fetch", + "did receive value: nil", + "will track region: \(expectedRegion)", "database did change", - "fetch", - "value: nil"]) + "will fetch", + "did receive value: nil"]) } } @@ -518,17 +518,17 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger.strings.prefix(11), [ - "start", - "fetch", - "value: nil", - "tracked region: \(expectedRegionA),choice(t)", + "will start", + "will fetch", + "did receive value: nil", + "will track region: \(expectedRegionA),choice(t)", "database did change", - "fetch", - "tracked region: \(expectedRegionB),choice(t)", - "value: Optional(1)", + "will fetch", + "will track region: \(expectedRegionB),choice(t)", + "did receive value: Optional(1)", "database did change", - "fetch", - "value: Optional(2)"]) + "will fetch", + "did receive value: Optional(2)"]) } } @@ -556,13 +556,13 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger1.strings.prefix(3), [ - "start", - "fetch", - "value: nil"]) + "will start", + "will fetch", + "did receive value: nil"]) XCTAssertEqual(logger2.strings.prefix(3), [ - "log: start", - "log: fetch", - "log: value: nil"]) + "log: will start", + "log: will fetch", + "log: did receive value: nil"]) } } @@ -590,13 +590,13 @@ class ValueObservationPrintTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(logger1.strings.prefix(3), [ - "start", - "fetch", - "value: nil"]) + "will start", + "will fetch", + "did receive value: nil"]) XCTAssertEqual(logger2.strings.prefix(3), [ - "start", - "fetch", - "value: foo"]) + "will start", + "will fetch", + "did receive value: foo"]) } } @@ -674,37 +674,37 @@ class ValueObservationPrintTests: GRDBTestCase { do { let logger = TestStream() - try waitFor(observation.handleEvents(onStart: { logger.write("start") })) + try waitFor(observation.handleEvents(willStart: { logger.write("start") })) XCTAssertEqual(logger.strings, ["start"]) } do { let logger = TestStream() - try waitFor(observation.handleEvents(onTrackedRegion: { _ in logger.write("region") })) + try waitFor(observation.handleEvents(willTrackRegion: { _ in logger.write("region") })) XCTAssertEqual(logger.strings, ["region"]) } do { let logger = TestStream() - try waitFor(observation.handleEvents(onDatabaseChange: { logger.write("change") })) + try waitFor(observation.handleEvents(databaseDidChange: { logger.write("change") })) XCTAssertEqual(logger.strings.prefix(1), ["change"]) } do { let logger = TestStream() - try waitFor(observation.handleEvents(onFetch: { logger.write("fetch") })) + try waitFor(observation.handleEvents(willFetch: { logger.write("fetch") })) XCTAssertEqual(logger.strings.prefix(2), ["fetch", "fetch"]) } do { let logger = TestStream() - try waitFor(observation.handleEvents(onValue: { _ in logger.write("value") })) + try waitFor(observation.handleEvents(didReceiveValue: { _ in logger.write("value") })) XCTAssertEqual(logger.strings.prefix(2), ["value", "value"]) } do { let logger = TestStream() - try waitForError(observation.handleEvents(onError: { _ in logger.write("error") })) + try waitForError(observation.handleEvents(didFail: { _ in logger.write("error") })) XCTAssertEqual(logger.strings, ["error"]) } do { let logger = TestStream() - try waitForCancel(observation.handleEvents(onCancel: { logger.write("cancel") })) + try waitForCancel(observation.handleEvents(didCancel: { logger.write("cancel") })) XCTAssertEqual(logger.strings, ["cancel"]) } } diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index 6593a82f2..e18414a8f 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -141,7 +141,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { let table = try String.fetchOne(db, sql: "SELECT name FROM source")! return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! }) - .handleEvents(onTrackedRegion: { regions.append($0) }) + .handleEvents(willTrackRegion: { regions.append($0) }) let observer = observation.start( in: dbQueue, @@ -192,7 +192,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { let table = try String.fetchOne(db, sql: "SELECT name FROM source")! return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! }) - .handleEvents(onTrackedRegion: { regions.append($0) }) + .handleEvents(willTrackRegion: { regions.append($0) }) let observer = observation.start( in: dbQueue, diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 0b75a7695..a3da023a5 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -94,7 +94,7 @@ class ValueObservationTests: GRDBTestCase { let expectation = self.expectation(description: "") let observation = ValueObservation .tracking(request.fetchAll) - .handleEvents(onTrackedRegion: { + .handleEvents(willTrackRegion: { region = $0 expectation.fulfill() })